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/master | <file_sep>var panes = {};
var Pane = Backbone.View.extend({
events:{
'submit form':'getForm',
'click .btn-ajax':'getLink',
'mouseenter .problem':'problemOver',
'mouseleave .problem':'problemOut',
},
initialize: function(){
this.render();
},
render: function(){
var view = this;
// resize pane to display if needed
this.$(".navbar-fixed-bottom").each(function(){
var paddingBottom = Number(view.$el.css("padding-bottom").replace("px",""));
view.$el.css("padding-bottom",paddingBottom+$(this).outerHeight()+"px");
});
// if div not visable
if(!this.$el.is(':visible')) this.show();
},
getForm: function(event){
event.preventDefault();
var view = this;
var form = $(event.currentTarget);
if(this.model.has("loading")) return false;
this.model.set("loading", true);
form.addClass("loading");
$.ajax({
type:form.attr("method"),
url:form.attr("action"),
data:form.serialize(),
}).always(function(data, textStatus){
form.removeClass("loading");
if(data.responseJSON) data = data.responseJSON;
if(data['content']){
if(form.data("target") == "pane"){
var pane = $(data['content']).insertAfter(view.$el);
view.$el.remove();
view.setElement(pane[0]);
view.render();
}else{
$(data['content']).insertAfter(form);
form.remove();
}
}
view.model.unset("loading");
});
},
getLink: function(event){
event.preventDefault();
var view = this;
var bttn = $(event.currentTarget)
if(bttn.hasClass("loading")) return false;
bttn.addClass("loading")
this.model.loadPage(bttn.attr("href")).always(function(){
bttn.removeClass("loading");
});
},
remove: function(callback){
var view = this;
this.hide(function(){
if(callback) callback();
Backbone.View.prototype.remove.apply(view);
});
},
show: function(callback){
var pane = this;
this.$el.show().css({
'position':'absolute',
'top':this.$el.height(),
'width':this.$el.parent().width(),
}).animate({
'top':this.$el.css("margin-top"),
'duration':0,
},{
'complete':function(){
pane.$(".navbar-fixed-bottom").each(function(){
var paddingBottom = Number(pane.$el.css("padding-bottom").replace("px",""));
pane.$el.css("padding-bottom",paddingBottom+$(this).outerHeight()+"px");
});
},
'duration':0,
'always':function(){
if(callback) callback();
}
});
this.$('.form-actions').each(function(){
var menu = $(this);
menu.css({
'bottom':0-menu.height(),
}).animate({
'bottom':0,
},
{
'duration':0,
}
);
});
return this;
},
hide: function(callback){
// if(callback) callback();
this.$('.form-actions').each(function(){
var menu = $(this);
menu.animate({
'bottom':0-menu.height(),
},{
'duration':0,
});
});
this.$el.css({
'position':'absolute',
'top':this.$el.css("margin-top"),
'width':this.$el.parent().width(),
'opacity':1,
}).animate({
'opacity':0,
'top':0-this.$el.height(),
},{
always:function(){
if(callback) callback();
},
'duration':0,
});
return this;
},
problemOver: function(event){
var problem = $(event.currentTarget);
problem.addClass("problem-hover");
},
problemOut: function(event){
var problem = $(event.currentTarget);
problem.removeClass("problem-hover");
}
});
var ProblemPane = Pane.extend({
'events':function(){
return _.extend({},Pane.prototype.events,{
'change .problem input':'toggleProblem',
});
},
toggleProblem:function(event){
if(event.currentTarget.checked){
$(event.currentTarget).parent().addClass("problem-selected");
}else{
$(event.currentTarget).parent().removeClass("problem-selected");
}
},
render: function(){
Pane.prototype.render.call(this); // ideally this would go after
var currentRow=[];
var pane = this;
pane.$('.problem').each(function(){
var problem = $(this);
if((problem.hasClass('problem-row-start') || pane.$('.problem:last')[0] == this)
&& currentRow.length > 0){
if(pane.$('.problem:last')[0] == this) currentRow.push(problem);
var tallestProblem = _.max(currentRow,function(problem){
return problem.height();
});
_.each(currentRow, function(problem){
problem.height(tallestProblem.height());
});
currentRow = [];
}
currentRow.push(problem);
});
}
});
panes['problems'] = ProblemPane;
var ProblemMostPane = ProblemPane.extend({
toggleProblem:function(event){
this.$('.problem-selected').removeClass("problem-selected");
if(event.currentTarget.checked){
$(event.currentTarget).parent().addClass("problem-selected");
}
}
});
panes['problems-most'] = ProblemMostPane;<file_sep>from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from main.views import home as main_home
def home(request):
if not request.is_ajax() and 'session_key' in request.session:
del request.session['session_key']
return main_home(request)<file_sep>from django.db import models
from sorl.thumbnail import ImageField
from django.db.models.signals import pre_save, post_save, pre_delete
from django.contrib.auth.models import User
# Create your models here.
class Problem(models.Model):
class Meta:
verbose_name = 'Problem'
verbose_name_plural = 'Problems'
ordering = ['title']
title = models.CharField(blank=True, max_length=150)
image = ImageField(
blank=True,
null=True,
upload_to="problems",
)
selected = False
def in_session(self, session=None, key=None, problem_list=[]):
if key:
session = Session.objects.get(key=key)
if session:
problem_list = session.problems()
if self.id in [p.id for p in problem_list]:
self.selected = True
return True
return False
def is_selected(self):
if self.selected:
return self.selected
return False
def __unicode__(self):
return self.title
class Session(models.Model):
class Meta:
verbose_name = 'Session'
verbose_name_plural = 'Sessions'
key = models.CharField( unique=True, max_length=30)
user = models.ForeignKey(User, blank=True, null=True)
def problems(self):
try:
return Problem.objects.filter(important__session=self).all()
except:
return []
def email_add(self, email):
try:
user, created = User.objects.get_or_create(username=email, email=email)
self.user = user
self.save()
except:
return False
return True
def __unicode__(self):
if self.user and self.user.email:
return "%s: %s" % (self.user.email, self.key)
return self.key
def session_make_key():
key = User.objects.make_random_password(30) #make a random string the size of key field
try:
Session.objects.get(key=key) # if this key is in use, recurse
return session_make_key()
except:
return key
def session_create_key(sender, instance, **kwargs):
if 'raw' in kwargs and kwargs['raw']:
return
if not instance.key:
instance.key = User.objects.make_random_password(30)
pre_save.connect(session_create_key, sender=Session)
class Important(models.Model):
class Meta:
verbose_name = 'Important'
verbose_name_plural = 'Importants'
problem = models.ForeignKey(Problem)
session = models.ForeignKey(Session)
ranking = models.IntegerField(blank=True, null=True, default=0)
def __unicode__(self):
return unicode(self.session) + unicode(self.problem)
class PersonType(models.Model):
name = models.CharField(unique=True, max_length=50, default="")
def __unicode__(self):
return self.name
class Survey(models.Model):
session = models.ForeignKey(Session, null=True, blank=True)
person_types = models.ManyToManyField(PersonType)
birth_year = models.IntegerField(blank=True, null=True)
def __unicode__(self):
return ",".join([ x.name for x in self.person_type.all()])
class Suggestion(models.Model):
class Meta:
verbose_name = 'Suggestion'
verbose_name_plural = 'Suggestions'
session = models.ForeignKey(Session)
submitted = models.DateTimeField(auto_now=True, auto_now_add=True)
description = models.CharField(max_length=500)
problems = models.ManyToManyField(Problem)
def __unicode__(self):
return self.description
<file_sep>Django==1.6.5
Pillow==2.4.0
South==0.8.4
boto==2.29.1
dj-database-url==0.3.0
django-crispy-forms==1.4.0
django-herokuapp==0.9.18
django-require==1.0.6
django-require-s3==1.0.0
django-storages==1.1.8
psycopg2==2.5.3
pycrypto==2.6.1
pytz==2014.4
sh==1.09
sorl-thumbnail==11.12
waitress==0.8.9
<file_sep>from django.conf.urls import patterns, include, url
urlpatterns = patterns('main.views',
url(r'^email','email', name="main-email"),
url(r'^survey','survey', name="main-survey"),
url(r'^end','end', name="session-end"),
url(r'^start(?P<session_key>\w+)','start', name="session-start"),
url(r'^','home', name="main-home"),
)<file_sep>{% load thumbnail %}
<div class="pane">
<h1>Your Selections</h1>
<p>Here are the selections that you have made</p>
<div class="problems problem-list">
{% for problem in problems %}
<div class="problem problem-card">
<span class="title problem-title" for="problem-{{problem.id}}">{{problem.title}}</span>
{% thumbnail problem.image "300x300" crop="center" as im %}
<img src="{{ im.url }}" alt="" />
{% endthumbnail %}
</div>
{% endfor %}
</div>
<nav class="form-actions actions navbar">
<a href="{% url 'problems-pick' %}" class="btn btn-ajax btn-large btn-primary pull-right">Edit your selections</a>
<a href="{% url 'suggestion-add' %}" class="btn btn-ajax btn-large btn-secondary pull-right" >Add a new issue</a>
</nav>
</div><file_sep>var Page = Backbone.Model.extend({
initialize: function(){
var model = this;
$(document).ajaxComplete(function(event, request, settings){
var data = request.responseJSON;
if(data['messages']){
_.forEach(data['messages'],function(message){
new Message({
text:message.text,
messageType:message.type,
});
});
}
if(data['redirect']){
model.loadPage(data['redirect']);
}
});
},
loadPage: function(url){
if(this.has('loading')) return false;
this.set('loading',true);
var model = this;
var jqhxr = $.ajax({
url:url,
}).done(function(data){
if(data['content']){
var pane = $(data['content']).insertAfter($(".pane:last"));
pane.hide();
model.setPane(pane[0],pane.data("type"));
}
}).always(function(){
model.unset('loading');
});
return jqhxr;
},
setPane: function(div, type){
var oldPane = this.get("currentPane");
if(oldPane){
var page = this;
oldPane.remove(function(){
page.set("currentPane", false);
page.setPane(div, type);
});
return this;
}
var paneView = Pane;
if(type && panes[type]) paneView = panes[type];
var pane = new paneView({
model:this,
el:div,
});
this.set('currentPane', pane);
this.listenTo(pane, 'pane-added', this.setPane);
return this;
}
});
var Message = Backbone.View.extend({
events:{
'click .close-btn':'handleClose',
},
initialize: function(options){
this.text = options.text;
this.messageType = options.messageType;
this.render();
},
render: function(){
var view = this;
var messageDiv = $('<div class="alert alert-'+this.messageType+'">'+this.text+'<a href="#" class="close-btn close glyphicon glyphicon-remove"><span class="hidden">Close</span></a></div>').prependTo($('#alerts'));
this.setElement(messageDiv);
setTimeout(function(){
view.hide();
},5000);
return this;
},
handleClose: function(event){
event.preventDefault();
this.hide();
},
hide: function(){
var view = this;
this.$el.animate({
opacity:0
},{
always: function(){
view.remove();
}
})
}
});<file_sep>from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, HTML, Submit
from django.core.urlresolvers import reverse
class SuggestionForm(forms.Form):
description = forms.CharField(
label="Describe your issue",
help_text='Tell us about the context about the issue. When does the issues happen? Who is involved?',
required=True,
widget = forms.Textarea,
)
email = forms.CharField(
label="Add your email address so we can clarify anything we don't understand in your issue (Optional)",
required=False,
widget=forms.EmailInput,
)
def __init__(self, *args, **kwargs):
super(SuggestionForm,self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.form_action = reverse('suggestion-add')
self.helper.attrs = {
'data_target':'pane',
}
self.helper.layout = Layout(
'description',
'email',
Div(
Submit("submit","Add Your Issue", css_class="btn-primary btn-large pull-right"),
HTML('<a href="%s" class="btn-secondary btn-large btn-ajax pull-right">%s</a>' % (
reverse("main-home"),
"No Thanks",
)),
css_class="form-actions")
)
<file_sep>from django.shortcuts import render_to_response, get_object_or_404
from django.template.loader import render_to_string
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib import messages
import json
from problems.models import Session
from main.forms import SurveyForm, EmailForm
import django.dispatch
pre_template_render = django.dispatch.Signal(providing_args=["template"])
def response(request, data={}, template="base.html", render=False, error=False, redirect=False):
for reciver, response in pre_template_render.send(False, template=template):
if response:
template = response
if request.is_ajax():
if render:
template = render
if template and template != "base.html":
content = render_to_string(template, data, context_instance=RequestContext(request))
data = {'content':content}
if redirect:
data = {'redirect':redirect}
data['messages'] = []
for message in messages.get_messages(request):
data['messages'].append({
'text':message.message,
'type':message.tags,
})
return HttpResponse(
json.dumps(data),
content_type='application/json',
)
if redirect:
return HttpResponseRedirect(redirect)
if render:
content = render_to_string(render, data, context_instance=RequestContext(request))
data = {'content': content}
return render_to_response(
template,
data,
context_instance=RequestContext(request)
)
from problems.views import pick
def home(request):
if 'session_key' not in request.session:
session = Session()
session.save()
request.session['session_key'] = session.key
return pick(request)
return response(request,
render='main/welcome.html',
data = {
'email_form':EmailForm(session=session)
}
)
session, created = Session.objects.get_or_create(key=request.session['session_key'])
return response(request,
data={
'problems':session.problems(),
},
render='main/home.html',
)
def survey(request):
if 'session_key' not in request.session:
return HttpResponseRedirect(reverse(important))
session, created = Session.objects.get_or_create(key=request.session['session_key'])
form = SurveyForm()
if request.POST:
form = SurveyForm(request.POST)
if form.is_valid():
survey = Survey()
survey.birth_year = form.cleaned_data['birth_year']
survey.save()
for t in form.cleaned_data['person_types']:
ty, created = PersonType.objects.get_or_create(name=t)
survey.person_types.add(ty)
return response(request, redirect=reverse('main-home'))
return response(request,
render='main/form.html',
data = { 'form':form }
)
def email(request):
if 'session_key' not in request.session:
return HttpResponseRedirect(reverse(important))
session, created = Session.objects.get_or_create(key=request.session['session_key'])
form = EmailForm(session = session)
if request.POST:
form = EmailForm(request.POST, session = session)
if form.is_valid():
user, created = User.objects.get_or_create(username=form.cleaned_data['email'], email=form.cleaned_data['email'])
session.user = user
session.save()
messages.add_message(request,messages.SUCCESS,'Added your email address %s.' % (user.email))
send_mail(
'Your diabetes problems account',
'You can continue your session at anytime by visiting %s' % (
request.build_absolute_uri(reverse(start, kwargs={'session_key':session.key})),
),
'<EMAIL>',
[user.email],
fail_silently=True
)
return response(request, redirect=reverse('main-home'))
return response(request,
render='main/form.html',
data = { 'form':form }
)
def start(request, session_key=False):
if session_key:
try:
session = Session.objects.get(key = session_key)
messages.add(request, messages.SUCCESS,'You session has been started')
request.session['session_key'] = session_key
except:
messages.add(request, messages.ERROR,'Your session doesn\'t exist')
return response(request, redirect=reverse('main-home'))
def end(request):
try:
del request.session['session_key']
messages.add(request,messages.SUCCESS,'Your session has been ended.')
except:
pass
return response(request, redirect=reverse('main-home'))
<file_sep>from django.conf.urls import patterns, include, url
urlpatterns = patterns('ajax.views',
url(r'^','home', name="ajax-home"),
)<file_sep>from main.views import pre_template_render
from django.dispatch import receiver
@receiver(pre_template_render)
def change_template(sender, **kwargs):
print("Request finished!")
if 'template' in kwargs and kwargs['template'] == 'base.html':
return "ajax.html"
return False
<file_sep>"""
Settings used by diabetes_problems project.
This consists of the general produciton settings, with an optional import of any local
settings.
"""
# Import production settings.
from diabetes_problems.settings.production import *
# Import optional local settings.
try:
from diabetes_problems.settings.local import *
except ImportError:
pass<file_sep>"""
Settings for local development.
These settings are not fast or efficient, but allow local servers to be run
using the django-admin.py utility.
This file should be excluded from version control to keep the settings local.
"""
import os.path
from production import BASE_DIR
# Run in debug mode.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
THUMBNAIL_DEBUG = DEBUG
# Serve files locally for development.
DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage"
STATICFILES_STORAGE = "require.storage.OptimizedCachedStaticFilesStorage"
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_SERVE = True
# Use local server.
SITE_DOMAIN = "localhost:8000"
PREPEND_WWW = False
ALLOWED_HOSTS = ['*']
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Disable the template cache for development.
TEMPLATE_LOADERS = (
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR,'database.db'),
}
}
<file_sep>from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, HTML, Submit
from django.core.urlresolvers import reverse
class SurveyForm(forms.Form):
person_types = forms.MultipleChoiceField(
label = 'Check every term that best descibe you',
widget=forms.CheckboxSelectMultiple,
choices = (
('Patient','Patient'),
('Medical Provider','Medical Provider'),
('Caregiver','Caregiver'),
('Designer','Designer'),
('Technologist','Technologist'),
),
)
birth_year = forms.CharField(
label = 'Enter your birth year',
help_text= 'Enter the year in YYYY format',
)
def __init__(self, data=None, session=None, *args, **kwargs):
if data:
super(SurveyForm, self).__init__(data, *args, **kwargs)
else:
super(SurveyForm, self).__init__(*args, **kwargs)
if session:
self.session = session
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.form_action = reverse('main-survey')
self.helper.add_input(Submit('submit', 'Submit'))
def clean(self):
cleaned_data = super(SurveyForm, self).clean()
if 'birth_year' not in cleaned_data:
return cleaned_data
birth_year = cleaned_data['birth_year']
if len(birth_year) != 4:
self._errors['birth_year'] = self.error_class(['Please enter only 4 digits'])
del cleaned_data['birth_year']
try:
birth_year = int(birth_year)
except:
self._errors['birth_year'] = self.error_class(['Please enter only numbers'])
del cleaned_data['birth_year']
return cleaned_data
class EmailForm(forms.Form):
email = forms.CharField(required=True, widget=forms.EmailInput)
def __init__(self, data=None, session=None, *args, **kwargs):
if data:
super(EmailForm, self).__init__(data, *args, **kwargs)
else:
super(EmailForm, self).__init__(*args, **kwargs)
if session:
self.session = session
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.form_action = reverse('main-email')
if self.session and self.session.user:
self.helper.layout = Layout(
HTML("<p>Thanks for giving us your email. You should recieve an email from us shortly.</p>"),
)
else:
self.helper.layout = Layout(
'email',
Submit('submit','Add your email')
)<file_sep>from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from main.views import response
from django.contrib.auth.models import User
from problems.models import Problem, Session, Important, PersonType, Survey, Suggestion
from problems.forms import SuggestionForm
from django.contrib import messages
from django.core.mail import send_mail
def pick(request):
try:
session = Session.objects.get(key=request.session['session_key'])
except:
return response(request, redirect=reverse('main-home'))
session_problems = session.problems() #Should do something to make this call not suck
if request.POST:
selected_problems = []
# check for existing session
for problem in [x for x in request.POST if 'problem' in x ]:
try:
pid = problem.split('-')[1]
prob = Problem.objects.get(id=pid)
selected_problems.append(prob)
except:
continue
if len(selected_problems) >= 1 or 'skip' in request.POST:
for problem in selected_problems:
if problem.id in [p.id for p in session_problems]:
continue
imp = Important(
problem=problem,
session=session,
)
imp.save()
return response(request, redirect=reverse('main-home'))
messages.add_message(request, messages.ERROR, 'Either skip this message, or select a problem.')
problems = Problem.objects.order_by('?').all()
for problem in problems:
problem.in_session(problem_list = session_problems)
return response(request,{
'problems':problems,
},
render='problems/problems-form.html')
def most(request):
try:
session = Session.objects.get(key=request.session['session_key'])
except:
return response(request, redirect=reverse('main-home'))
if len(session.problems()) <= 1:
return response(request, redirect=reverse('suggestion-add'))
if request.POST:
if 'problem' in request.POST:
try:
imp = Important.objects.get(
problem_id = request.POST['problem'],
session = session,
)
imp.ranking = 1
imp.save()
Important.objects.filter(session=session).exclude(id=imp.id).update(ranking=0)
messages.add_message(request, messages.SUCCESS, "Your most important issue has been saved")
return response(request, redirect=reverse('main-home'))
except:
pass
messages.add_message(request, messages.ERROR, "Problem saving your most important issue")
return response(request,{
'problems':session.problems(),
}, render="problems/most.html")
def order(request):
try:
session = Session.objects.get(key=request.session['session_key'])
except:
return response(request, redirect=reverse('main-home'))
if len(session.problems()) <= 1:
return response(request, redirect=reverse('suggestion-add'))
if request.POST:
for problem in [x for x in request.POST if 'problem' in x ]:
try:
pid = problem.split('-')[1]
imp = Important.objects.get(
problem__id=pid,
session = session,
)
imp.ranking = int(request.POST[problem])
imp.save()
except:
pass
return response(request, redirect=reverse('suggestion-add'))
return response(request,{
'problems':session.problems(),
}, render='problems/order.html')
def suggestion(request):
try:
session = Session.objects.get(key=request.session['session_key'])
except:
return response(request, redirect=reverse('main-home'))
form = SuggestionForm()
if request.POST:
form = SuggestionForm(request.POST)
if form.is_valid():
suggestion = Suggestion(
session = session,
description = form.cleaned_data['description']
)
suggestion.save()
if 'email' in form.cleaned_data['email']:
session.email_add(form.cleaned_data['email'])
messages.add_message(request, messages.SUCCESS,'Your suggestion has been saved. We will notify you when it is made public.')
return response(request, redirect=reverse('main-home'))
messages.add_message(request, messages.ERROR,'Please add a suggestion.')
return response(request, {
'form':form,
},
render='problems/suggestions.html',
)
<file_sep>from django.conf.urls import patterns, include, url
urlpatterns = patterns('problems.views',
url(r'^suggestion','suggestion', name="suggestion-add"),
url(r'^most','most', name="problems-most"),
url(r'^order','order', name="problems-order"),
url(r'^problems','pick', name="problems-pick"),
) | 5afda6fe24527dccbb6f968a2c7b977765089224 | [
"JavaScript",
"Python",
"Text",
"HTML"
]
| 16 | JavaScript | nickdotreid/diabetes-problems | 4eb5534ccb39b326e486bb77a95c2bdf4b27e3a4 | affd8d694ff3e0a87845bdf691a9364cafa3b147 |
refs/heads/master | <repo_name>jtoledo3970/CSC-262<file_sep>/Week 2/MidtermD2/src/midtermd2/MidtermD2.java
package midtermd2;
public class MidtermD2 {
public static void main(String[] args) {
int n = 5;
System.out.println("N = " + n);
// First Section
for (int j = 0; j < n; j++) {
for (int i = 0; i < (5*n); i++) {
System.out.print(" * ");
}
System.out.println();
}
// Second Section
for (int j = 0; j < n; j++) {
for (int i = 0; i < (5*n); i++) {
if (i >= 0 && i < n || i >= ((5*n)-n) && i <= (5*n)) {
System.out.print(" * ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
// Third Section
for (int j = 0; j < n; j++) {
for (int i = 0; i < (5*n); i++) {
if (i >= 0 && i < n || i >= (n*2) && i < (n*3) || i >= ((5*n)-n) && i <= (5*n)) {
System.out.print(" * ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
// Fourth Section
for (int j = 0; j < n; j++) {
for (int i = 0; i < (5*n); i++) {
if (i >= 0 && i < n || i >= ((5*n)-n) && i <= (5*n)) {
System.out.print(" * ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
// Fifth Section
for (int j = 0; j < n; j++) {
for (int i = 0; i < (5*n); i++) {
System.out.print(" * ");
}
System.out.println();
}
}
}
<file_sep>/Week 1/Triangle/src/Triangle.java
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
double side1, side2, side3;
Scanner in = new Scanner(System.in);
System.out.println("You will now enter three nonzero values");
// Three sides
System.out.println("Enter side 1: ");
side1 = in.nextDouble();
System.out.println("Enter side 2: ");
side2 = in.nextDouble();
System.out.println("Enter side 3: ");
side3 = in.nextDouble();
// Test of the triangle
if (side1 + side2 > side3) {
if (side1 + side3 > side2) {
if (side2 + side3 > side1) {
System.out.println("Those numbers can be the sides of a triangle");
} else {
System.out.println("These cannot be the sides of a triangle.");
}
} else {
System.out.println("These cannot be the sides of a triangle.");
}
}
}
}
<file_sep>/Week 1/EmployeeTest/src/employeetest/EmployeeTest.java
package employeetest;
final class Employee {
// The three instance var
private String firstName, lastName;
private double monthlySalary;
// Constructor
public Employee (String firstName, String lastName, double monthlySalary) {
// Initilization
setFirstName(firstName);
setLastName(lastName);
setMonthlySalary(monthlySalary);
}
// Accesors and Mutators
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setMonthlySalary(double salary) {
if (salary > 0) {
this.monthlySalary = salary;
} else {
System.out.println("Invalid entry: the salary should be a positive number");
}
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public double getMonthlySalary() {
return monthlySalary;
}
}
public class EmployeeTest {
public static void main(String[] args) {
Employee employeeA = new Employee("Jose", "Toledo", 82000.00);
Employee employeeB = new Employee("Tim", "Cook", 100289.00);
System.out.println("This is your first employee's information");
System.out.println("-----------------------------------------");
System.out.println("First name: " + employeeA.getFirstName() + "\nLast Name: " + employeeA.getLastName() + "\nMonthlySalary: $" + employeeA.getMonthlySalary() + "\nYearly Salary: $" + (employeeA.getMonthlySalary()*12) + "\nNow we will give " + employeeA.getFirstName() + " a raise of 10% which comes out to: " + (((employeeA.getMonthlySalary() * 1.1))*12));
System.out.println("-----------------------------------------");
System.out.println("This is your second employee's information");
System.out.println("-----------------------------------------");
System.out.println("First name: " + employeeB.getFirstName() + "\nLast Name: " + employeeB.getLastName() + "\nMonthlySalary: $" + employeeB.getMonthlySalary() + "\nYearly Salary: $" + (employeeB.getMonthlySalary()*12) + "\nNow we will give " + employeeB.getFirstName() + " a raise of 10% which comes out to: " + (((employeeB.getMonthlySalary() * 1.1))*12));
}
}
<file_sep>/Week 2/Pyramid/src/pyramid/Pyramid.java
package pyramid;
public class Pyramid {
public static void main(String[] args) {
int n = 8;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
for (int j = 0; j < i; j++) {
System.out.printf("%4d", (int) Math.pow(2,j));
}
for (int j = i - 2; j >= 0; j--) {
System.out.printf("%4d", (int) Math.pow(2,j));
}
System.out.println();
}
}
}
<file_sep>/Week 1/Account/src/AccountTest.java
import java.util.Scanner;
public class AccountTest {
public static void main(String[] args) {
double withdrawalAmount;
Account account1 = new Account("<NAME>", 1000.00);
System.out.println(account1.getName() + " balance: " + account1.getBalance());
Scanner in = new Scanner (System.in);
System.out.println("Enter the amount that you would like to withdrawal: ");
withdrawalAmount = in.nextDouble();
System.out.printf("Subtracting %.2f from account balance%n", withdrawalAmount);
account1.withdraw(withdrawalAmount);
System.out.println(account1.getName() + "'s balance: " + account1.getBalance());
}
}
class Account {
private String name;
private double balance;
public Account (String name, double balance) {
this.name = name;
if (balance > 0.0) {
this.balance = balance;
}
}
public void deposit (double depositAmount) {
if (depositAmount > 0.0) {
balance = balance + depositAmount;
}
}
public void withdraw (double withdrawalAmount) {
if (balance > withdrawalAmount) {
balance = balance - withdrawalAmount;
} else {
System.out.println("Withdrawal amount exceeded account balance");
}
}
public double getBalance() {
return balance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
<file_sep>/Week 3/DiceRolling/src/dicerolling/DiceRolling.java
package dicerolling;
public class DiceRolling {
public static void main(String[] args) {
int rolls = 36000000;
int size = 13;
int x, y;
int []sum = new int[size];
for (int i = 1; i <= rolls; ++i) {
x = (int)(1 + Math.random() * 6);
y = (int)(1 + Math.random() * 6);
++sum[x+y];
}
System.out.printf("If a pair of dice are rolled %d times this is the random outcome\n", rolls);
System.out.println("Sum\tTotal\t");
for (int j = 2; j < size; j++) {
System.out.println(j + "\t" + sum[j] + "\t");
}
}
}
<file_sep>/Week 2/MidtermA/src/midterma/MidtermA.java
package midterma;
import java.util.Scanner;
public class MidtermA {
public static void main(String[] args) {
double x;
double y;
double z;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your first number: ");
x = input.nextDouble();
System.out.print("Please enter your first number: ");
y = input.nextDouble();
System.out.print("Please enter your first number: ");
z = input.nextDouble();
double absY = Math.abs(y);
double zF = Math.pow(z,4);
double yT = Math.pow(y, 3);
double pT = Math.pow(x,2) - y;
double firstPart = Math.sqrt((x*x)+(Math.pow(absY, 3)));
double secondPart = Math.sqrt((y)-(1/x));
double thirdPart = zF + yT + Math.pow(pT, 3) - 11;
// This is the actual equation
System.out.println((firstPart + secondPart)/thirdPart);
}
}
<file_sep>/Week 3/TaylorRecursion/src/taylorrecursion/TaylorRecursion.java
package taylorrecursion;
public class TaylorRecursion {
public static void main(String[] args) {
int n = 10;
float x = 4.0f;
System.out.printf("e^x = %f", exponential(n,x));
}
public static float exponential(int n, float x) {
float sum = 1.0f;
for (int i = n - 1; i > 0; --i) {
sum = 1 + x * sum / i;
}
return sum;
}
}
<file_sep>/Week 2/MidtermC/src/MidtermC.java
public class MidtermC {
public static void main(String[] args) {
// Random number generation
int number = (int)((Math.random() * (14 - 1)) + 1);
// Generate a random integer 1 - 4
int suit = (int)(Math.random() * 4);
// Displays card
System.out.println("Drum roll please .........................");
System.out.println("..........................................");
System.out.print("The card you picked is ");
switch(number) {
case 1: System.out.print("Ace"); break;
case 2: System.out.print(number); break;
case 3: System.out.print(number); break;
case 4: System.out.print(number); break;
case 5: System.out.print(number); break;
case 6: System.out.print(number); break;
case 7: System.out.print(number); break;
case 8: System.out.print(number); break;
case 9: System.out.print(number); break;
case 10: System.out.print(number); break;
case 11: System.out.print("Jack"); break;
case 12: System.out.print("Queen"); break;
case 13: System.out.print("King");
}
System.out.print(" of ");
switch (suit) {
case 0: System.out.println("Clubs"); break;
case 1: System.out.println("Diamonds"); break;
case 2: System.out.println("Hearts"); break;
case 3: System.out.println("Spades");
}
}
}
<file_sep>/Week 3/SavingsAccount/src/savingsaccount/SavingsAccount.java
package savingsaccount;
class Savings {
private static double annualInterestRate = 0;
private double savingsBalance;
public Savings(double balance) {
savingsBalance = balance;
}
public void calculateMonthlyInterest() {
savingsBalance += savingsBalance * (annualInterestRate / 12.0);
}
public static void modifyInterestRate(double newRate) {
annualInterestRate = (newRate >= 0 && newRate <= 1.0) ? newRate:0.04;
}
public String toString() {
return String.format("$%.2f", savingsBalance);
}
}
public class SavingsAccount {
public static void main(String[] args) {
Savings a = new Savings (2000);
Savings b = new Savings (3000);
Savings.modifyInterestRate(0.04);
System.out.println("Monthly balances for one year at 4%");
System.out.println(" Balances:");
System.out.printf("%20s%10s\n", "Saver 1", "Saver 2");
System.out.printf("%-10s%10s%10s\n", "Base", a.toString(), b.toString());
for (int month = 1; month < 13; month++) {
String ml = String.format("Month: %d", month);
a.calculateMonthlyInterest();
b.calculateMonthlyInterest();
System.out.printf("%-10s%10s%10s\n", ml, a.toString(), b.toString());
}
Savings.modifyInterestRate(0.05);
a.calculateMonthlyInterest();
b.calculateMonthlyInterest();
System.out.println("\nAfter setting the interest rate to 5%");
System.out.println(" Balances:");
System.out.printf("%-10s%10s\n", "Saver 1", "Saver 2");
System.out.printf("%-10s%10s\n", a.toString(), b.toString());
}
}
| 859e470557ffb651a2d9a8313d4a846330b5b2ef | [
"Java"
]
| 10 | Java | jtoledo3970/CSC-262 | 6e4a2cd7255339d520f42152ee4be1b4bbf5eb23 | 953c4f7feb40ef5aa46e15475eb1e772987d03a3 |
refs/heads/master | <file_sep>/*
File: DSA_TestSuite_Lab7.h
Author(s):
Base: <NAME>
<EMAIL>
Created: 03.05.2021
Last Modified: 03.21.2021
Purpose: Declaration of Lab7 Unit Tests for BST
Notes: Property of Full Sail University
*/
// Header protection
#pragma once
/************/
/* Includes */
/************/
#include "BST.h"
#include <vector>
class DSA_TestSuite_Lab7 {
#if LAB_7
using myBST = BST<int>;
using myNode = myBST::Node;
static myBST* GenerateTree();
static void GetNodes(myNode* _node, std::vector<myNode*>& _vec);
static void DisplayNode(int _val, const myNode* _left, const myNode* _right, const myNode& _node);
static void DisplayTree(const std::string& _prefix, const myNode* _node, bool _isLeft);
static void DisplayTree(const myNode* _node);
public:
static void BSTDefaultConstructor();
static void BSTNodeConstructor();
static void BSTCopyConstructor();
static void BSTAssignmentOperator();
static void BSTClear();
static void BSTDestructor();
static void BSTPushRoot();
static void BSTPushRootLeft();
static void BSTPushRootRight();
static void BSTPushLeft();
static void BSTPushRight();
static void BSTContainsTrue();
static void BSTContainsFalse();
static void BSTRemoveCase0Root();
static void BSTRemoveCase0Left();
static void BSTRemoveCase0Right();
static void BSTRemoveCase1RootLeft();
static void BSTRemoveCase1RootRight();
static void BSTRemoveCase1LeftLeft();
static void BSTRemoveCase1LeftRight();
static void BSTRemoveCase1RightLeft();
static void BSTRemoveCase1RightRight();
static void BSTRemoveCase2Subtree();
static void BSTRemoveCase2NonRootNoSubtree();
static void BSTRemove();
static void BSTRemoveNotFound();
static void BSTInOrderTraversal();
#endif // End LAB_7
};
<file_sep>/*
File: DList.h
Author(s):
Base: <NAME>
<EMAIL>
Student: Yates, Phillip
Created: 12.27.2020
Last Modified: 02.26.2021
Purpose: A doubly-linked list (similar to std::list)
Notes: Property of Full Sail University
*/
//Header protection
#pragma once
/***********/
/* Defines */
/***********/
/*
How to use:
When working on a lab, turn that lab's #define from 0 to 1
Example: #define LAB_1 1
When working on an individual unit test, turn that #define from 0 to 1
Example: #define DYNARRAY_DEFAULT_CTOR 1
NOTE: If the unit test is not on, that code will not be compiled!
*/
// Master toggle
#define LAB_3 0
// Individual unit test toggles
#define LIST_CTOR 1 //Passing // Hammas FTW
#define LIST_NODE_CTOR_DEFAULT 1 //Passing
#define LIST_NODE_CTOR 1 //Passing
#define LIST_ADDHEAD_EMPTY 1 //Passing
#define LIST_ADDHEAD 1 //Passing
#define LIST_ADDTAIL_EMPTY 1 //Passing
#define LIST_ADDTAIL 1 //Passing
#define LIST_CLEAR 1 //Passing
#define LIST_DTOR 1 //Passing
#define LIST_ITER_BEGIN 1 //Passing
#define LIST_ITER_END 1 //Passing
#define LIST_ITER_INCREMENT_PRE 1 //Passing
#define LIST_ITER_INCREMENT_POST 1 //Passing
#define LIST_ITER_DECREMENT_PRE 1 //Passing
#define LIST_ITER_DECREMENT_POST 1 //Passing
#define LIST_INSERT_EMPTY 1 //Passing
#define LIST_INSERT_HEAD 1 //Passing
#define LIST_INSERT 1 //Passing
#define LIST_ERASE_EMPTY 1 //Passing
#define LIST_ERASE_HEAD 1 //Passing
#define LIST_ERASE_TAIL 1 //Passing
#define LIST_ERASE 1 //Passing
#define LIST_COPY_CTOR_INT 1 //Passing
#define LIST_COPY_CTOR_USER_DEFINED 1 //Passing
#define LIST_ASSIGNMENT_OP_INT 1 //Passing
#define LIST_ASSIGNMENT_OP_USER_DEFINED 1 //Passing
#if LAB_3
template<typename T>
class DList {
friend class DSA_TestSuite_Lab3; // Giving access to test code
struct Node {
T data;
Node* next, * prev; //Tail
Node(const T& _data, Node* _next = nullptr, Node* _prev = nullptr)
{
data = _data;
next = _next;
prev = _prev;
// TODO: Implement this method
}
};
public:
class Iterator {
public:
Node* mCurr;
// Pre-fix increment operator
//
// Return: Invoking object with curr pointing to next node
//
// Example:
// I - Iterator's curr
// R - Return
/*
Before
0<-[4]<->[5]<->[6]->0
I
After
0<-[4]<->[5]<->[6]->0
I
R
*/
Iterator& operator++() {
// TODO: Implement this method
//mCurr->next holds the value I need
//mCurr->next is a node
//I need to return a Iterator
mCurr = mCurr->next;
return *this;
/* Iterator iter;
iter.mCurr = mHead;
return iter;*/
}
// Post-fix increment operator
//
// In: (unused) Post-fix operators take in an unused int, so that the compiler can differentiate
//
// Return: An iterator that has its curr pointing to the "old" curr
// NOTE: Will need a temporary iterator
//
// Example:
// I - Iterator's curr
// R - Return
/*
Before
0<-[4]<->[5]<->[6]->0
I
After
0<-[4]<->[5]<->[6]->0
R I
*/
Iterator operator++(int) {
// TODO: Implement this method
Iterator temp = *this; // OLD
mCurr = mCurr->next; //Change Data
return temp; //Return OLD;
}
// Pre-fix decrement operator
//
// Return: Invoking object with curr pointing to previous node
//
// Example:
// I - Iterator's curr
// R - Return
/*
Before
0<-[4]<->[5]<->[6]->0
I
After
0<-[4]<->[5]<->[6]->0
I
R
*/
Iterator& operator--() {
// TODO: Implement this method
mCurr = mCurr->prev;
return *this;
}
// Post-fix decrement operator
//
// In: (unused) Post-fix operators take in an unused int, so that the compiler can differentiate
//
// Return: An iterator that has its curr pointing to the "old" curr
// NOTE: Will need a temporary iterator
//
// Example:
// I - Iterator's curr
// R - Return
/*
Before
0<-[4]<->[5]<->[6]->0
I
After
0<-[4]<->[5]<->[6]->0
I R
*/
Iterator operator--(int) {
// TODO: Implement this method
Iterator temp = *this;
mCurr = mCurr->prev;
return temp;
}
// Dereference operator
//
// Return: The data the curr is pointing to
T& operator*() {
// TODO: Implement this method
}
// Not-equal operator (used for testing)
//
// In: _iter The iterator to compare against
//
// Return: True, if the iterators are not pointing to the same node
bool operator != (const Iterator& _iter) const {
return mCurr != _iter.mCurr;
}
};
// Data members
Node* mHead; // The head (first node) of the list
Node* mTail; // The tail (last node) of the list
size_t mSize; // Current number of nodes being stored
public:
// Default constructor
// Creates a new empty linked list
DList() {
// TODO: Implement this method
mHead = nullptr;
mTail = nullptr;
mSize = 0;
}
// Destructor
// Cleans up all dynamically allocated memory
~DList() {
// TODO: Implement this method
//Dont use a method here
Node* temp = mHead;
while (mHead != nullptr) {
mHead = mHead->next;
delete temp;
temp = mHead;
}
mSize = 0;
mTail = nullptr;
}
// Copy constructor
// Used to initialize one object to another
//
// In: _copy The object to copy from
DList(const DList& _copy) {
// TODO: Implement this method
*this = _copy;
}
// Assignment operator
// Used to assign one object to another
// In: _asign The object to assign from
//
// Return: The invoking object (by reference)
// This allows us to daisy-chain
DList& operator=(const DList& _assign) {
// TODO: Implement this method
if (this != &_assign) //Needs to be passed by ref so it can come back changed
{
Clear();
RecursiveCopy(_assign.mHead); //Goes in to copy
}
return *this;
}
private:
// Optional recursive helper method for use with Rule of 3
//
// In: _curr The current Node to copy
void RecursiveCopy(const Node* _curr) { // 0<-[4]<->[5]<->[6]->0
// TODO (optional): Implement this method C CN
if (_curr != NULL) {
RecursiveCopy(_curr->next); //This builds the list A too Z // 0<-[4]<->[5]<->[6]->0
AddHead(_curr->data); //ADD head inserts starting with 6 then 5 then 4 so it ends up // 0<-[4]<->[5]<->[6]->0
}
}
public:
// Add a piece of data to the front of the list
//
// In: _data The object to add to the list
void AddHead(const T& _data) {
// TODO: Implement this method
//Next //Prev
Node* holder = new Node(_data, nullptr, nullptr);
if (mHead == nullptr)
{
mHead = holder; //Head (_data, next->NUll, Prev->nullptr)
mTail = holder; // Tail (_data, next->NULL, Prev->nullptr)
}
else
{
mHead->prev = holder; //Mhead->Next = (Data, Next->Null, Prev->mHead)
holder->next = mHead;
mHead = holder;
}
mSize++;
}
// Add a piece of data to the end of the list
//
// In: _data The object to add to the list
void AddTail(const T& _data) {
// TODO: Implement this method
//Next //Behind
Node* holder = new Node(_data, nullptr, mTail);
if (mTail == nullptr) {
mHead = holder;
mTail = holder;
}
else
{
mTail->next = holder;
mTail = holder;
}
mSize++;
}
// Clear the list of all dynamic memory
// Resets the list to its default state
void Clear() {
// TODO: Implement this method
Node* temp = mHead;
while (mHead != nullptr) {
mHead = mHead->next;
delete temp;
temp = mHead;
}
mSize = 0;
mTail = nullptr;
}
private:
// Optional recursive helper method for use with Clear
//
// In: _curr The current Node to clear
void RecursiveClear(const Node* _curr) {
// TODO (Optional): Implement this method
}
public:
// Insert a piece of data *before* the passed-in iterator
//
// In: _iter The iterator
// _data The value to add
//
// Example:
/*
Before
0<-[4]<->[5]<->[6]->0
I
After
0<-[4]<->[9]<->[5]<->[6]->0
I
*/
// Return: The iterator
// SPECIAL CASE: Inserting at head or empty list
// NOTE: The iterator should now be pointing to the new node created
Iterator Insert(Iterator& _iter, const T& _data) {
// TODO: Implement this method
Node* n = new Node(_data); //Create a new Node
mSize++;
if (mHead == nullptr) {
mHead = n;
mTail = n;
}
else if (_iter.mCurr == mHead)
//[2]<->[3]
//[n] <->
{
n->next = mHead;
mHead->prev = n;
mHead = n;
}
else
{
Node* current = _iter.mCurr;
Node* previous = _iter.mCurr->prev;
current->prev = n;
n->next = current;
n->prev = previous;
previous->next = n;
}
_iter.mCurr = n; // It needs to point to the new Node Created;
return _iter;
}
// Erase a Node from the list
//
// In: _iter The iterator
//
// Example
/*
Before
0<-[4]<->[5]<->[6]->0
I
After
0<-[4]<->[6]->0
I
*/
// Return: The iterator
// SPECIAL CASE: Erasing head or tail
// NOTE: The iterator should now be pointing at the node after the one erased
Iterator Erase(Iterator& _iter) {
// TODO: Implement this method
Node* current = _iter.mCurr;
Node* Holder = NULL; //Used for next mostly
if (_iter.mCurr == mHead && _iter.mCurr == mTail)
{
mHead = nullptr;
mTail = nullptr;
}
//HEAD ERASER IF CURR != NPTR
else if (_iter.mCurr == mHead)
{
Holder = _iter.mCurr->next;
mHead = mHead->next;
mHead->prev = NULL;
}
//TAIL ERASER
else if (_iter.mCurr == mTail)
{
//No need for Holder No mans land no return. *Sorry these help me understand
mTail = mTail->prev;
mTail->next = NULL;
}
else
{
Node* previous = _iter.mCurr->prev;
Holder = _iter.mCurr->next;
previous->next = Holder;
Holder->prev = previous;
}
delete current;
_iter.mCurr = Holder;
mSize--;
return _iter;
}
// Set an Iterator at the front of the list
//
// Return: An iterator that has its curr pointing to the list's head
Iterator Begin() {
// TODO: Implement this method
//Node* temp = mHead;
Iterator iter;
iter.mCurr = mHead;
return iter;
}
// Set an Iterator pointing to the end of the list
//
// Return: An iterator that has its curr pointing to a null pointer
Iterator End() {
// TODO: Implement this method
Iterator iter;
mTail = nullptr;
iter.mCurr = mTail;
return iter;
}
};
#endif // End LAB_3<file_sep>/*
File: DSA_TestSuite_Lab8.cpp
Author(s):
Base: <NAME>
<EMAIL>
Created: 03.12.2021
Last Modified: 03.19.2021
Purpose: Definitions of Lab8 Unit Tests for Huffman compression
Notes: Property of Full Sail University
*/
/************/
/* Includes */
/************/
#include <string>
#include <iostream>
#include "DSA_TestSuite_Lab8.h"
#include "DSA_Memory_Management.h"
#include "DSA_TestSuite_GlobalFunctions.h"
#if LAB_8
bool DSA_TestSuite_Lab8::HuffmanCompareTree(myHuffNode* _a, myHuffNode* _b) {
// Check for empty
if (!_a && !_b)
return 1;
// One is empty
else if (!_a || !_b)
return 0;
// Both non-empty
else {
return (_a->value == _b->value &&
_a->freq == _b->freq &&
HuffmanCompareTree(_a->left, _b->left) &&
HuffmanCompareTree(_a->left, _b->left));
}
}
void DSA_TestSuite_Lab8::ParseTree(myHuffNode* _node, myVector& _nodeVec) {
if (_node) {
ParseTree(_node->left, _nodeVec);
_nodeVec.push_back(_node);
ParseTree(_node->right, _nodeVec);
}
}
// Generate frequency tables for each of the sample files
unsigned int* GetFreqTable(int _fileNumber) {
unsigned int* freqTable = new unsigned int[257];
// us-cities.txt
if (!_fileNumber) {
// 0 1 2 3 4 5 6 7 8 9
unsigned int freq[257] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0
18579, 0, 0, 18579, 0, 0, 0, 0, 0, 0, // 10
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20
0, 0, 5984, 0, 0, 0, 0, 0, 0, 2, // 30
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, // 40
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 50
0, 0, 0, 0, 0, 933, 1933, 2616, 816, 834, // 60
1002, 1076, 1447, 334, 305, 533, 1442, 1913, 824, 582, // 70
1594, 56, 1157, 2337, 798, 116, 508, 1274, 2, 101, // 80
51, 0, 0, 0, 0, 0, 0, 13765, 1778, 2928, // 90
4107, 16254, 1025, 2723, 3479, 9870, 37, 2568, 11884, 2495, // 100
11333, 11486, 1761, 115, 10804, 6800, 8469, 3886, 2337, 1926, // 110
278, 2814, 231, 0, 0, 0, 0, 0, 0, 0, // 120
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 130
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 140
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 180
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 190
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 200
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 210
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 220
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 230
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 240
0, 0, 0, 0, 0, 0, 202882 }; // 250
memcpy(freqTable, freq, sizeof(unsigned int) * 257);
}
// words.txt
else {
// 0 1 2 3 4 5 6 7 8 9
unsigned int freq[257] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0
178635, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 10
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 30
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 50
0, 0, 0, 0, 0, 120923, 30120, 64162, 54854, 182711, // 60
20016, 43460, 36764, 140275, 2674, 14435, 84604, 44853, 106737, 103479, // 70
46599, 2584, 112444, 150189, 104029, 52104, 15429, 12416, 4761, 25860, // 80
7601, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 90
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 100
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 110
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 120
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 130
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 140
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 180
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 190
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 200
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 210
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 220
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 230
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 240
0, 0, 0, 0, 0, 0, 1762718 // 250
};
memcpy(freqTable, freq, sizeof(unsigned int) * 257);
}
return freqTable;
}
#if HUFFMAN_CTOR
void DSA_TestSuite_Lab8::HuffmanConstructor() {
// Creating a random filename (not an actual file)
std::string file;
for (int i = 0; i < 5; ++i)
file += char((rand() % 26) + 97);
file += ".file";
std::cout << "Testing Huffman constructor with " << file << "\n";
Huffman huff(file);
unsigned int testFreq = 0;
bool isSameFreq = true;
bool emptyEncoding = true;
if (verboseMode)
std::cout << "No verbose data for this test (non-verbose ouput is sufficient)\n";
// Error testing
if (huff.mFileName != file)
PrintMessage("Filename was not copied into data member");
for (size_t i = 0; i < 257; ++i) {
if (memcmp(&huff.mFrequencyTable, &testFreq, 4) != 0) {
PrintMessage("One (or more) indices have not been set to 0");
isSameFreq = false;
break;
}
}
if (huff.mLeafList.size())
PrintMessage("Leaf list should be empty at this point");
if (huff.mRoot != nullptr)
PrintMessage("Root should be null");
for (size_t i = 0; i < 256; ++i)
if (huff.mEncodingTable[i].size()) {
PrintMessage("All encoding tables should be empty");
emptyEncoding = false;
break;
}
// Testing for success
if (huff.mFileName == file &&
isSameFreq && emptyEncoding &&
nullptr == huff.mRoot &&
!huff.mLeafList.size())
PrintMessage();
}
#endif // End HUFFMAN_CTOR
#if HUFFMAN_GENERATE_FREQUENCY
void DSA_TestSuite_Lab8::HuffmanGenerateFrequencyTable() {
int fileNum = rand() % 2;
std::string fileName = (0 == fileNum ? "us-cities.txt" : "words.txt");
std::cout << "Testing Huffman frequency table generation with " << fileName << '\n';
bool isSameFreq = true;
unsigned int testFreq = 0;
unsigned int* testFreqTable = GetFreqTable(fileNum);
Huffman huff(fileName);
huff.GenerateFrequencyTable();
if (verboseMode)
std::cout << "No verbose data for this test (non-verbose ouput is sufficient)\n";
// Error testing
bool failMsg = true;
for (size_t i = 0; i < 257; ++i) {
if (huff.mFrequencyTable[i] != testFreqTable[i]) {
string indexString = "[" + std::to_string(i) +
"]:\t Expected: " + std::to_string(testFreqTable[i]) +
"\tYours: " + std::to_string(huff.mFrequencyTable[i]);
if (failMsg) {
PrintMessage("One or more values in frequency table are incorrect");
isSameFreq = false;
failMsg = false;
}
std::cout << indexString << '\n';
}
}
// Clean up
delete[] testFreqTable;
// Testing for success
if (isSameFreq)
PrintMessage();
}
#endif // End HUFFMAN_GENERATE_FREQUENCY
#if HUFFMAN_GENERATE_LEAFLIST
void DSA_TestSuite_Lab8::HuffmanGenerateLeafList() {
int fileNum = rand() % 2;
std::string fileName = (0 == fileNum ? "us-cities.txt" : "words.txt");
std::cout << "Testing Huffman leaf list generation with " << fileName << '\n';
int leafSize = !fileNum ? 57 : 27;
unsigned int testFreq = 0;
unsigned int* testFreqTable = GetFreqTable(fileNum);
bool isSameFreq = true;
Huffman huff(fileName);
memcpy(huff.mFrequencyTable, testFreqTable, sizeof(unsigned int) * 257);
huff.GenerateLeafList();
if (verboseMode)
std::cout << "No verbose data for this test (non-verbose ouput is sufficient)\n";
// Error testing
if (huff.mLeafList.size() != leafSize)
PrintMessage("Leaf list is incorrect size (did you accidentally include the total?)");
for (auto iter = huff.mLeafList.begin(); iter != huff.mLeafList.end(); ++iter) {
if ((*iter)->freq != testFreqTable[(*iter)->value]) {
PrintMessage("Frequency of one or more nodes is incorrect");
isSameFreq = false;
break;
}
}
// Clean up
delete[] testFreqTable;
for (size_t i = 0; i < huff.mLeafList.size(); ++i)
delete huff.mLeafList[i];
// Testing for success
if (huff.mLeafList.size() == leafSize &&
isSameFreq)
PrintMessage();
}
#endif // End HUFFMAN_GENERATE_LEAFLIST
#if HUFFMAN_GENERATE_TREE
struct leaf {
short val;
unsigned int freq;
};
void DSA_TestSuite_Lab8::HuffmanGenerateTree() {
std::cout << "Testing generation of Huffman tree\n";
Huffman huff("not_used.txt");
bool correctTree = false;
unsigned int totalFreq = 15;
// Generating data for string/file containing "This is a test.";
leaf leafNodes[9] = { {' ', 3},
{'.', 1},
{'T', 1},
{'a', 1},
{'e', 1},
{'h', 1},
{'i', 2},
{'s', 3},
{'t', 2},
};
// Adding leaves to list
for (size_t i = 0; i < 9; ++i)
huff.mLeafList.push_back(new myHuffNode(leafNodes[i].val, leafNodes[i].freq));
// Creating tree in a convulated way to not give away the answer
myHuffNode tree[17] = {
/* 0 */ Huffman::HuffNode(-1, 15, &tree[1], &tree[2], nullptr),
/* 1 */ Huffman::HuffNode(-1, 6, &tree[3], &tree[4], &tree[0]),
/* 2 */ Huffman::HuffNode(-1, 9, &tree[5], &tree[6], &tree[0]),
/* 3 */ Huffman::HuffNode(-1, 3, &tree[7], &tree[8], &tree[1]),
/* 4 */ Huffman::HuffNode('s', 3, nullptr, nullptr, &tree[1]),
/* 5 */ Huffman::HuffNode(-1, 4, &tree[9], &tree[10], &tree[2]),
/* 6 */ Huffman::HuffNode(-1, 5, &tree[11], &tree[12], &tree[2]),
/* 7 */ Huffman::HuffNode('e', 1, nullptr, nullptr, &tree[3]),
/* 8 */ Huffman::HuffNode('i', 2, nullptr, nullptr, &tree[3]),
/* 9 */ Huffman::HuffNode(-1, 2, &tree[13], &tree[14], &tree[5]),
/* 10 */ Huffman::HuffNode(-1, 2, &tree[15], &tree[16], &tree[5]),
/* 11 */ Huffman::HuffNode('t', 2, nullptr, nullptr, &tree[6]),
/* 12 */ Huffman::HuffNode(' ', 3, nullptr, nullptr, &tree[6]),
/* 13 */ Huffman::HuffNode('h', 1, nullptr, nullptr, &tree[9]),
/* 14 */ Huffman::HuffNode('a', 1, nullptr, nullptr, &tree[9]),
/* 15 */ Huffman::HuffNode('.', 1, nullptr, nullptr, &tree[10]),
/* 16 */ Huffman::HuffNode('T', 1, nullptr, nullptr, &tree[10]),
};
huff.GenerateTree();
bool identicalTree = HuffmanCompareTree(huff.mRoot, &tree[0]);
bool parentNodes = true;
if (verboseMode) {
// TODO
}
// Error testing
if (!huff.mRoot)
PrintMessage("Root is not pointing to a valid node");
if (huff.mRoot && huff.mRoot->freq != totalFreq)
PrintMessage("Root does not contain total frequency");
if (huff.mRoot && huff.mRoot->left && huff.mRoot->left->parent != huff.mRoot) {
PrintMessage("Nodes do not have valid parent pointers");
parentNodes = false;
}
if (!identicalTree)
PrintMessage("Trees are not identical. Double-check algorithm");
// Testing for success
if (huff.mRoot &&
totalFreq == huff.mRoot->freq &&
parentNodes && identicalTree)
PrintMessage();
// Clean up
myVector nodes;
ParseTree(huff.mRoot, nodes);
for (auto iter = nodes.begin(); iter != nodes.end(); ++iter)
delete *iter;
huff.mRoot = nullptr;
}
#endif // End HUFFMAN_GENERATE_TREE
#if HUFFMAN_CLEAR_TREE
void DSA_TestSuite_Lab8::HuffmanClearTree() {
std::cout << "Testing Clear method\n";
Huffman huff("not_used.txt");
size_t memoryUsed = metrics.inUse;
myHuffNode* tree[17];
for (size_t i = 0; i < 17; ++i)
tree[i] = new myHuffNode(-1, -1);
/* 0 */ *tree[0] = myHuffNode(-1, 15, tree[1], tree[2], nullptr);
/* 1 */ *tree[1] = myHuffNode(-1, 6, tree[3], tree[4], tree[0]);
/* 2 */ *tree[2] = myHuffNode(-1, 9, tree[5], tree[6], tree[0]);
/* 3 */ *tree[3] = myHuffNode(-1, 3, tree[7], tree[8], tree[1]);
/* 4 */ *tree[4] = myHuffNode('s', 3, nullptr, nullptr, tree[1]);
/* 5 */ *tree[5] = myHuffNode(-1, 4, tree[9], tree[10], tree[2]);
/* 6 */ *tree[6] = myHuffNode(-1, 5, tree[11], tree[12], tree[2]);
/* 7 */ *tree[7] = myHuffNode('e', 1, nullptr, nullptr, tree[3]);
/* 8 */ *tree[8] = myHuffNode('i', 2, nullptr, nullptr, tree[3]);
/* 9 */ *tree[9] = myHuffNode(-1, 2, tree[13], tree[14], tree[5]);
/* 10 */ *tree[10] = myHuffNode(-1, 2, tree[15], tree[16], tree[5]);
/* 11 */ *tree[11] = myHuffNode('t', 2, nullptr, nullptr, tree[6]);
/* 12 */ *tree[12] = myHuffNode(' ', 3, nullptr, nullptr, tree[6]);
/* 13 */ *tree[13] = myHuffNode('h', 1, nullptr, nullptr, tree[9]);
/* 14 */ *tree[14] = myHuffNode('a', 1, nullptr, nullptr, tree[9]);
/* 15 */ *tree[15] = myHuffNode('.', 1, nullptr, nullptr, tree[10]);
/* 16 */ *tree[16] = myHuffNode('T', 1, nullptr, nullptr, tree[10]);
huff.mRoot = tree[0];
huff.ClearTree();
if (verboseMode)
std::cout << "No verbose data for this test (non-verbose ouput is sufficient)\n";
if (metrics.inUse != memoryUsed)
PrintMessage("Not all nodes from tree were deleted");
if (huff.mRoot)
PrintMessage("Root was not set to nullptr after delete");
if (memoryUsed == metrics.inUse &&
nullptr == huff.mRoot)
PrintMessage();
}
#endif // End HUFFMAN_CLEAR_TREE
#if HUFFMAN_DTOR
void DSA_TestSuite_Lab8::HuffmanDestructor() {
std::cout << "Testing Destructor\n";
size_t memoryUsed = metrics.inUse;
Huffman*huff = new Huffman("not_used.txt");
myHuffNode* tree[17];
for (size_t i = 0; i < 17; ++i)
tree[i] = new myHuffNode(-1, -1);
/* 0 */ *tree[0] = myHuffNode(-1, 15, tree[1], tree[2], nullptr);
/* 1 */ *tree[1] = myHuffNode(-1, 6, tree[3], tree[4], tree[0]);
/* 2 */ *tree[2] = myHuffNode(-1, 9, tree[5], tree[6], tree[0]);
/* 3 */ *tree[3] = myHuffNode(-1, 3, tree[7], tree[8], tree[1]);
/* 4 */ *tree[4] = myHuffNode('s', 3, nullptr, nullptr, tree[1]);
/* 5 */ *tree[5] = myHuffNode(-1, 4, tree[9], tree[10], tree[2]);
/* 6 */ *tree[6] = myHuffNode(-1, 5, tree[11], tree[12], tree[2]);
/* 7 */ *tree[7] = myHuffNode('e', 1, nullptr, nullptr, tree[3]);
/* 8 */ *tree[8] = myHuffNode('i', 2, nullptr, nullptr, tree[3]);
/* 9 */ *tree[9] = myHuffNode(-1, 2, tree[13], tree[14], tree[5]);
/* 10 */ *tree[10] = myHuffNode(-1, 2, tree[15], tree[16], tree[5]);
/* 11 */ *tree[11] = myHuffNode('t', 2, nullptr, nullptr, tree[6]);
/* 12 */ *tree[12] = myHuffNode(' ', 3, nullptr, nullptr, tree[6]);
/* 13 */ *tree[13] = myHuffNode('h', 1, nullptr, nullptr, tree[9]);
/* 14 */ *tree[14] = myHuffNode('a', 1, nullptr, nullptr, tree[9]);
/* 15 */ *tree[15] = myHuffNode('.', 1, nullptr, nullptr, tree[10]);
/* 16 */ *tree[16] = myHuffNode('T', 1, nullptr, nullptr, tree[10]);
huff->mRoot = tree[0];
delete huff;
if (verboseMode)
std::cout << "No verbose data for this test (non-verbose ouput is sufficient)\n";
if (metrics.inUse != memoryUsed)
PrintMessage("Not all nodes from tree were deleted");
if (memoryUsed == metrics.inUse)
PrintMessage();
}
#endif // End HUFFMAN_DTOR
#if HUFFMAN_GENERATE_ENCODING
void DSA_TestSuite_Lab8::HuffmanGenerateEncodingTable() {
std::cout << "Testing generation of Huffman encoding table\n";
Huffman huff("dummy.txt");
bool correctEncoding = true;
// Generating data for string/file containing "This is a test."
// Creating tree in a convuluted way to not give away the answer
Huffman::HuffNode tree[17] = {
/* 0 */ Huffman::HuffNode(-1, 15, &tree[1], &tree[2], nullptr),
/* 1 */ Huffman::HuffNode(-1, 6, &tree[3], &tree[4], &tree[0]),
/* 2 */ Huffman::HuffNode(-1, 9, &tree[5], &tree[6], &tree[0]),
/* 3 */ Huffman::HuffNode(-1, 3, &tree[7], &tree[8], &tree[1]),
/* 4 */ Huffman::HuffNode('s', 3, nullptr, nullptr, &tree[1]),
/* 5 */ Huffman::HuffNode(-1, 4, &tree[9], &tree[10], &tree[2]),
/* 6 */ Huffman::HuffNode(-1, 5, &tree[11], &tree[12], &tree[2]),
/* 7 */ Huffman::HuffNode('e', 1, nullptr, nullptr, &tree[3]),
/* 8 */ Huffman::HuffNode('i', 2, nullptr, nullptr, &tree[3]),
/* 9 */ Huffman::HuffNode(-1, 2, &tree[13], &tree[14], &tree[5]),
/* 10 */ Huffman::HuffNode(-1, 2, &tree[15], &tree[16], &tree[5]),
/* 11 */ Huffman::HuffNode('t', 2, nullptr, nullptr, &tree[6]),
/* 12 */ Huffman::HuffNode(' ', 3, nullptr, nullptr, &tree[6]),
/* 13 */ Huffman::HuffNode('h', 1, nullptr, nullptr, &tree[9]),
/* 14 */ Huffman::HuffNode('a', 1, nullptr, nullptr, &tree[9]),
/* 15 */ Huffman::HuffNode('.', 1, nullptr, nullptr, &tree[10]),
/* 16 */ Huffman::HuffNode('T', 1, nullptr, nullptr, &tree[10]),
};
Huffman::HuffNode* leafNodes[9] = {
&tree[12], // ' '
&tree[15], // '.'
&tree[16], // 'T'
&tree[14], // 'a'
&tree[7], // 'e'
&tree[13], // 'h'
&tree[8], // 'i'
&tree[4], // 's'
&tree[11], // 't'
};
// Adding leaves to list
for (int i = 0; i < 9; ++i)
huff.mLeafList.push_back(leafNodes[i]);
// Test data
vector<bool> encodingData[9];
int indices[9] = { ' ', '.', 'T', 'a', 'e', 'h', 'i', 's', 't' };
encodingData[0].push_back(1); encodingData[0].push_back(1); encodingData[0].push_back(1);
encodingData[1].push_back(1); encodingData[1].push_back(0); encodingData[1].push_back(1); encodingData[1].push_back(0);
encodingData[2].push_back(1); encodingData[2].push_back(0); encodingData[2].push_back(1); encodingData[2].push_back(1);
encodingData[3].push_back(1); encodingData[3].push_back(0); encodingData[3].push_back(0); encodingData[3].push_back(1);
encodingData[4].push_back(0); encodingData[4].push_back(0); encodingData[4].push_back(0);
encodingData[5].push_back(1); encodingData[5].push_back(0); encodingData[5].push_back(0); encodingData[5].push_back(0);
encodingData[6].push_back(0); encodingData[6].push_back(0); encodingData[6].push_back(1);
encodingData[7].push_back(0); encodingData[7].push_back(1);
encodingData[8].push_back(1); encodingData[8].push_back(1); encodingData[8].push_back(0);
huff.mRoot = &tree[0];
huff.GenerateEncodingTable();
if (verboseMode) {
// TODO
}
for (int i = 0; i < 9; ++i)
if (huff.mEncodingTable[indices[i]] != encodingData[i]) {
PrintMessage(std::string(to_string(indices[i]) + " Encoding data is incorrect. Did you not reverse the codes?").c_str());
correctEncoding = false;
}
huff.mRoot = nullptr;
if (correctEncoding)
PrintMessage();
}
#endif // End HUFFMAN_GENERATE_ENCODING
#if HUFFMAN_COMPRESS
void DSA_TestSuite_Lab8::HuffmanCompress() {
int fileNum = rand() % 2;
string fileName = fileNum == 0 ? "us-cities.txt" : "words.txt";
std::cout << "Testing compression of "<< fileName << " using Huffman algorithm (this might take a few seconds)\n";
string compressedFileName = fileNum == 0 ? "us-cities.bin" : "words.bin";
string checkFileName = fileNum == 0 ? "us-cities_check.bin" : "words_check.bin";
char* checkBuffer = nullptr, * studentBuffer = nullptr;
int checkTotal = 0, studentTotal = 0;
Huffman huff(fileName);
bool identicalData = true;
huff.Compress(compressedFileName.c_str());
// Error testing
// Open the two files to do a byte-by-byte comparison
ifstream checkFile(checkFileName, ios_base::binary);
ifstream studentFile(compressedFileName, ios_base::binary);
if (!studentFile.is_open())
PrintMessage("Compressed file did not open correctly");
else {
// Read all of both files
checkFile.seekg(0, ios_base::end);
studentFile.seekg(0, ios_base::end);
checkTotal = (int)checkFile.tellg();
studentTotal = (int)studentFile.tellg();
checkFile.seekg(0, ios_base::beg);
studentFile.seekg(0, ios_base::beg);
checkBuffer = new char[checkTotal];
studentBuffer = new char[studentTotal];
checkFile.read(checkBuffer, checkTotal);
studentFile.read(studentBuffer, studentTotal);
checkFile.close();
studentFile.close();
if (studentTotal < checkTotal) {
PrintMessage("Your file is too small (missing data)");
}
else if (studentTotal > checkTotal) {
PrintMessage("Your file is too large (possibly tried to uncompress trailing 0's)");
}
if (studentTotal == checkTotal && memcmp(studentBuffer, checkBuffer, studentTotal) != 0) {
PrintMessage("Data is incorrect");
identicalData = false;
}
}
delete[] checkBuffer;
delete[] studentBuffer;
std::remove(compressedFileName.c_str());
// Success
if (studentTotal != 0 && studentTotal == checkTotal &&
identicalData)
PrintMessage();
}
#endif // End HUFFMAN_COMPRESS
#if HUFFMAN_DECOMPRESS
void DSA_TestSuite_Lab8::HuffmanDecompress() {
int fileNum = rand() % 2;
string compressedFileName = fileNum == 0 ? "us-cities_check.bin" : "words_check.bin";
std::cout << "Testing decompression of "<< compressedFileName << " using Huffman algorithm (this might take a few seconds)\n";
string checkFileName = fileNum == 0 ? "us-cities.txt" : "words.txt";
string studentFileName = fileNum == 0 ? "us-cities_uncompressed.txt" : "words_uncompressed.txt";
char* checkBuffer, * studentBuffer;
int checkTotal, studentTotal;
bool identicalData = true;
Huffman huff(compressedFileName);
bool success = true;
huff.Decompress(studentFileName.c_str());
// Open the two files to do a byte-by-byte comparison
ifstream checkFile(checkFileName, ios_base::binary);
ifstream studentFile(studentFileName, ios_base::binary);
// Read all of both files
checkFile.seekg(0, ios_base::end);
studentFile.seekg(0, ios_base::end);
checkTotal = (int)checkFile.tellg();
studentTotal = (int)studentFile.tellg();
checkFile.seekg(0, ios_base::beg);
studentFile.seekg(0, ios_base::beg);
checkBuffer = new char[checkTotal];
studentBuffer = new char[studentTotal];
checkFile.read(checkBuffer, checkTotal);
studentFile.read(studentBuffer, studentTotal);
checkFile.close();
studentFile.close();
std::remove(studentFileName.c_str());
if (studentTotal < checkTotal) {
PrintMessage("Your file is too small (missing data)");
}
else if (studentTotal > checkTotal) {
PrintMessage("Your file is too large (possibly tried to uncompress trailing 0's)");
}
if (success && memcmp(studentBuffer, checkBuffer, studentTotal) != 0) {
PrintMessage("Data is incorrect");
identicalData = false;
}
delete[] checkBuffer;
delete[] studentBuffer;
// Success
if (studentTotal == checkTotal &&
identicalData)
PrintMessage();
}
#endif // End HUFFMAN_DECOMPRESS
#endif // End LAB_8<file_sep>/*
File: DSA_TestSuite_Lab7.cpp
Author(s):
Base: <NAME>
<EMAIL>
Created: 03.05.2021
Last Modified: 03.21.2021
Purpose: Definitions of Lab7 Unit Tests for BST
Notes: Property of Full Sail University
*/
/************/
/* Includes */
/************/
#include <iostream>
#include "DSA_TestSuite_Lab7.h"
#include "DSA_Memory_Management.h"
#include "DSA_TestSuite_GlobalFunctions.h"
#if LAB_7
DSA_TestSuite_Lab7::myBST* DSA_TestSuite_Lab7::GenerateTree() {
myBST* bst = new myBST;
// Allocate all nodes
myNode* val50 = new myNode(50);
myNode* val25 = new myNode(25);
myNode* val75 = new myNode(75);
myNode* val10 = new myNode(10);
myNode* val35 = new myNode(35);
myNode* val65 = new myNode(65);
myNode* val100 = new myNode(100);
myNode* val15 = new myNode(15);
myNode* val60 = new myNode(60);
myNode* val80 = new myNode(80);
// Manually linking all nodes
val50->left = val25; val50->right = val75; val50->parent = nullptr;
val25->left = val10; val25->right = val35; val25->parent = val50;
val75->left = val65; val75->right = val100; val75->parent = val50;
val10->left = nullptr; val10->right = val15; val10->parent = val25;
val35->left = nullptr; val35->right = nullptr; val35->parent = val25;
val65->left = val60; val65->right = nullptr; val65->parent = val75;
val100->left = val80; val100->right = nullptr; val100->parent = val75;
val15->left = nullptr; val15->right = nullptr; val15->parent = val10;
val60->left = nullptr; val60->right = nullptr; val60->parent = val65;
val80->left = nullptr; val80->right = nullptr; val80->parent = val100;
bst->mRoot = val50;
/*
bst->mRoot = new myNode(50);
bst->mRoot->left = new myNode(25);
bst->mRoot->left->left = new myNode(10);
bst->mRoot->left->right = new myNode(35);
bst->mRoot->left->left->right = new myNode(15);
bst->mRoot->right = new myNode(75);
bst->mRoot->right->left = new myNode(65);
bst->mRoot->right->left->left = new myNode(60);
bst->mRoot->right->right = new myNode(100);
bst->mRoot->right->right->left = new myNode(80);
*/
/*
50
/\
25 75
/\ /\
10 35 65 100
\ / /
15 60 80
*/
return bst;
}
void DSA_TestSuite_Lab7::GetNodes(myNode* _node, std::vector<myNode*>& _vec) {
if (_node) {
_vec.push_back(_node);
GetNodes(_node->left, _vec);
GetNodes(_node->right, _vec);
}
}
void DSA_TestSuite_Lab7::DisplayNode(int _val, const myNode* _left, const myNode* _right, const myNode& _node) {
std::cout << "\t\tExpected Values\t\tYour Values\n"
<< "data:\t\t" << _val << "\t\t\t" << _node.data << '\n';
std::cout << "left:\t\t" << _left << "\t" << _node.left << '\n';
std::cout << "right:\t\t" << _right << "\t" << _node.right << '\n';
}
/* DisplayTree functionality originally from
https://stackoverflow.com/questions/36802354/print-binary-tree-in-a-pretty-way-using-c
*/
void DSA_TestSuite_Lab7::DisplayTree(const std::string& _prefix, const myNode* _node, bool _isLeft) {
if (_node != nullptr) {
std::cout << _prefix;
std::cout << (!_isLeft ? "R--" : "L__");
// print the value of the node
std::cout << _node->data << std::endl;
// enter the next tree level - left and right branch
DisplayTree(_prefix + (!_isLeft ? "| " : " "), _node->right, false);
DisplayTree(_prefix + (!_isLeft ? "| " : " "), _node->left, true);
}
}
void DSA_TestSuite_Lab7::DisplayTree(const myNode* _node) {
DisplayTree("", _node, false);
}
#if BST_CTOR
void DSA_TestSuite_Lab7::BSTDefaultConstructor() {
std::cout << "Testing default constructor\n";
myBST bst;
if (verboseMode)
std::cout << "No verbose data for this test (non-verbose ouput is sufficient)\n";
// Error testing
if (bst.mRoot)
PrintMessage("Root should be null");
if(metrics.inUse)
PrintMessage("No memory should be allocated to an empty tree");
// Testing for success
if (nullptr == bst.mRoot &&
0 == metrics.inUse)
PrintMessage();
}
#endif // End BST_CTOR
#if BST_NODE_CTOR
void DSA_TestSuite_Lab7::BSTNodeConstructor() {
std::cout << "Testing BST::Node constructor with valid node parameters\n";
int randVal = rand() % 100 + 1;
myNode node(randVal);
if (verboseMode)
DisplayNode(randVal, nullptr, nullptr, node);
if (randVal != node.data)
PrintMessage("Data in node is incorrect");
if (node.left || node.right)
PrintMessage("Node is not a leaf node");
// Success
if (randVal == node.data &&
!node.left &&
!node.right)
PrintMessage();
}
#endif // End BST_NODE_CTOR
#if BST_COPY_CTOR
void DSA_TestSuite_Lab7::BSTCopyConstructor() {
std::cout << "Testing copy constructor\n";
// Creating an initial tree
myBST* original = GenerateTree();
std::vector<myNode*> origVec;
GetNodes(original->mRoot, origVec);
size_t memoryOriginal = metrics.inUse;
// Calling copy constructor
myBST copy(*original);
if (verboseMode) {
std::cout << "\t\tExpected\n";
DisplayTree(original->mRoot);
std::cout << "\n\t\tYours\n";
DisplayTree(copy.mRoot);
std::cout << '\n';
}
std::vector<myNode*> copyVec;
GetNodes(copy.mRoot, copyVec);
size_t memoryUsed = metrics.inUse;
size_t correctMemory = memoryOriginal * 2 - sizeof(myBST*);
bool deepCopies = true;
bool identicalValues = true;
// Error testing
if (origVec.size() != copyVec.size())
PrintMessage("Entire tree was not copied");
else {
for (size_t i = 0; i < origVec.size(); ++i) {
if (origVec[i] == copyVec[i]) {
PrintMessage("BST is using shallow copies");
deepCopies = false;
break;
}
if (origVec[i]->data != copyVec[i]->data) {
PrintMessage("One (or more) nodes have the incorrect value");
identicalValues = false;
break;
}
}
}
if (memoryUsed < correctMemory)
PrintMessage("Not enough memory allocated (did you not allocate memory for each node?)");
else if (memoryUsed > correctMemory)
PrintMessage("Too much memory allocated (too many nodes allocated)");
// Testing for success
if (origVec.size() == copyVec.size() &&
deepCopies && identicalValues &&
metrics.inUse == correctMemory)
PrintMessage();
// Clean up
delete original;
}
#endif // End BST_COPY_CTOR
#if BST_ASSIGNMENT_OP
void DSA_TestSuite_Lab7::BSTAssignmentOperator() {
std::cout << "Testing assignment operator\n";
// Creating an initial tree
myBST* original = GenerateTree();
std::vector<myNode*> origVec;
GetNodes(original->mRoot, origVec);
size_t memoryOriginal = metrics.inUse;
// Calling assignment operator
myBST assign;
assign = *original;
if (verboseMode) {
std::cout << "\t\tExpected\n";
DisplayTree(original->mRoot);
std::cout << "\n\t\tYours\n";
DisplayTree(assign.mRoot);
std::cout << '\n';
}
std::vector<myNode*> copyVec;
GetNodes(assign.mRoot, copyVec);
size_t memoryUsed = metrics.inUse;
size_t correctMemory = memoryOriginal * 2 - sizeof(myBST*);
bool deepCopies = true;
bool identicalValues = true;
// Error testing
if (origVec.size() != copyVec.size())
PrintMessage("Entire tree was not copied");
else {
for (size_t i = 0; i < origVec.size(); ++i) {
if (origVec[i] == copyVec[i]) {
PrintMessage("BST is using shallow copies");
deepCopies = false;
break;
}
if (origVec[i]->data != copyVec[i]->data) {
PrintMessage("One (or more) nodes have the incorrect value");
identicalValues = false;
break;
}
}
}
if (memoryUsed < correctMemory)
PrintMessage("Not enough memory allocated (did you not allocate memory for each node?)");
else if (memoryUsed > correctMemory)
PrintMessage("Too much memory allocated (did you not clean up old nodes before re-allocating?)");
// Testing for success
if (origVec.size() == copyVec.size() &&
deepCopies && identicalValues &&
metrics.inUse == correctMemory)
PrintMessage();
// Clean up
delete original;
}
#endif // End BST_ASSIGNMENT_OP
#if BST_CLEAR
void DSA_TestSuite_Lab7::BSTClear() {
std::cout << "Testing Clear\n";
myBST* bst = GenerateTree();
size_t memoryUsed = metrics.inUse;
bst->Clear();
// Error testing
if (metrics.inUse == memoryUsed - sizeof(myNode*))
PrintMessage("Only one node deleted. Did you just delete root?");
if (metrics.inUse > sizeof(myBST*))
PrintMessage("Not all nodes were cleared");
if (bst->mRoot != nullptr)
PrintMessage("root was not set back to null");
// Testing for success
if (metrics.inUse == sizeof(myNode*) &&
nullptr == bst->mRoot)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_CLEAR
#if BST_DTOR
void DSA_TestSuite_Lab7::BSTDestructor() {
std::cout << "Testing destructor\n";
myBST* bst = GenerateTree();
size_t memoryUsed = metrics.inUse;
bst->Clear();
// Error testing
if (metrics.inUse == memoryUsed - sizeof(myNode*))
PrintMessage("Only one node deleted. Did you just delete root?");
if (metrics.inUse > sizeof(myBST*))
PrintMessage("Not all nodes were cleared");
// Testing for success
if (metrics.inUse == sizeof(myNode*))
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_DTOR
#if BST_PUSH_ROOT
void DSA_TestSuite_Lab7::BSTPushRoot() {
std::cout << "Testing Push on an empty tree\n";
int randomVal = rand() % 99 + 1;
myNode rootOnly(randomVal);
myBST bst;
bst.Push(randomVal);
if (verboseMode) {
std::cout << "\t\tExpected\n";
DisplayTree(&rootOnly);
std::cout << "\n\t\tYours\n";
DisplayTree(bst.mRoot);
}
// Error testing
if (0 == metrics.inUse)
PrintMessage("No dynamic memory was allocated");
if (metrics.inUse > sizeof(myNode))
PrintMessage("Too much memory was allocated (should only allocate one node)");
if (nullptr == bst.mRoot)
PrintMessage("Root was not set to allocated node");
if (bst.mRoot->data != randomVal)
PrintMessage("Node's value is incorrect");
if (nullptr != bst.mRoot->left || nullptr != bst.mRoot->right)
PrintMessage("Node is not set as a leaf node");
if (nullptr != bst.mRoot->parent)
PrintMessage("Root's parent should be null");
// Testing for success
if (metrics.inUse == sizeof(myNode) &&
bst.mRoot &&
bst.mRoot->data == randomVal &&
nullptr == bst.mRoot->left &&
nullptr == bst.mRoot->right &&
nullptr == bst.mRoot->parent)
PrintMessage();
}
#endif // BST_PUSH_ROOT
#if BST_PUSH_ROOT_LEFT
void DSA_TestSuite_Lab7::BSTPushRootLeft() {
std::cout << "Testing Push on a tree with only a root node (left)\n";
// Setting up two nodes
int rootVal = rand() % 50 + 50;
int leftVal = rand() % rootVal + 1;
myNode rootNode(rootVal), leftNode(leftVal);
rootNode.left = &leftNode;
myBST bst;
bst.Push(rootVal);
myNode* rootAddress = bst.mRoot;
// Pushing left node
bst.Push(leftVal);
myNode* left = bst.mRoot->left;
if (verboseMode) {
std::cout << "\t\tExpected\n";
DisplayTree(&rootNode);
std::cout << "\n\t\tYours\n";
DisplayTree(bst.mRoot);
}
// Error testing
if (0 == metrics.inUse)
PrintMessage("No dynamic memory was allocated");
if (metrics.inUse > sizeof(myNode)*2)
PrintMessage("Too much memory was allocated (should only allocate one node)");
if (nullptr == bst.mRoot)
PrintMessage("Root should not be null");
if (rootAddress != bst.mRoot)
PrintMessage("Root's address should not be changed");
if (nullptr == bst.mRoot->left)
PrintMessage("New node was not linked to root's left");
else {
if (left->data != leftVal)
PrintMessage("Newly added node's value is incorrect");
if (nullptr != left->left || nullptr != left->right)
PrintMessage("Node is not set as a leaf node");
if (bst.mRoot != left->parent)
PrintMessage("Node's parent is incorrect");
}
// Testing for success
if (metrics.inUse == sizeof(myNode) * 2 &&
bst.mRoot == rootAddress &&
left && left->data == leftVal &&
nullptr == left->left && nullptr == left->right &&
left->parent == bst.mRoot)
PrintMessage();
}
#endif // End BST_PUSH_ROOT_LEFT
#if BST_PUSH_ROOT_RIGHT
void DSA_TestSuite_Lab7::BSTPushRootRight() {
std::cout << "Testing Push on a tree with only a root node (right)\n";
// Setting up two nodes
int rootVal = rand() % 50 + 1;
int leftVal = rand() % 50 + rootVal;
myNode rootNode(rootVal), rightNode(leftVal);
rootNode.right = &rightNode;
myBST bst;
bst.Push(rootVal);
myNode* rootAddress = bst.mRoot;
// Pushing left node
bst.Push(leftVal);
myNode* right = bst.mRoot->right;
if (verboseMode) {
std::cout << "\t\tExpected\n";
DisplayTree(&rootNode);
std::cout << "\n\t\tYours\n";
DisplayTree(bst.mRoot);
}
// Error testing
if (0 == metrics.inUse)
PrintMessage("No dynamic memory was allocated");
if (metrics.inUse > sizeof(myNode) * 2)
PrintMessage("Too much memory was allocated (should only allocate one node)");
if (nullptr == bst.mRoot)
PrintMessage("Root should not be null");
if (rootAddress != bst.mRoot)
PrintMessage("Root's address should not be changed");
if (nullptr == bst.mRoot->right)
PrintMessage("New node was not linked to root's right");
else {
if (right->data != leftVal)
PrintMessage("Newly added node's value is incorrect");
if (nullptr != right->left || nullptr != right->right)
PrintMessage("Node is not set as a leaf node");
if (bst.mRoot != right->parent)
PrintMessage("Node's parent is incorrect");
}
// Testing for success
if (metrics.inUse == sizeof(myNode) * 2 &&
bst.mRoot == rootAddress &&
right && right->data == leftVal &&
nullptr == right->left && nullptr == right->right &&
right->parent == bst.mRoot)
PrintMessage();
}
#endif // End BST_PUSH_ROOT_RIGHT
#if BST_PUSH_LEFT
void DSA_TestSuite_Lab7::BSTPushLeft() {
std::cout << "Testing Push on a left Node not connected to the root\n";
// Setting up three nodes
int rootVal = rand() % 50 + 50;
int rootLeftVal = rand() % 25 + 10;
int childVal = rand() % 10;
myNode root(rootVal);
myNode rootLeft(rootLeftVal, &root);
myNode child(childVal, &rootLeft);
root.left = &rootLeft;
rootLeft.left = &child;
myBST bst;
bst.Push(rootVal);
bst.Push(rootLeftVal);
bst.Push(childVal);
if (verboseMode) {
std::cout << "\t\tExpected\n";
DisplayTree(&root);
std::cout << "\n\t\tYours\n";
DisplayTree(bst.mRoot);
}
// Error testing
myNode* addedNode = nullptr;
if (0 == metrics.inUse)
PrintMessage("No dynamic memory was allocated");
if (metrics.inUse > sizeof(myNode) * 3)
PrintMessage("Too much memory was allocated (should only allocate one node)");
if (nullptr == bst.mRoot)
PrintMessage("Root should not be null");
if (bst.mRoot && bst.mRoot->left && nullptr == bst.mRoot->left->left)
PrintMessage("Newly created node is not attached in tree at correct location (or at all)");
else {
addedNode = bst.mRoot->left->left;
if (addedNode->data != childVal)
PrintMessage("Value of new node is incorrect");
if(addedNode->left != nullptr || addedNode->right != nullptr)
PrintMessage("Node is not set as a leaf node");
if(addedNode->parent != bst.mRoot->left)
PrintMessage("Node's parent is incorrect");
}
// Test for success
if (metrics.inUse == sizeof(myNode) * 3 &&
bst.mRoot && bst.mRoot->left && bst.mRoot->left->left &&
childVal == addedNode->data &&
nullptr == addedNode->left && nullptr == addedNode->right &&
addedNode->parent == bst.mRoot->left)
PrintMessage();
}
#endif // End BST_PUSH_LEFT
#if BST_PUSH_RIGHT
void DSA_TestSuite_Lab7::BSTPushRight() {
std::cout << "Testing Push on a left Node not connected to the root\n";
// Setting up three nodes
int rootVal = rand() % 50 + 50;
int rootLeftVal = rand() % 10;
int childVal = rand() % 10 + 10;
myNode root(rootVal);
myNode rootLeft(rootLeftVal, &root);
myNode child(childVal, &rootLeft);
root.left = &rootLeft;
rootLeft.right = &child;
myBST bst;
bst.Push(rootVal);
bst.Push(rootLeftVal);
bst.Push(childVal);
if (verboseMode) {
std::cout << "\t\tExpected\n";
DisplayTree(&root);
std::cout << "\n\t\tYours\n";
DisplayTree(bst.mRoot);
}
// Error testing
myNode* addedNode = nullptr;
if (0 == metrics.inUse)
PrintMessage("No dynamic memory was allocated");
if (metrics.inUse > sizeof(myNode) * 3)
PrintMessage("Too much memory was allocated (should only allocate one node)");
if (nullptr == bst.mRoot)
PrintMessage("Root should not be null");
if (bst.mRoot && bst.mRoot->left && nullptr == bst.mRoot->left->right)
PrintMessage("Newly created node is not attached in tree at correct location (or at all)");
else {
addedNode = bst.mRoot->left->right;
if (addedNode->data != childVal)
PrintMessage("Value of new node is incorrect");
if (addedNode->left != nullptr || addedNode->right != nullptr)
PrintMessage("Node is not set as a leaf node");
if (addedNode->parent != bst.mRoot->left)
PrintMessage("Node's parent is incorrect");
}
// Test for success
if (metrics.inUse == sizeof(myNode) * 3 &&
bst.mRoot && bst.mRoot->left && bst.mRoot->left->right &&
childVal == addedNode->data &&
nullptr == addedNode->left && nullptr == addedNode->right &&
addedNode->parent == bst.mRoot->left)
PrintMessage();
}
#endif // End BST_PUSH_RIGHT
#if BST_CONTAINS_TRUE
void DSA_TestSuite_Lab7::BSTContainsTrue() {
BST<int>* bst = GenerateTree();
std::vector<myNode*> nodes;
GetNodes(bst->mRoot, nodes);
int containsVal = nodes[rand() % nodes.size()]->data;
std::cout << "Testing Contains on a value that is present in the list (" << containsVal << ")\n";
bool found = bst->Contains(containsVal);
if (verboseMode) {
std::cout << "Yours\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (!found)
PrintMessage("Contains returned false (value was in tree)");
// Success
if (found)
PrintMessage();
delete bst;
}
#endif // End BST_CONTAINS_TRUE
#if BST_CONTAINS_FALSE
void DSA_TestSuite_Lab7::BSTContainsFalse() {
BST<int>* bst = GenerateTree();
std::vector<myNode*> nodes;
GetNodes(bst->mRoot, nodes);
int containsVal = nodes[rand() % nodes.size()]->data + rand()% 4 + 1;
std::cout << "Testing Contains on a value that is not present in the list (" << containsVal << ")\n";
bool found = bst->Contains(containsVal);
if (verboseMode) {
std::cout << "Yours\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (found)
PrintMessage("Contains returned true (value was in tree)");
// Success
if (!found)
PrintMessage();
delete bst;
}
#endif BST_CONTAINS_FALSE
#if BST_REMOVE_CASE0_ROOT
void DSA_TestSuite_Lab7::BSTRemoveCase0Root() {
std::cout << "Testing RemoveCase0 on root\n";
// Setting up tree for testing
myBST bst;
bst.mRoot = new myNode(50);
bst.RemoveCase0(bst.mRoot);
if(verboseMode)
std::cout << "No additional information to display for this test\n";
// Error testing
if (metrics.inUse != 0)
PrintMessage("Node was not deleted");
if (bst.mRoot != nullptr)
PrintMessage("Root was not set back to null");
// Testing for success
if (0 == metrics.inUse &&
nullptr == bst.mRoot)
PrintMessage();
}
#endif // End BST_REMOVE_CASE0_ROOT
#if BST_REMOVE_CASE0_LEFT
void DSA_TestSuite_Lab7::BSTRemoveCase0Left() {
std::cout << "Testing RemoveCase0 on non-root left child (60)\n";
// Setting up tree for testing
myBST* bst = GenerateTree();
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
myNode* parent = bst->mRoot->right->left;
myNode* nodeToRemove = parent->left;
bst->RemoveCase0(nodeToRemove);
if (verboseMode) {
std::cout << "\n\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if (parent->left != nullptr)
PrintMessage("Parent of deleted node did not update its left pointer");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
nullptr == parent->left)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_CASE0_LEFT
#if BST_REMOVE_CASE0_RIGHT
void DSA_TestSuite_Lab7::BSTRemoveCase0Right() {
std::cout << "Testing RemoveCase0 on non-root right child (15)\n";
// Setting up tree for testing
myBST* bst = GenerateTree();
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
myNode* parent = bst->mRoot->left->left;
myNode* nodeToRemove = parent->right;
bst->RemoveCase0(nodeToRemove);
if (verboseMode) {
std::cout << "\n\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if (parent->right != nullptr)
PrintMessage("Parent of deleted node did not update its right pointer");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
nullptr == parent->right)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_CASE0_RIGHT
#if BST_REMOVE_CASE1_ROOT_LEFT
void DSA_TestSuite_Lab7::BSTRemoveCase1RootLeft() {
std::cout << "Testing RemoveCase1 on root with left child (50)\n";
// Generating test tree
myBST* bst = new myBST;
myNode* val50 = new myNode(50);
myNode* val25 = new myNode(25);
myNode* val10 = new myNode(10);
myNode* val35 = new myNode(35);
myNode* val15 = new myNode(15);
val50->left = val25; val50->right = nullptr; val50->parent = nullptr;
val25->left = val10; val25->right = val35; val25->parent = val50;
val10->left = nullptr; val10->right = val15; val10->parent = val15;
val35->left = nullptr; val35->right = nullptr; val35->parent = val25;
val15->left = nullptr; val15->right = nullptr; val15->parent = val10;
bst->mRoot = val50;
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
bst->RemoveCase1(bst->mRoot);
if (verboseMode) {
std::cout << "\n\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if (bst->mRoot != val25)
PrintMessage("Root was not updated to left node");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
nullptr == bst->mRoot->parent)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_CASE1_ROOT_LEFT
#if BST_REMOVE_CASE1_ROOT_RIGHT
void DSA_TestSuite_Lab7::BSTRemoveCase1RootRight() {
std::cout << "Testing RemoveCase1 on root with right child (50)\n";
// Generating test tree
myBST* bst = new myBST;
myNode* val50 = new myNode(50);
myNode* val75 = new myNode(75);
myNode* val65 = new myNode(65);
myNode* val100 = new myNode(100);
myNode* val60 = new myNode(60);
myNode* val80 = new myNode(80);
val50->left = nullptr; val50->right = val75; val50->parent = nullptr;
val75->left = val65; val75->right = val100; val75->parent = val50;
val65->left = val60; val65->right = nullptr; val65->parent = val75;
val100->left = val80; val100->right = nullptr; val100->parent = val75;
val60->left = nullptr; val60->right = nullptr; val60->parent = val65;
val80->left = nullptr; val80->right = nullptr; val80->parent = val100;
bst->mRoot = val50;
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
bst->RemoveCase1(bst->mRoot);
if (verboseMode) {
std::cout << "\n\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if (bst->mRoot != val75)
PrintMessage("Root was not updated to right node");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
nullptr == bst->mRoot->parent)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_CASE1_ROOT_RIGHT
#if BST_REMOVE_CASE1_LEFT_LEFT
void DSA_TestSuite_Lab7::BSTRemoveCase1LeftLeft() {
std::cout << "Testing RemoveCase1 on non-root left node that has a left child (65)\n";
// Generating tree
myBST* bst = new myBST;
myNode* val50 = new myNode(50);
myNode* val75 = new myNode(75);
myNode* val65 = new myNode(65);
myNode* val100 = new myNode(100);
myNode* val60 = new myNode(60);
myNode* val80 = new myNode(80);
myNode* val55 = new myNode(55);
val50->left = nullptr; val50->right = val75; val50->parent = nullptr;
val75->left = val65; val75->right = val100; val75->parent = val50;
val65->left = val60; val65->right = nullptr; val65->parent = val75;
val100->left = val80; val100->right = nullptr; val100->parent = val75;
val60->left = val55; val60->right = nullptr; val60->parent = val65;
val80->left = nullptr; val80->right = nullptr; val80->parent = val100;
val55->left = nullptr; val55->right = nullptr; val55->parent = val60;
bst->mRoot = val50;
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
myNode* nodeToRemove = val65;
myNode* parent = nodeToRemove->parent;
myNode* child = nodeToRemove->left;
bst->RemoveCase1(nodeToRemove);
if (verboseMode) {
std::cout << "\n\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if (parent->left != child)
PrintMessage("Parent's left pointer was not set to node after removed node");
if (child->parent != parent)
PrintMessage("Node after removed node's parent was not set to removed node's parent");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
parent->left == child &&
child->parent == parent)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_CASE1_LEFT_LEFT
#if BST_REMOVE_CASE1_LEFT_RIGHT
void DSA_TestSuite_Lab7::BSTRemoveCase1LeftRight() {
std::cout << "Testing RemoveCase1 on non-root left node that has a right child (10)\n";
// Generating tree
myBST* bst = new myBST;
myNode* val50 = new myNode(50);
myNode* val25 = new myNode(25);
myNode* val10 = new myNode(10);
myNode* val35 = new myNode(35);
myNode* val15 = new myNode(15);
myNode* val20 = new myNode(20);
bst->mRoot = val50;
val50->left = val25; val50->right = nullptr; val50->parent = nullptr;
val25->left = val10; val25->right = val35; val25->parent = val50;
val10->left = nullptr; val10->right = val15; val10->parent = val25;
val35->left = nullptr; val35->right = nullptr; val35->parent = val25;
val15->left = nullptr; val15->right = val20; val15->parent = val10;
val20->left = nullptr; val20->right = nullptr; val20->parent = val15;
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
myNode* nodeToRemove = val15;
myNode* parent = nodeToRemove->parent;
myNode* child = nodeToRemove->right;
bst->RemoveCase1(nodeToRemove);
if (verboseMode) {
std::cout << "\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if(metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if(parent->right != child)
PrintMessage("Parent's left pointer was not set to node after removed node");
if (child->parent != parent)
PrintMessage("Node after removed node's parent was not set to removed node's parent");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
parent->right == child &&
child->parent == parent)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_CASE1_LEFT_RIGHT
#if BST_REMOVE_CASE1_RIGHT_LEFT
void DSA_TestSuite_Lab7::BSTRemoveCase1RightLeft() {
std::cout << "Testing RemoveCase1 on non-root right node that has a left child (100)\n";
// Generating tree
myBST* bst = new myBST;
myNode* val50 = new myNode(50);
myNode* val75 = new myNode(75);
myNode* val65 = new myNode(65);
myNode* val100 = new myNode(100);
myNode* val60 = new myNode(60);
myNode* val80 = new myNode(80);
val50->left = nullptr; val50->right = val75; val50->parent = nullptr;
val75->left = val65; val75->right = val100; val75->parent = val50;
val65->left = val60; val65->right = nullptr; val65->parent = val75;
val100->left = val80; val100->right = nullptr; val100->parent = val75;
val60->left = nullptr; val60->right = nullptr; val60->parent = val65;
val80->left = nullptr; val80->right = nullptr; val80->parent = val100;
bst->mRoot = val50;
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
myNode* nodeToRemove = val100;
myNode* parent = nodeToRemove->parent;
myNode* child = nodeToRemove->left;
bst->RemoveCase1(nodeToRemove);
if (verboseMode) {
std::cout << "\n\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if (parent->right != child)
PrintMessage("Parent's right pointer was not set to node after removed node");
if (child->parent != parent)
PrintMessage("Node after removed node's parent was not set to removed node's parent");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
parent->right == child &&
child->parent == parent)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_CASE1_RIGHT_LEFT
#if BST_REMOVE_CASE1_RIGHT_RIGHT
void DSA_TestSuite_Lab7::BSTRemoveCase1RightRight() {
std::cout << "Testing RemoveCase1 on non-root right node that has a right child (35)\n";
// Generating tree
myBST* bst = new myBST;
myNode* val50 = new myNode(50);
myNode* val25 = new myNode(25);
myNode* val10 = new myNode(10);
myNode* val35 = new myNode(35);
myNode* val15 = new myNode(15);
myNode* val40 = new myNode(40);
bst->mRoot = val50;
val50->left = val25; val50->right = nullptr; val50->parent = nullptr;
val25->left = val10; val25->right = val35; val25->parent = val50;
val10->left = nullptr; val10->right = val15; val10->parent = val15;
val35->left = nullptr; val35->right = val40; val35->parent = val25;
val15->left = nullptr; val15->right = nullptr; val15->parent = val10;
val40->left = nullptr; val40->right = nullptr; val40->parent = val35;
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
myNode* nodeToRemove = val35;
myNode* parent = nodeToRemove->parent;
myNode* child = nodeToRemove->right;
bst->RemoveCase1(nodeToRemove);
if (verboseMode) {
std::cout << "\n\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if (parent->right != child)
PrintMessage("Parent's right pointer was not set to node after removed node");
if (child->parent != parent)
PrintMessage("Node after removed node's parent was not set to removed node's parent");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
parent->right == child &&
child->parent == parent)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_CASE1_RIGHT_RIGHT_NOSUBTREE
#if BST_REMOVE_CASE2_SUBTREE
void DSA_TestSuite_Lab7::BSTRemoveCase2Subtree() {
std::cout << "Testing RemoveCase2 on node that contains subtree (75)\n";
myBST* bst = GenerateTree();
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
myNode* nodeToRemove = bst->mRoot->right;
myNode* nodeToCheck = nodeToRemove->right;
bst->RemoveCase2(nodeToRemove);
if (verboseMode) {
std::cout << "\n\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if (nodeToRemove->data != 80)
PrintMessage("Node's value was not replaced with next lowest value in tree");
if (nodeToCheck->right != nullptr)
PrintMessage("Next lowest node was not removed from tree");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
80 == nodeToRemove->data &&
nullptr == nodeToCheck->right)
PrintMessage();
// Clean up
delete bst;
}
#endif BST_REMOVE_CASE2_SUBTREE
#if BST_REMOVE_CASE2_NO_SUBTREE
void DSA_TestSuite_Lab7::BSTRemoveCase2NonRootNoSubtree() {
std::cout << "Testing RemoveCase2 on node that contains subtree (25)\n";
myBST* bst = GenerateTree();
size_t memoryUsed = metrics.inUse;
if (verboseMode) {
std::cout << "\t\tYours Before\n";
DisplayTree(bst->mRoot);
}
myNode* nodeToRemove = bst->mRoot->left;
bst->RemoveCase2(nodeToRemove);
if (verboseMode) {
std::cout << "\n\t\tYours After\n";
DisplayTree(bst->mRoot);
}
// Error testing
if (metrics.inUse > memoryUsed - sizeof(myNode))
PrintMessage("Incorrect amount of memory (did you not delete the node?)");
if (nodeToRemove->data != 35)
PrintMessage("Node's value was not replaced with next lowest value in tree");
if (nodeToRemove->right != nullptr)
PrintMessage("Next lowest node was not removed from tree");
// Testing for success
if (metrics.inUse == memoryUsed - sizeof(myNode) &&
35 == nodeToRemove->data &&
nullptr == nodeToRemove->right)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_CASE2_NO_SUBTREE
#if BST_REMOVE
void DSA_TestSuite_Lab7::BSTRemove() {
std::cout << "Testing Remove for Case 0/1/2\n";
myBST* bstCase0 = GenerateTree();
myBST* bstCase1 = GenerateTree();
myBST* bstCase2 = GenerateTree();
const int numCase0 = 4, numCase1 = 3, numCase2 = 3;
int case0Nodes[numCase0] = { 15, 35, 60, 80 };
int case1Nodes[numCase1] = { 10, 65, 100 };
int case2Nodes[numCase2] = { 25, 50, 75 };
int case0ToRemove = case0Nodes[rand() % numCase0];
int case1ToRemove = case1Nodes[rand() % numCase1];
int case2ToRemove = case2Nodes[rand() % numCase2];
bool case0Removed = bstCase0->Remove(75);
bool case1Removed = bstCase1->Remove(case1ToRemove);
bool case2Removed = bstCase2->Remove(case2ToRemove);
if(verboseMode)
std::cout << "No additional information to display for this test\n";
// Error testing
if (false == case0Removed)
PrintMessage("Case 0 node was not removed (incorrect if check?)");
if (false == case1Removed)
PrintMessage("Case 1 node was not removed (incorrect if check?)");
if (false == case2Removed)
PrintMessage("Case 2 node was not removed (incorrect if check?)");
// Testing for success
if (case0Removed &&
case1Removed &&
case2Removed)
PrintMessage();
// Clean up
delete bstCase0;
delete bstCase1;
delete bstCase2;
}
#endif // End BST_REMOVE
#if BST_REMOVE_NOT_FOUND
void DSA_TestSuite_Lab7::BSTRemoveNotFound() {
std::cout << "Testing Remove for a value not in tree\n";
myBST* bst = GenerateTree();
int valueNotFound = rand() % 100 + 101;
bool removed = bst->Remove(valueNotFound);
if (verboseMode)
std::cout << "No additional information to display for this test\n";
// Error testing
if (true == removed)
PrintMessage("Remove returned true when no node was removed");
// Testing for success
if (false == removed)
PrintMessage();
// Clean up
delete bst;
}
#endif // End BST_REMOVE_NOT_FOUND
#if BST_IN_ORDER_TRAVERSAL
void DSA_TestSuite_Lab7::BSTInOrderTraversal() {
std::cout << "Testing in-order traversal\n";
BST<int>* bst = GenerateTree();
std::string inOrderStr = "10 15 25 35 50 60 65 75 80 100";
std::string result = bst->InOrder();
if (verboseMode)
std::cout << "Expected:\t" << inOrderStr << '\n'
<< "Yours:\t\t" << result << '\n';
if (result[result.size() - 1] == ' ')
PrintMessage("String has a trailing space");
else if (result != inOrderStr)
PrintMessage("Method not returning string in correct order");
// Success
if (result == inOrderStr)
PrintMessage();
delete bst;
}
#endif BST_IN_ORDER_TRAVERSAL
#endif // End LAB_7<file_sep>/*
File: DSA_TestSuite_Lab7.h
Author(s):
Base: <NAME>
<EMAIL>
Created: 03.14.2021
Last Modified: 03.14.2021
Purpose: Declaration of Lab8 Unit Tests for Huffman
Notes: Property of Full Sail University
*/
// Header protection
#pragma once
/************/
/* Includes */
/************/
#include "Huffman.h"
#include <vector>
class DSA_TestSuite_Lab8 {
#if LAB_8
using myHuffNode = Huffman::HuffNode;
using myVector = std::vector<myHuffNode*>;
// Helper method
static bool HuffmanCompareTree(myHuffNode* _a, myHuffNode* _b);
static void ParseTree(myHuffNode* _node, myVector& _nodeVec);
public:
static void HuffmanConstructor();
static void HuffmanGenerateFrequencyTable();
static void HuffmanGenerateLeafList();
static void HuffmanGenerateTree();
static void HuffmanClearTree();
static void HuffmanDestructor();
static void HuffmanGenerateEncodingTable();
static void HuffmanCompress();
static void HuffmanDecompress();
#endif // End LAB_8
};<file_sep>/*
File: DSA_Lab2.h
Author(s):
Base: <NAME>
<EMAIL>
Student:
Created: 11.30.2020
Last Modified: 02.26.2021
Purpose: Usage of the std::vector class
Notes: Property of Full Sail University
*/
// Header protection
#pragma once
/***********/
/* Defines */
/***********/
/*
How to use:
When working on a lab, turn that lab's #define from 0 to 1
Example: #define LAB_1 1
When working on an individual unit test, turn that #define from 0 to 1
Example: #define DYNARRAY_DEFAULT_CTOR 1
NOTE: If the unit test is not on, that code will not be compiled!
*/
// Master toggle
#define LAB_2 0
// Individual unit test toggles
#define LAB2_PALINDROME_NUMBER 1 //Passing
#define LAB2_VECTOR_FILL_FILE 1 //Passing
#define LAB2_VECTOR_FILL_ARRAY 1 //Passing
#define LAB2_VECTOR_CLEAR 1 //Passing
#define LAB2_VECTOR_SORT_ASCENDING 1 //Passing
#define LAB2_VECTOR_SORT_DESCENDING 1 //Passing
#define LAB2_VECTOR_BRACKETS 1 //Passing
#define LAB2_VECTOR_CONTAINS_TRUE 1 //Passing
#define LAB2_VECTOR_CONTAINS_FALSE 1 //Passing
#define LAB2_VECTOR_MOVE_PALINDROME 1 //Passing
/************/
/* Includes */
/************/
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
//File Header for binary
struct fileHeader
{
int totalValue; //total number of values 10000 // Then 5000 vec values with 2 in each
int grouping; // how many values in each vector // 2 data in each.
};
#if LAB_2
// Checks to see if a number is a palindrome (reads the same forwards and backwards)
// An example of a palindrome word would be "racecar"
//
// In: _num The number to check
//
// Return: True, if the number is a palindrome number
inline bool IsPalindromeNumber(unsigned int _num) {
// TODO: Implement this method
int checkIfEqual = _num;
int mainHolder = 0;
bool trueFalse = false;
while (_num > 0)
{
int digit = _num % 10;
mainHolder = (mainHolder * 10) + digit;
_num = _num / 10;
}
if (checkIfEqual == mainHolder) {
trueFalse = true;
}
return trueFalse;
}
class DSA_Lab2
{
friend class DSA_TestSuite_Lab2; // Giving access to test code
private:
std::vector<unsigned int> mValues; // contains all of the values
std::vector<unsigned int> mPalindromes; // contains just the numbers that are palindromes (only used in MovePalindromes method)
public:
// Fill out the mValues vector with the contents of the binary file
// First four bytes of the file are the number of ints in the file
//
// In: _input Name of the file to open
void Fill(const char* _input) {
// TODO: Implement this method
int total = 0;
std::ifstream reader(_input, std::ios_base::binary);
reader.read((char*)&total, 4);
unsigned int currVal = 0;
for (int i = 0; i < total; i++)
{
reader.read((char*)&currVal, sizeof(int));
mValues.push_back(currVal);
}
reader.close();
}
//// sort the vector
//// begin() - returns an iterator "pointing" to [0]
//// end() - returns an iterator "pointing" to the address past the last element ([100])
//std::sort(vec.begin(), vec.end());
// Fill out the mValues vector with the contents of an array
//
// In: _arr The array of values
// _size The number of elements in the array
void Fill(const unsigned int* _arr, size_t _size) {
// TODO: Implement this method
for (int i = 0; i < _size; i++)
{
mValues.push_back(_arr[i]);
}
}
// Remove all elements from vector and decrease capacity to 0
void Clear() {
// TODO: Implement this method
std::vector<unsigned int>().swap(mValues);
}
// Sort the vector
//
// In: _ascending To sort in ascending order or not
//
// NOTE: Use the std::sort method in this implementation
void Sort(bool _ascending) {
// TODO: Implement this method
if (_ascending == true) {
std::sort(mValues.begin(), mValues.end());
}
else {
std::sort(mValues.begin(), mValues.end(), std::greater<unsigned int>());
}
}
// Get an individual element from the mValues vector
int operator[](int _index) {
// TODO: Implement this method
for (int i = 0; i < mValues.size(); i++)
{
}
return mValues[_index];
}
// Determine if a value is present in the vector
//
// In: _val The value to check for
//
// Return: True, if the value is present
bool Contains(unsigned int _val) const {
// TODO: Implement this method
bool trueFalse = false;
if (std::count(mValues.begin(), mValues.end(), _val)) {
trueFalse = true;
}
else
{
trueFalse = false;
}
return trueFalse;
}
// Move all palindrome numbers from mValues vector to mPalindromes vector
//
// Pseudocode:
// iterate through the main values vector
// if the value is a palindrome
// add it to the palindrome vector
// remove it from the values vector
void MovePalindromes() {
// TODO: Implement this method
for (int i = 0; i < mValues.size(); i++)
{
if (IsPalindromeNumber(mValues[i]) == true)
{
mPalindromes.push_back(mValues[i]);
mValues.erase(mValues.begin()+i);
}
}
}
};
#endif // End LAB_2<file_sep>/*
File: DList.h
Author(s):
Base: <NAME>
<EMAIL>
Student:
Created: 1.17.2021
Last Modified: 2.26.2021
Purpose: A hash-mapped data structure using key/value pairs and separate chaining
Notes: Property of Full Sail University
*/
// Header protection
#pragma once
/***********/
/* Defines */
/***********/
/*
How to use:
When working on a lab, turn that lab's #define from 0 to 1
Example: #define LAB_1 1
When working on an individual unit test, turn that #define from 0 to 1
Example: #define DYNARRAY_DEFAULT_CTOR 1
NOTE: If the unit test is not on, that code will not be compiled!
*/
// Master toggle
#define LAB_5 1
// Individual unit test toggles
#define DICT_CTOR 0 //Passing
#define DICT_PAIR_CTOR 0 //Passing
#define DICT_DTOR 0 //Passing
#define DICT_CLEAR 0
#define DICT_INSERT 0 //Passing
#define DICT_INSERT_EXISTING 0 //Passing
#define DICT_FIND 0 //Passing
#define DICT_FIND_NOT_FOUND 0 //Passing
#define DICT_REMOVE 0 //Passing
#define DICT_REMOVE_NOT_FOUND 0 //Passing
#define DICT_ASSIGNMENT_OP 1 //Passing
#define DICT_COPY_CTOR 0
/************/
/* Includes */
/************/
#include <list>
#if LAB_5
//Key First Value 2nd
template<typename Key, typename Value>
class Dictionary {
friend class DSA_TestSuite_Lab5; // Giving access to test code
// The objects stored in the hash-table
struct Pair {
Key key; // The key for insertion/lookup
Value value; // The data
// Constructor
// In: _key
// _value
Pair(const Key& _key, const Value& _value) {
// TODO: Implement this method
key = _key;
value = _value;
}
// For testing
bool operator==(const Pair& _comp) {
return (_comp.key == key &&
_comp.value == value);
}
};
//*Linked List
std::list<Pair>* mTable; // A dynamic array of lists (these are the buckets)
size_t mNumBuckets; // Number of elements in mTable
unsigned int(*mHashFunc)(const Key&); // Pointer to the hash function
//Function pointer
public:
// Constructor
// In: _numBuckets The number of elements to allocate
// _hashFunc The hashing function to be used
Dictionary(size_t _numBuckets, unsigned int (*_hashFunc)(const Key&)) {
// TODO: Implement this method
mNumBuckets = _numBuckets;
mHashFunc = _hashFunc;
mTable = new std::list<Pair>[_numBuckets];
}
// Destructor
// Cleans up any dynamically allocated memory
~Dictionary() {
// TODO: Implement this method
delete[] mTable;
}
// Copy constructor
// Used to initialize one object to another
// In: _copy The object to copy from
Dictionary(const Dictionary& _copy) {
// TODO: Implement this method
}
// Assignment operator
// Used to assign one object to another
// In: _assign The object to assign from
//
// Return: The invoking object (by reference)
// This allows us to daisy-chain
Dictionary& operator=(const Dictionary& _assign) {
// TODO: Implement this method
delete[] mTable;
mTable = new std::list<Pair>[_assign.mNumBuckets];
if (this != &_assign)
{
this->mNumBuckets = _assign.mNumBuckets;
this->mHashFunc = _assign.mHashFunc;
for (int i = 0; i < mNumBuckets; i++)
{
mTable[i] = _assign.mTable[i];
}
}
return *this;
}
// Clear
// Clears all internal data being stored
// NOTE: Does not delete table or reset hash function
void Clear() {
// TODO: Implement this method
for (int i = 0; i < mNumBuckets; i++)
{
for (typename std::list<Pair>::iterator it = mTable[i].begin(); it != mTable[i].end(); ++it)
{
if (it->key != NULL) {
it->key = NULL;
it->value = NULL;
}
}
}
}
// Insert an item into the table
// In: _key The key to add at
// _value The value at the key
//
// NOTE: If there is already an item at the provided key, overwrite it.
void Insert(const Key& _key, const Value& _value) {
// TODO: Implement this method
//Call Hash Function
int hashValue = mHashFunc(_key);
auto& tableCell = mTable[hashValue];
auto Itr = begin(tableCell);
bool keyExist = false;
for (; Itr != end(tableCell); ++Itr) {
if (Itr->key == _key) {
keyExist = true;
Itr->value = _value;
break;
}
}
if (!keyExist) {
tableCell.emplace_back(_key, _value);
}
return;
}
// Find a value at a specified key
// In: _key The key to search for
//
// Return: A const pointer to the value at the searched key
// NOTE: Return a null pointer if key is not present
const Value* Find(const Key& _key) {
// TODO: Implement this method
//Call Has function
int hashValue = mHashFunc(_key);
auto& tableCell = mTable[hashValue];
auto Itr = begin(tableCell);
bool keyExist = false;
for (; Itr != end(tableCell); ++Itr) {
if (Itr->key == _key) {
keyExist = true;
return &Itr->value;
break;
}
}
if (!keyExist) {
return nullptr;
}
//for (; Itr != end(tableCell); Itr++) {
// //Key exist
// if (Itr->key == _key && _key != NULL) {
// const Value& ptr = Itr->value ;
// return &ptr;
// }
//
// //Key dose not exist ptr needs to return a null //**DONE**
// else {
// return nullptr;
// }
//
//}
}
// Remove a value at a specified key
// In: _key The key to remove
//
// Return: True, if an item was removed
bool Remove(const Key& _key) {
// TODO: Implement this method
int currBucket = mHashFunc(_key);
for (typename std::list<Pair>::iterator it = mTable[currBucket].begin(); it != mTable[currBucket].end(); ++it)
{
if (it->key == _key) {
mTable[currBucket].erase(it);
return true;
}
}
return false;
}
};
#endif // End LAB_5<file_sep>/*
File: BST.h
Author(s):
Base: <NAME>
<EMAIL>
Student:
Created: 03.05.2021
Last Modified: 03.21.2021
Purpose: A binary search tree
Notes: Property of Full Sail University
*/
// Header protection
#pragma once
/************/
/* Includes */
/************/
#include <string>
/***********/
/* Defines */
/***********/
/*
How to use:
When working on a lab, turn that lab's #define from 0 to 1
Example: #define LAB_1 1
When working on an individual unit test, turn that #define from 0 to 1
Example: #define DYNARRAY_DEFAULT_CTOR 1
NOTE: If the unit test is not on, that code will not be compiled!
*/
// Master toggle
#define LAB_7 0
// Individual unit test toggles
#define BST_CTOR 0
#define BST_NODE_CTOR 0
#define BST_CLEAR 0
#define BST_DTOR 0
#define BST_PUSH_ROOT 0
#define BST_PUSH_ROOT_LEFT 0
#define BST_PUSH_ROOT_RIGHT 0
#define BST_PUSH_LEFT 0
#define BST_PUSH_RIGHT 0
#define BST_CONTAINS_TRUE 0
#define BST_CONTAINS_FALSE 0
#define BST_REMOVE_CASE0_ROOT 0
#define BST_REMOVE_CASE0_LEFT 0
#define BST_REMOVE_CASE0_RIGHT 0
#define BST_REMOVE_CASE1_ROOT_LEFT 0
#define BST_REMOVE_CASE1_ROOT_RIGHT 0
#define BST_REMOVE_CASE1_LEFT_LEFT 0
#define BST_REMOVE_CASE1_LEFT_RIGHT 0
#define BST_REMOVE_CASE1_RIGHT_LEFT 0
#define BST_REMOVE_CASE1_RIGHT_RIGHT 0
#define BST_REMOVE_CASE2_NO_SUBTREE 0
#define BST_REMOVE_CASE2_SUBTREE 0
#define BST_REMOVE 0
#define BST_REMOVE_NOT_FOUND 0
#define BST_IN_ORDER_TRAVERSAL 0
#define BST_ASSIGNMENT_OP 0
#define BST_COPY_CTOR 0
#if LAB_7
// Templated binary search tree
template<typename Type>
class BST {
friend class DSA_TestSuite_Lab7; // Giving access to test code
struct Node {
Type data; // The value being stored
Node* left, * right; // The left and right nodes
Node* parent; // The parent node
// Constructor
// Always creates a leaf node
//
// In: _data The value to store in this node
// _parent The parent pointer (optional)
Node(const Type& _data, Node* _parent = nullptr) {
// TODO: Implement this method
}
};
// Data members
Node* mRoot; // The top-most Node in the tree
public:
// Default constructor
// Always creates an empty tree
BST() {
// TODO: Implement this method
}
// Destructor
// Clear all dynamic memory
~BST() {
// TODO: Implement this method
}
// Copy constructor
// Used to initialize one object to another
//
// In: _copy The object to copy from
BST(const BST<Type>& _copy) {
// TODO: Implement this method
}
// Assignment operator
// Used to assign one object to another
//
// In: _assign The object to assign from
//
// Return: The invoking object (by reference)
// This allows us to daisy-chain
BST<Type>& operator=(const BST<Type>& _assign) {
// TODO: Implement this method
}
private:
// Recursive helper method for use with Rule of 3
//
// In: _curr The current Node to copy
//
// NOTE: Use pre-order traversal
void Copy(const Node* _curr) {
// TODO: Implement this method
}
public:
// Clears out the tree and readies it for re-use
void Clear() {
// TODO: Implement this method
}
private:
// Recursive helper method for use with Clear
//
// In: _curr The current Node to clear
//
// NOTE: Use post-order traversal
void Clear(Node* _curr) {
// TODO: Implement this method
}
public:
// Add a value into the tree
//
// In: _val The value to add
void Push(const Type& _val) {
// TODO: Implement this method
}
private:
// Optional recursive helper method for use with Push
//
// In: _val The value to add
// _curr The current Node being looked at
void Push(const Type& _val, Node* _curr, Node* _parent) {
// TODO: Implement this method (Optional)
}
public:
// Checks to see if a value is in the tree
//
// In: _val The value to search for
//
// Return: True, if found
bool Contains(const Type& _val) {
// TODO: Implement this method
}
private:
// Optional helper method for use with Contains and Remove methods
//
// In: _val The value to search for
//
// Return: The node containing _val (or nullptr if not found)
Node* FindNode(const Type& _val) {
// TODO: Implement this method (Optional)
}
// Remove a leaf node from the tree
// Case 0
//
// In: _node The Case 0 node to remove
//
// Note: The node being passed in will always be a Case 0
// Remember to check all 3 subcases
// 1. Root only
// 2. Left leaf node
// 3. Right leaf node
void RemoveCase0(Node* _node) {
// TODO: Implement this method
}
// Remove a node from the tree that has only one child
// Case 1
//
// In: _node The Case 1 node to remove
//
// Note: The node being passed in will always be a Case 1
// Remember to check all 6 subcases
// 1. Root with left child
// 2. Root with right child
// 3. Left node with left child
// 4. Left node with right child
// 5. Right node with left child
// 6. Right node with right child
void RemoveCase1(Node* _node) {
// TODO: Implement this method
}
// Remove a node from the tree that has both children
// Case 2
//
// In: _node The Case 2 node to remove
//
// Note: The node being passed in will always be a Case 2
void RemoveCase2(Node* _node) {
// TODO: Implement this method
}
public:
// Removes a value from tree (first instance only)
//
// In: _val The value to search for
//
// Return: True, if a Node was removed
//
// Note: Can use FindNode to get the node* to remove,
// and then call one of the RemoveCase methods
bool Remove(const Type& _val) {
// TODO: Implement this method
}
// Returns a space-delimited string of the tree in order
/*
Example:
24
/ \
10 48
\ \
12 50
Should return: "10 12 24 48 50"
*/
// Note: Use to_string to convert an int to its string equivelent
// Don't forget about the trailing space!
std::string InOrder() {
// TODO: Implement this method
}
private:
// Recursive helper method to help with InOrder
//
// In: _curr The current Node being looked at
// _str The string to add to
//
// NOTE: Use in-order traversal
void InOrder(Node* _curr, std::string& _str) {
// TODO: Implement this method
}
};
#endif // End LAB_7 | 0d35e1523108b25091143ea23f7e628ffda7dbc6 | [
"C++"
]
| 8 | C++ | Kainthekiller/Vectors-Pandalorms | ba641d40182d35adb2ab30b42f75dfe07d24e371 | e8dd363e63f30304d8fb11d4b7d654c22b22aae4 |
refs/heads/master | <repo_name>dajahu/Draw-Something---Not-Complete<file_sep>/Draw Something/ViewController.swift
//
// ViewController.swift
// Draw Something
//
// Created by <NAME> on 2016-02-29.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var tempImageView: UIImageView!
var lastPoint = CGPoint.zero
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
swiped = false
if let touch = touches.first as UITouch! {
lastPoint = touch.locationInView(self.view)
}
}
func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {
// 1
UIGraphicsBeginImageContext(view.frame.size)
let context = UIGraphicsGetCurrentContext()
tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
// 2
CGContextMoveToPoint(context, fromPoint.x, fromPoint.y)
CGContextAddLineToPoint(context, toPoint.x, toPoint.y)
// 3
CGContextSetLineCap(context, CGLineCap.Round)
CGContextSetLineWidth(context, brushWidth)
CGContextSetRGBStrokeColor(context, red, green, blue, 1.0)
CGContextSetBlendMode(context, .Normal)
// 4
CGContextStrokePath(context)
// 5
tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
tempImageView.alpha = opacity
UIGraphicsEndImageContext()
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
swiped = true
if let touch = touches.first as UITouch! {
let currentPoint = touch.locationInView(view)
drawLineFrom(lastPoint, toPoint: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if !swiped {
// draw a single point
drawLineFrom(lastPoint, toPoint: lastPoint)
}
// Merge tempImageView into mainImageView
UIGraphicsBeginImageContext(mainImageView.frame.size)
mainImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: .Normal, alpha: 1.0)
tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: .Normal, alpha: opacity)
mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
tempImageView.image = nil
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 04a835993b58e6cafc3fb6241c81070b91497b4c | [
"Swift"
]
| 1 | Swift | dajahu/Draw-Something---Not-Complete | 556e1faa96b2046df66b79f529e23a4f01b0a634 | f4c923345ed71cc15546644acce64207e86ad251 |
refs/heads/master | <file_sep># imports
import sqlite3
from flask import Flask, render_template, request, session, g, redirect, url_for, \
abort, render_template, flash
from contextlib import closing
from datetime import datetime
# configuration
DATABASE = 'D:/Documents/Bask/bask.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = '<PASSWORD>'
# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
# DATABASE OPERATIONS
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
# ROUTES
@app.route('/')
def hello_world():
cursor = g.db.execute('select * from event')
events = [dict(event_id=row[0], description=row[1],
# parse date from sqlite 'date' (actually a string), then convert to readable format
event_date=datetime.strptime(row[2], '%Y-%m-%d').strftime('%A %b %d'),
# see docs on strftime in python and sqlite3 for formatting
event_time=datetime.strptime(row[3], '%H:%M').strftime('%I:%M %p'),
minors=row[5], cover=row[6], lat=row[7], lng=row[8])
for row in cursor.fetchall()]
return render_template('home.html', events=events)
@app.route('/about')
def about():
return render_template('layout.html')
@app.route('/contact')
def contact():
return render_template('layout.html')
# login
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('Welcome back', app.config['USERNAME'])
return redirect(url_for('band'))
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('band'))
# Band event
@app.route('/band')
def band():
cursor = g.db.execute('select * from event order by event_date desc')
events = [dict(event_id=row[0], description=row[1],
# parse date from sqlite 'date' (actually a string), then convert to readable format
event_date=datetime.strptime(row[2], '%Y-%m-%d').strftime('%A %b %d'),
# see docs on strftime in python and sqlite3 for formatting
event_time=datetime.strptime(row[3], '%H:%M').strftime('%I:%M %p'),
minors=row[5], cover=row[6], lat=row[7], lng=row[8])
for row in cursor.fetchall()]
return render_template('band.html', events=events)
@app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
g.db.execute('insert into event (description, event_date, event_time, cover, lat, lng) '
'values (?, ?, ?, ?, ?, ?)',
[request.form['description'], request.form['event_date'], request.form['event_time'],
request.form['cover'], request.form['lat'], request.form['lng']])
g.db.commit()
flash('New entry was successfully posted')
return redirect(url_for('band'))
# MAIN
if __name__ == '__main__':
app.debug = True
app.run()
<file_sep>Bask
====
Band Finder - A web app in Python using Flask framework.
Enter details about your event and use the autocomplete places feature to enter a location.
See it on the map! Your followers can see when and where you'll be playing.
<file_sep>{% extends "layout.html" %}
{% block body %}
<head>
<title>Bask - Login</title>
</head>
<body>
<h2>Login</h2>
{% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
<form action="{{ url_for('login') }}" method=post>
<dl>
<dt>Username:
<dd><input type=text name=username>
<dt>Password:
<dd><input type=password name=password>
<dd><input type=submit value=Login>
</dl>
</form>
</div> <!-- /container -->
</body>
</html>
{% endblock %}<file_sep>drop table if exists event;
create table event (
id integer primary key autoincrement,
description text not null,
event_date date,
event_time time,
address text,
minors boolean,
cover smallint,
lat text,
lng text
); | 5220243530e1e435f6ebbcec8d27956f1dda2248 | [
"Markdown",
"SQL",
"Python",
"HTML"
]
| 4 | Python | RoxT/Bask | 347031a0d3b437be384eff19633ecf4ee320cc8e | d2d47af2077d9c861d34d3941d89cc22725ee4b0 |
refs/heads/master | <file_sep>dependencies {
compile parent.project('opt4j-core')
compile parent.project('opt4j-satdecoding')
}
<file_sep>/*******************************************************************************
* Copyright (c) 2014 Opt4J
*
* 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.
*******************************************************************************/
package org.opt4j.core.config;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import com.google.inject.Module;
/**
* Helper class for loading {@link PropertyModule} configurations from files or
* retrieving these from XML {@link Node}s.
*
* @author lukasiewycz
*
*/
public class ModuleLoader {
protected final ModuleRegister moduleRegister;
/**
* Constructs a {@link ModuleLoader}.
*
* @param moduleRegister
* the register of all found modules
*/
public ModuleLoader(ModuleRegister moduleRegister) {
super();
this.moduleRegister = moduleRegister;
}
/**
* Loads all modules from a file (as filename).
*
* @param filename
* the file (as filename)
* @return the modules
*/
public Collection<? extends Module> load(String filename) {
File file = new File(filename);
return load(file);
}
/**
* Entity resolver for replacing XML entity references inside the XML
* configuration loaded by Opt4j to configure the active modules and their
* parameters.
*/
public class Opt4JEntityResolver implements EntityResolver {
File configDirectory;
/**
* Constructs a {@link Opt4JEntityResolver}.
*
* @param configDirectory
* the directory where the configuration that is currently
* parsed resides in
*/
Opt4JEntityResolver(File configDirectory) {
this.configDirectory = configDirectory;
}
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
String result = null;
if (systemId.startsWith("opt4j://")) {
if (systemId.equals("opt4j://CONFIGDIR"))
result = configDirectory.getPath();
else
throw new SAXException(
"Entity definition " + systemId + " within protocol opt4j:// is not supported!");
} else if (systemId.startsWith("env://")) {
String var = systemId.substring(6);
result = System.getenv(var);
if (result == null)
throw new SAXException("Environment variable " + var + " used by entity definition " + systemId
+ " is not defined!");
} else
return null;
return new InputSource(new StringReader(result));
}
};
/**
* Loads all modules from a {@link File}.
*
* @param file
* the input file
* @return a list of the modules
*/
public Collection<? extends Module> load(File file) {
List<Module> modules = new ArrayList<>();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setExpandEntityReferences(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new Opt4JEntityResolver(file.getParentFile().getAbsoluteFile()));
Document document = builder.parse(file);
modules.addAll(get(document.getDocumentElement()));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return modules;
}
/**
* Loads all modules from an XML {@link Node}.
*
* @param node
* the XML node
* @return a list of the modules
*/
public Collection<? extends Module> get(Node node) {
List<Module> modules = new ArrayList<>();
JNode application = new JNode(node);
for (JNode child : application.getChildren("module")) {
String name = child.getAttribute("class");
PropertyModule module = null;
try {
Class<? extends Module> clazz = Class.forName(name).asSubclass(Module.class);
module = moduleRegister.get(clazz);
} catch (ClassNotFoundException e) {
System.err.println("Class " + name + " not found.");
}
if (module != null) {
module.setConfiguration(child.getNode());
modules.add(module.getModule());
}
}
return modules;
}
}
<file_sep>dependencies {
compile parent.project('opt4j-core')
}
| 39dfb93cbdbc7a15cb5f54d7de5c12d8de6ce314 | [
"Java",
"Gradle"
]
| 3 | Gradle | JoachimFalk/opt4j | efa64ff865c4705408307f5743276fc9b0fcbce7 | 5f6a658071522e97297e1d3d6a85ab31bfd8f0a3 |
refs/heads/master | <file_sep>package com.siuuu.controller;
import com.siuuu.domain.Session;
import com.siuuu.service.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class SessionController {
@Autowired
private SessionService sessionService;
@GetMapping("/sessionByTopic/{topic}")
public List<Session> searchByTopic(@PathVariable String topic){
return sessionService.sessionOfTopic(topic);
}
@GetMapping("/sessionBySubject/{subject}")
public List<Session> searchBySubject(@PathVariable String subject){
return sessionService.sessionOfSubject(subject);
}
@GetMapping("/sessionByCity/{place}")
public List<Session> searchByPlace(@PathVariable String place){
return sessionService.sessionOnPlace(place);
}
@GetMapping("/sessionByCity/{city}")
public List<Session> searchByCity(@PathVariable String city){
return sessionService.sessionOnCity(city);
}
@GetMapping("/sessions")
public List<Session> searchAll(){
return sessionService.findAll();
}
}
<file_sep>package com.siuuu.domain;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;
@Entity
@Table(schema = "public", name = "usuario")
public class User {
//Attributes
@Id
@Column(name = "c_usuario")
@GeneratedValue(generator = "usuario_c_usuario_seq1", strategy = GenerationType.AUTO)
@SequenceGenerator(name = "usuario_c_usuario_seq1", sequenceName = "public.usuario_c_usuario_seq1", allocationSize = 1)
private long cUser;
@Column(name = "u_foto")
private String uPhoto;
@Column(name = "u_nombres")
private String uFirstName;
@Column(name = "u_apellidos")
private String uLastName;
@NotNull
@Column(name = "u_nombre_usuario")
private String uUsername;
@Column(name = "u_contrasenia")
private String uPassword;
@Column(name = "u_fecha_nacimiento")
private String uBirthday;
@Column(name = "u_pais")
private String uCountry;
@Column(name = "u_institucion")
private String uInstitution;
@Column(name = "u_sexo")
private String uGender;
@Column(name = "u_grado")
private String uDegree;
@Column(name = "u_tipo")
private String uType;
@Column(name = "u_carrera")
private String uCareer;
//@OneToMany(mappedBy = "sUser", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
//private List<Session> uSessions;
//Attributes
//AllArgumentsConstructor
public User(String uPhoto, String uFirstName, String uLastName, String uUsername, String uPassword, String uBirthday, String uCountry, String uInstitution, String uGender, String uDegree, String uType, String uCareer) {
this.uPhoto = uPhoto;
this.uFirstName = uFirstName;
this.uLastName = uLastName;
this.uUsername = uUsername;
this.uPassword = <PASSWORD>;
this.uBirthday = uBirthday;
this.uCountry = uCountry;
this.uInstitution = uInstitution;
this.uGender = uGender;
this.uDegree = uDegree;
this.uType = uType;
this.uCareer = uCareer;
//this.uSessions = uSessions;
}
//AllArgumentsConstructor
//NoArgumentsConstructor
public User() {
}
//NoArgumentsConstructor
//Getters and setters
public long getcUser() {
return cUser;
}
public void setcUser(long cUser) {
this.cUser = cUser;
}
public String getuPhoto() {
return uPhoto;
}
public void setuPhoto(String uPhoto) {
this.uPhoto = uPhoto;
}
public String getuFirstName() {
return uFirstName;
}
public void setuFirstName(String uFirstName) {
this.uFirstName = uFirstName;
}
public String getuLastName() {
return uLastName;
}
public void setuLastName(String uLastName) {
this.uLastName = uLastName;
}
public String getuUsername() {
return uUsername;
}
public void setuUsername(String uUsername) {
this.uUsername = uUsername;
}
public String getuPassword() {
return uPassword;
}
public void setuPassword(String uPassword) {
this.uPassword = uPassword;
}
public String getuBirthday() {
return uBirthday;
}
public void setuBirthday(String uBirthday) {
this.uBirthday = uBirthday;
}
public String getuCountry() {
return uCountry;
}
public void setuCountry(String uCountry) {
this.uCountry = uCountry;
}
public String getuInstitution() {
return uInstitution;
}
public void setuInstitution(String uInstitution) {
this.uInstitution = uInstitution;
}
public String getuGender() {
return uGender;
}
public void setuGender(String uGender) {
this.uGender = uGender;
}
public String getuDegree() {
return uDegree;
}
public void setuDegree(String uDegree) {
this.uDegree = uDegree;
}
public String getuType() {
return uType;
}
public void setuType(String uType) {
this.uType = uType;
}
public String getuCareer() {
return uCareer;
}
public void setuCareer(String uCareer) {
this.uCareer = uCareer;
}
//public List<Session> getuSessions(){
// return uSessions;
//}
//public void setuSessions(List<Session> sessions){
// this.uSessions = uSessions;
//}
//Getters and setters
}
<file_sep>package com.siuuu.service;
import com.siuuu.domain.Session;
import com.siuuu.repository.SessionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SessionServiceImpl implements SessionService{
@Autowired
private SessionRepository sessionRepository;
@Override
public List<Session> sessionOfTopic(String topic) {
return sessionRepository.findBySTopic(topic);
}
@Override
public List<Session> sessionOfSubject(String subject) {
return sessionRepository.findBySSubject(subject);
}
@Override
public List<Session> sessionOnPlace(String place) {
return sessionRepository.findBySPlace(place);
}
@Override
public List<Session> sessionOnCity(String city) {
return sessionRepository.findBySCity(city);
}
@Override
public List<Session> findAll(){
return sessionRepository.findAll();
}
}
<file_sep># Kenary-BackEnd

<file_sep>package com.siuuu.controller;
import com.siuuu.domain.Session;
import com.siuuu.domain.User;
import com.siuuu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/user")
public boolean newUser(@RequestBody @Valid User user){
return userService.save(user);
}
@GetMapping("/login/{username}/{password}")
public User searchUser(@PathVariable("username") String username, @PathVariable("password") String password){
return userService.findByUserForLogin(username, password);
}
@GetMapping("/usersList")
public List<User> usersList(){
return userService.findAll();
}
@PutMapping("/user")
public boolean updateUserByUsername(@RequestBody @Valid User user){
return userService.modifyUser(user);
}
@GetMapping("/user/{Id}")
public User searchUserById(@PathVariable Long Id){
return userService.findUserById(Id);
}
//@GetMapping("/sessionsOf/{username}")
//public List<Session> sessionListByUsername(@PathVariable("username") String username){
// User user = new User();
// user = userService.findSessionsByUser(username);
// List<Session> sessions = null;
// sessions = user.getuSessions();
// return sessions;
//}
}
<file_sep>package com.siuuu.repository;
import com.siuuu.domain.Session;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface SessionRepository extends JpaRepository<Session, Long> {
public List<Session> findBySTopic(String topic);
public List<Session> findBySSubject(String subject);
public List<Session> findBySPlace(String place);
public List<Session> findBySCity(String city);
}
<file_sep>package com.siuuu.service;
import com.siuuu.domain.User;
import com.siuuu.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public boolean save(User user){
try{
userRepository.save(user);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
@Override
public User findUserById(Long Id){
return userRepository.findByCUser(Id);
}
@Override
public User findByUserForLogin(String username, String password) {
return userRepository.findByUUsernameAndUPassword(username, password);
}
@Override
public User findSessionsByUser(String username){
return userRepository.findByUUsername(username);
}
@Override
public void remove(User user){
userRepository.delete(user);
}
@Override
public boolean modifyUser(User user){
try {
userRepository.save(user);
return true;
} catch(Exception e){
e.printStackTrace();
return false;
}
}
}
| ee3026857533175861e08b2609462e8b511ff02d | [
"Markdown",
"Java"
]
| 7 | Java | SIUUUUU/Kenary-BackEnd | 2c46db4c9adab66a9cc08ac7e906afb547f3cee1 | 8d60b8d966430cd304b9dfc07f680a2d3fb8313a |
refs/heads/master | <file_sep><?php
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
$lang = array_merge($lang, [
'MEDUSA_NO_USER_INFO' => 'MEDUSA user information not available.',
]);
| 948971c5dca0fd81f075dc24237776acf8b11b3c | [
"PHP"
]
| 1 | PHP | TRMN/medusa-auth | 24ae2135cb8808dee16e542f68bb531be9816e04 | 09fb54bbab7552cde5ee071d237a73e28878af55 |
refs/heads/master | <repo_name>jrw77/NumbersOrPrimes<file_sep>/README.md
# NumbersOrPrimes
Example project for iOS class (CSCI 423) at the University of Wisconsin, Parkside, taught by Prof. Weimar.
<file_sep>/NumbersOrPrimes/PrimeTableViewCell.swift
//
// PrimeTableViewCell.swift
// TableViewPrimes
//
// Created by weimar on 2/17/16.
// Copyright © 2016 Weimar. All rights reserved.
//
import UIKit
class PrimeTableViewCell: UITableViewCell {
@IBOutlet weak var primeImage: UIImageView!
@IBOutlet weak var primeNumber: UILabel!
@IBOutlet weak var primeDecomp: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/NumbersOrPrimes/PrimeDataSource.swift
//
// PrimeDataSource.swift
// TableViewPrimes
//
// Created by weimar on 2/17/16.
// Copyright © 2016 Weimar. All rights reserved.
//
import Foundation
/*
PrimeDataSource is a helper class to determin all prime nubers up to a certain maximum.
The position of the prime numbers can be determined, and the prime decomposition calculated.
*/
class PrimeDataSource {
var sieve : [Bool]
var primes : [Int] = []
let MAX = 1000000
init(var max: Int){
if (max > MAX+1){
max = MAX+1
}
print("Init to \(max)")
sieve = [Bool](count: max, repeatedValue: true)
sieve[0] = false
sieve[1] = false
var i=2
for ( ; i < max && i*i <= max; i++ ) {
if (sieve[i]){
primes.append(i)
for (var j=2; i*j<max; j++ ) {
sieve[i*j] = false;
}
}
}
for ( ; i < max ; i++ ) {
if (sieve[i]){
primes.append(i)
}
}
}
var size: Int {
return sieve.endIndex+1
}
func getName (num: Int) -> String {
return String(num)
}
func isPrime(num: Int) -> Bool {
return sieve[num]
}
func decomposition( var num: Int) -> [(Int, Int)]{
var result = [(Int, Int)]()
var i = 0
while ( num > 1){
var j = 0
let base = primes[i]
while ( num % base == 0) {
num /= base
j = j+1
}
if (j != 0){
result.append( (base, j) )
}
i = i + 1
}
return result
}
func indexInPrimes(num: Int) -> Int {
let ind = primes.indexOf(num)
if let index = ind {
return index+1
}else{
return -1
}
}
func prime(atPosition pos: Int) -> Int? {
if (pos <= primes.endIndex){
return primes[pos-1]
}else{
return nil;
}
}
func decompositionAsProduct(num: Int) -> String {
var res=""
let decomp = decomposition(num)
var first = true
for (base, exp) in decomp {
for _ in 1...exp {
if (first){
first = false
}else{
res.appendContentsOf("*")
}
res.appendContentsOf(String(base))
}
}
return res
}
}
<file_sep>/NumbersOrPrimes/PrimeTableViewController.swift
//
// PrimeTableViewController.swift
// TableViewPrimes
//
// Created by weimar on 2/17/16.
// Copyright © 2016 Weimar. All rights reserved.
//
import UIKit
class PrimeTableViewController: UITableViewController {
var dataSource: PrimeDataSource = PrimeDataSource(max: 20)
let primeImage = UIImage(named: "check_ok.png")
let nonPrimeImage = UIImage(named: "check_cross.png")
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
tableView.estimatedRowHeight = 50
// the follwing is from www.raywunderlich.com/113772/uiserachcontroller-tutorial
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
// searchController.searchDisplayController?.displaysSearchBarInNavigationBar = true
searchController.searchBar.placeholder = NSLocalizedString("Number or #pos or x*y*z", comment: "")
searchController.searchBar.searchBarStyle = .Minimal
searchController.searchBar.keyboardType = .NumberPad
definesPresentationContext = true
// tableView.tableHeaderView = searchController.searchBar
navigationItem.titleView = searchController.searchBar
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1 // use just one section.
}
// return the number of rows.
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.size // can be changed by changing the data source and forcing the tableview to reload.
}
// creates/recycles a cell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell =
self.tableView.dequeueReusableCellWithIdentifier( "PrimeTableCell", forIndexPath: indexPath)
as! PrimeTableViewCell
var row = indexPath.row
// increase table size if necessary
if (row == dataSource.size-1){
print (" resize to \( row*2 )" )
// increase by doubling the max.
// easily scales to thousands of cells!
dataSource = PrimeDataSource(max: row*2)
tableView.reloadData()
}
if (row > dataSource.MAX){
row = dataSource.MAX;
}
// set content of cell.
cell.primeNumber.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cell.primeNumber.text = dataSource.getName(row)
cell.primeImage.image = dataSource.isPrime(row) ? primeImage : nonPrimeImage
cell.primeDecomp.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cell.primeDecomp.text = dataSource.isPrime(row)
? "Prime # \(dataSource.indexInPrimes(row)) of \(dataSource.primes.endIndex)"
: String(dataSource.decompositionAsProduct(row))
return cell
}
// Helper to select a certain number
func selectNumber(number: Int){
print(" select number \(number)")
if (number >= 1000000){
print(" Error: \(number) is too big!")
let searchText = searchController.searchBar.text!
searchController.searchBar.text = searchText.substringToIndex(searchText.endIndex.predecessor());
alert(title: "Sorry", text: "\(number) is too big!")
// MyToast(view: self.view, text: " Error: \(number) is too big!", duration: 5.0)
return
}
if (number >= dataSource.size){
dataSource = PrimeDataSource(max: number + 15)
tableView.reloadData()
}
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: number, inSection: 0),
atScrollPosition: UITableViewScrollPosition.Top,
animated: false)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowPrimeDetail" {
let detailViewController = segue.destinationViewController
as! PrimeDetailViewController
let myIndexPath = self.tableView.indexPathForSelectedRow!
let row = myIndexPath.row
detailViewController.number = row
}else if segue.identifier == "GoToAboutView" {
// no special action.
}else{
print(" Error: seque is "+segue.description)
}
}
// http://stackoverflow.com/questions/12509422/how-to-perform-unwind-segue-programmatically
@IBAction func unwindToContainerVC(segue: UIStoryboardSegue) {
// action here when coming back.
}
func alert(title title: String, text: String){
// create the alert
let alert = UIAlertController(title: title, message: text, preferredStyle: UIAlertControllerStyle.Alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
// show the alert
self.presentViewController(alert, animated: true, completion: nil)
}
}
extension PrimeTableViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController){
if let num = Int(searchController.searchBar.text!){
selectNumber(num)
}else if let text = searchController.searchBar.text {
if text.containsString("*"){
let numText = text.substringToIndex(text.rangeOfString("*")!.startIndex);
print ("numText =\(numText)")
if let num1 = Int(numText){
var prod = num1
var remText = text.substringFromIndex(text.rangeOfString("*")!.endIndex)
while (remText != ""){
if remText.containsString("*"){
let numText = remText.substringToIndex(remText.rangeOfString("*")!.startIndex);
print ("numText =\(numText)")
if let num2 = Int(numText){
prod *= num2
}
remText = remText.substringFromIndex(remText.rangeOfString("*")!.endIndex)
}else{ // probbaly another number?
if let num2 = Int(remText){
prod *= num2
}
remText = ""
}
}
selectNumber(prod)
}
}else if text.containsString("#"){
let remText = text.substringFromIndex(text.rangeOfString("#")!.endIndex);
print ("#remText =\(remText)")
if let num = Int(remText){
if (num < 78500){
while (dataSource.prime(atPosition: num) == nil){
dataSource = PrimeDataSource(max: dataSource.size * 2)
tableView.reloadData()
}
selectNumber(dataSource.primes[num-1])
}else{
// error
selectNumber(1000000);
}
}
}
}
}
}
<file_sep>/NumbersOrPrimes/PrimeDetailViewController.swift
//
// PrimeDetailViewController.swift
// NavigationPrimes
//
// Created by weimar on 2/17/16.
// Copyright © 2016 Weimar. All rights reserved.
//
import UIKit
class PrimeDetailViewController: UIViewController {
var number : Int?
let webPrefix = "http://m.wolframalpha.com/input/?i="
@IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
if let num = number {
self.title = "Number details: \(num)"
}
if let num = number {
let webURL = NSURL(string: webPrefix+String(num)+"&x=0&y=-30")
let urlRequest = NSURLRequest(URL: webURL!)
print("url: \(urlRequest)")
myWebView.loadRequest(urlRequest)
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
}
| b45982729958f41d6afefc2f2442fc6f719de1f5 | [
"Markdown",
"Swift"
]
| 5 | Markdown | jrw77/NumbersOrPrimes | e1d1878853523b77629176afb72c23596e3e6574 | 8b51ef56db9aac1ebbe564be7d59e2454ef2c282 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
COMMANDS=(
"Start"
"Stop"
"Track"
"Cancel"
"Continue"
# ["Undo"]="undo"
# ["Join"]="join"
# ["Split"]="split"
# ["Modify"]="modify"
# ["Resize"]="resize"
# ["Shorten"]="shorten"
# ["Lengthen"]="lengthen"
# ["Move"]="move"
# ["Delete"]="delete"
# ["Cancel"]="cancel"
# ["Track"]="track"
# ["Stop"]="stop"
# ["Start"]="start"
)
list_commands() {
echo -en "\0message\x1f<b>Quit</b> to exit\n"
for command in ${COMMANDS[@]}
do
echo $command
done
echo -en "Quit\0icon\x1fexit\n"
}
_tags() {
TAGS=($(timew tags :week))
S_TAGS=${TAGS[@]:4}
C_TAGS=()
NEW_TAGS=()
for tag in ${S_TAGS[@]}
do
if [[ "$tag" != "-" ]]; then
C_TAGS+=($tag)
else
echo "${C_TAGS[@]}"
unset C_TAGS
fi
done
}
_intervals() {
INTERVALS=$(timew summary :ids :yesterday)
declare -A ITEMS
declare -- IDX
for i in ${INTERVALS[@]}
do
if [[ $i =~ @[0-9] ]]; then
IDX="${i}"
elif [[ -n $IDX ]]; then
ITEMS[$i]="$IDX"
unset IDX
fi
done
for int in ${!ITEMS[@]}
do
echo $int
done
}
# Check if data file exists. Create it if not.
if [[ ! -f $HOME/.config/rofi/time-warrior.dat ]]; then
touch $HOME/.config/rofi/time-warrior.dat
fi
declare -A CONF
if [[ -z "$@" ]]; then
list_commands
else
if [[ "$@" = "Quit" ]]; then
exit 0
fi
if [[ "$@" = "Start" ]]; then
echo -en "\x00prompt\x1fTag: \n"
echo -en "\0message\x1f<b>Quit</b> to exit\n"
_tags
echo -en "Quit\0icon\x1fexit\n"
elif [[ "$@" = "Stop" ]]; then
timew stop >/dev/null
exit 0
elif [[ "$@" = "Cancel" ]]; then
timew cancel >/dev/null
elif [[ "$@" = "Continue" ]]; then
_intervals
else
timew start "$@" >/dev/null
exit 0
fi
fi | b760c3ee83c78ea577f4522feec557b7ebbee122 | [
"Shell"
]
| 1 | Shell | DaeronAlagos/rofi-scripts | bf1884cf6103b3aeab147d4dc35cb90167f18c33 | 75f2a7e4087cc263d179e9301366cecae0b6c821 |
refs/heads/master | <file_sep>const { ApolloServer, gql } = require('apollo-server');
const Schema = gql`
type Mutation {
createusers(value : Userinput) : ReturnMessage
addarticle(value : Articleinput) : ReturnMessage
}
type Query {
users : [User]
user(id : String!) : User
login(email: String!, password : String!): User
article(id : String) : Article
articles : [Article]
}
type User {
id : String
surname : String
othername : String
email : String
password : String
token : String
article : [Article]
}
input Userinput {
surname : String!
othername : String!
email : String!
password : String!
}
type ReturnMessage{
isSuccess : Boolean
message : String
}
type Article{
id : String
title : String
content : String
type : String
createdOn : String
isActive : Boolean
createdBy : String
user : User
}
input Articleinput{
id : String
title : String
content : String
type : String
isActive : Boolean
createdBy : String
}
`;
module.exports = Schema;<file_sep>const path = require('path');
const fs = require('fs');
const fullpath = path.join(path.dirname
(process.mainModule.filename), 'data', 'user.json');
const articlefullpath = path.join(path.dirname
(process.mainModule.filename), 'data', 'article.json');
let userList = [];
let articleList = [];
const Queries = {
users : () =>{
try{
let result = fs.readFileSync(fullpath);
userList = JSON.parse(result);
return userList;
}
catch(e)
{
console.log(e);
return userList;
}
},
article : () => {
try{
let result = fs.readFileSync(articlefullpath);
articleList = JSON.parse(result);
console.log(articleList);
return articleList;
}
catch(e)
{
console.log(e);
return articleList;
}
}
}
module.exports = Queries;<file_sep>const jwt = require('jsonwebtoken');
const Context = ({ req }) => {
let user = null;
try {
const token = req.headers.authorization.replace('Bearer ', '');
user = jwt.verify(token, JWT_SECRET);
} catch (error) {}
return { user };
}
module.exports = Context;<file_sep># GraphQLAPI-Blog-ApolloServer
simple blog api using graphql
<file_sep>const db = require('./data/dbqueries');
const path = require('path');
const fs = require('fs');
const {v4} = require('uuid');
const express = require('express');
app = express();
const moment = require('moment');
const todaydate = moment().format('MMMM Do YYYY, h:mm:ss a');
let guid = v4();
let error = [];
const fullpath = path.join(path.dirname(process.mainModule.filename), 'data', 'user.json');
const userfullpath = path.join(path.dirname(process.mainModule.filename), 'data', 'user.json');
const articlefullpath = path.join(path.dirname(process.mainModule.filename), 'data', 'article.json');
const Mutation = {
Mutation: {
createusers : (_, {value}) => {
try{
let result = db.users();
console.log(result);
const user = {id: guid, surname : value.surname, othername : value.othername, email : value.email, password : <PASSWORD>.<PASSWORD>};
const match = result.find(user => user.email === values.email);
if (match) throw Error('This user already exists');
result.push(user);
fs.writeFileSync(userfullpath, JSON.stringify(result));
return {isSuccess : true, message:'User created successfully'};
}
catch(e)
{
error.push({action : 'usercreation', errormessage : e.message})
return {isSuccess : false, message:'user creation failed'};
}
finally {
console.log(error);
}
},
addarticle : (_, {value}) => {
try{
let result = db.article();
console.log(result);
const article = {id: guid, title : value.title, content : value.content, type : value.type, isActive : value.isActive, createdBy : value.createdBy, createdOn : todaydate};
const match = result.find(article => article.title === values.title);
if (match) throw Error('This article already exists');
result.push(article);
fs.writeFileSync(articlefullpath, JSON.stringify(result));
return {isSuccess : true, message:'User created successfully'};
}
catch(e)
{
error.push({action : 'addarticle', errormessage : e.message})
return {isSuccess : false, message:'article creation failed'};
}
finally {
console.log(error);
}
},
},
};
module.exports = Mutation; | 3abbf9dd6a3c2a02a3edd4de364b30ab19ad3d15 | [
"JavaScript",
"Markdown"
]
| 5 | JavaScript | touthtek/GraphQLAPI-Blog-ApolloServer | 24afcb289eff35418f8ee3cd968bb8fcf2927a03 | 2bbdc0cf79c67386c633404067c8ee972d121974 |
refs/heads/master | <repo_name>windersan/TravelApp_PHPImpl_MySQLImpl<file_sep>/app/Login.php
<?php
include 'User.php';
$user = new User();
$user->username = $_GET["_username"];
$user->password = $_GET["_password"];
$_user = getUser($user->username, $user->password);
header('Location: index.html');
function getConnection() {
$servername = "127.0.0.1";
$dbname = "users_test2";
$username = "root";
$password = "<PASSWORD>";
try {
$connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo "EXCEPTION: Connection failed : " . $e->getMessage();
}
return $connection;
}
function getUser($username, $password) {
try {
$connection = getConnection();
$sql = "SELECT * FROM users_test2.user WHERE username = '$username'";
$result = $connection->query($sql);
$user_ = new User();
foreach ($result as $row){
$user_->firstname = $row['firstname'];
break;
}
$connection = null;
} catch (Exception $e) {
echo "EXCEPTION : Select failed : " . $e->getMessage();
}
return $user_;
}
exit();
<file_sep>/app/User.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of User
*
* @author devin
*/
class User {
public $firstname = '';
public $lastname = '';
public $username = '';
public $email = '';
public $password = '';
public function validate(){
if($this->firstname === null || $this->firstname === '') return false;
if($this->lastname === null || $this->lastname === '') return false;
if($this->username === null || $this->username === '') return false;
if($this->email === null || $this->email === '') return false;
if($this->password === null || $this->password === '') return false;
return true;
}
}
<file_sep>/app/Process.php
<?php
include 'User.php';
$user = new User();
$user->firstname = $_POST["first"];
$user->lastname = $_POST["last"];
$user->email = $_POST["email"];
$user->username = $_POST["username"];
$user->password = $_POST["<PASSWORD>"];
$isValid = $user->validate();
//if(isValid == true) header('Location: index.html');
//else header('Location: create.html');
insertUser($user->firstname, $user->lastname, $user->email, $user->username, $user->password);
if(isValid == true) header('Location: index.html');
else header('Location: create.html');
//header('Location: index.html');
function getConnection(){
$servername = "127.0.0.1";
$dbname = "users_test2";
$username = "root";
$password = "<PASSWORD>";
try{
$connection = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
echo "EXCEPTION: Connection failed : " . $e->getMessage();
}
return $connection;
}
function insertUser($firstname, $lastname, $email, $username, $password){
try{
$connection = getConnection();
$sql = "INSERT INTO user (firstname, lastname, email, username, password) "
. "VALUES ('$firstname', '$lastname', '$email', '$username', '$password')";
$connection->exec($sql);
$connection = null;
} catch(Exception $e){
echo "EXCEPTION : Insert failed : " . $e->getMessage();
}
}
exit();
| ea97c32af322e5819b5e0f918e3fef83ebed5f77 | [
"PHP"
]
| 3 | PHP | windersan/TravelApp_PHPImpl_MySQLImpl | a3a47e0ceea47c645202775d726f42c7517e9498 | 9ef322a030df122ae613c8720c68f768a7894b12 |
refs/heads/master | <file_sep>using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace SnippetsExtension
{
public class Snippet
{
public string Template { get; set; }
public string Value { get; set; }
public bool BeginOnly { get; set; }
public bool UsesRegex { get; set; }
public bool SelectTrigger { get; set; }
public bool ContainsPythonCode { get; set; }
public string PythonCode { get; set; }
public int PythonPosition { get; set; }
public static string ClearValue(string value)
{
return Regex.Replace(value, @"(?<!\\)\$\d", "");
}
public static string ClearValue(string value, int index)
{
return Regex.Replace(value, @"(?<!\\)\$" + index, "");
}
public static int Index(string value, int index)
{
value = Regex.Replace(value, $@"(?<!\\)\$[^{index}]", "");
var match = Regex.Match(value, @"(?<!\\)\$" + index);
return match.Success ? match.Index : -1;
}
public static string MiddleUpdate(string value, string oldword, string newword, int index)
{
var find = @"(?<!\\)\$" + index;
return Regex.Replace(value, find + Regex.Escape(oldword), "$$" + index + newword.Replace("$", "$$"));
}
}
}
<file_sep>using System;
using System.Windows;
namespace NotepadOnlineDesktop.Model
{
public static class ThemeManager
{
public static void Update()
{
switch (Properties.Settings.Default.theme)
{
case "light": SetLightTheme(); break;
case "dark": SetDarkTheme(); break;
}
}
static void SetDarkTheme()
{
Clear();
Add("Dark");
Add("Common");
}
static void SetLightTheme()
{
Clear();
Add("Light");
Add("Common");
}
static void Clear()
{
Application.Current.Resources.Clear();
}
static void Add(string name)
{
var uri = new Uri($@"Themes\{name}.xaml", UriKind.Relative);
var dict = (ResourceDictionary)Application.LoadComponent(uri);
Application.Current.Resources.MergedDictionaries.Add(dict);
}
}
}
<file_sep>using System.Windows;
namespace NotepadOnlineDesktop.View
{
public partial class ManagerWindow : Window
{
public ManagerWindow()
{
InitializeComponent();
var viewModel = new ViewModel.ManagerWindow();
DataContext = viewModel;
}
}
}
<file_sep>using System.Windows;
namespace NotepadOnlineDesktop.View
{
public partial class ReplaceWindow : Window
{
public ViewModel.ReplaceWindow ViewModel;
public ReplaceWindow()
{
InitializeComponent();
text.Focus();
DataContext = ViewModel = new ViewModel.ReplaceWindow();
}
}
}
<file_sep>using System.Windows;
namespace NotepadOnlineDesktop.View
{
public partial class MainWindow : Window
{
public static MainWindow Instance;
public MainWindow()
{
Model.ThemeManager.Update();
InitializeComponent();
var viewModel = new ViewModel.MainWindow(text, extensions)
{
Close = Close
};
Closing += viewModel.Closing;
CommandBindings.AddRange(viewModel.Bindings);
DataContext = viewModel;
Instance = this;
}
}
}
<file_sep>using System;
namespace NotepadOnlineDesktop.Model
{
public class FindEventArgs : EventArgs
{
public string Word { get; private set; }
public bool IgnoreCase { get; private set; }
public bool Regex { get; private set; }
public bool UpDirection { get; private set; }
public bool DownDirection { get; private set; }
public FindEventArgs(string word, bool ignoreCase, bool regex, bool upDirection, bool downDirection)
{
Word = word ?? throw new ArgumentNullException(nameof(word));
IgnoreCase = ignoreCase;
Regex = regex;
UpDirection = upDirection;
DownDirection = downDirection;
}
}
}
<file_sep>using System.Windows;
namespace NotepadOnlineDesktop.View
{
public partial class FindWindow : Window
{
public ViewModel.FindWindow ViewModel;
public FindWindow()
{
InitializeComponent();
text.Focus();
DataContext = ViewModel = new ViewModel.FindWindow();
}
}
}
<file_sep>namespace SnippetsExtension
{
public enum ImporterState
{
ReadingTemplate,
ReadingValue
}
}
<file_sep>using CloudExtension.Properties;
using NotepadOnlineDesktopExtensions;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using static DataBase.ReturnCodeDescriptions;
namespace CloudExtension
{
[Export(typeof(IExtension))]
public class Main : IExtension
{
public string Name { get; } = Resources.Name;
public string Version { get; } = "1.0";
public string Author { get; } = "DMSoft";
public string Description { get; } = Resources.Info;
public List<MenuItem> Menu
{
get
{
return new List<MenuItem>()
{
openFolder,
update,
saveInCloud,
delete,
properties
};
}
}
MenuItem openFolder;
MenuItem update;
MenuItem saveInCloud;
MenuItem delete;
MenuItem properties;
IApplicationInstance app;
public Main()
{
saveInCloud = new MenuItem() { Header = Resources.SaveInCloud };
saveInCloud.Click += SaveInCloud_Click;
delete = new MenuItem() { Header = Resources.DeleteFile };
delete.Click += Delete_Click;
openFolder = new MenuItem() { Header = Resources.OpenCloudFolder };
openFolder.Click += OpenFolder_Click;
update = new MenuItem() { Header = Resources.UpdateFiles };
update.Click += Update_Click;
properties = new MenuItem() { Header = Resources.Properties };
properties.Click += Properties_Click;
}
public async Task OnStart(IApplicationInstance instance)
{
app = instance;
if (!Directory.Exists(Settings.Default.path))
{
Settings.Default.path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\NotepadOnline\";
Directory.CreateDirectory(Settings.Default.path);
}
if (Settings.Default.email.Length == 0)
return;
var result = await DataBase.Manager.LoginAsync(Settings.Default.email, Settings.Default.password, Settings.Default.token);
if (result != DataBase.ReturnCode.Success)
{
MessageBox.Show(Resources.LogInFailed + ". " + result.GetDescription(), Resources.Name);
return;
}
await UpdateFolderAsync();
}
public async Task OnStop()
{
await Task.CompletedTask;
}
async void SaveInCloud_Click(object sender, RoutedEventArgs e)
{
if (DataBase.Manager.Status != DataBase.ManagerStatus.Ready)
{
MessageBox.Show(Resources.SignInFirstly, Resources.FileNotSaved);
return;
}
string name;
if (app.Name != null)
{
name = app.Name.Substring(app.Name.LastIndexOf("\\") + 1);
name = name.Substring(0, name.LastIndexOf('.'));
}
else
{
var input = new InputNameWindow();
input.ShowDialog();
if (!input.Canceled)
name = input.Text;
else
return;
}
SaveToFolder(name, app.Text);
await SaveToCloudAsync(name, app.Text);
}
void Delete_Click(object sender, RoutedEventArgs e)
{
if (app.Name == null || !app.Name.StartsWith(Settings.Default.path) || !app.Name.EndsWith(".txt"))
{
MessageBox.Show(Resources.OpenFromCloudToOperate, Resources.IllegalFile);
return;
}
var name = app.Name.Substring(Settings.Default.path.Length);
name = name.Substring(0, name.Length - 4);
var result = DataBase.Manager.DelData(name);
if (result != DataBase.ReturnCode.Success)
{
MessageBox.Show(Resources.FileNotDeleted + ". " + result.GetDescription(), Resources.DeletingFailed);
return;
}
File.Delete(app.Name);
MessageBox.Show(Resources.FileDeleted, Resources.Success);
}
void OpenFolder_Click(object sender, RoutedEventArgs e)
{
app.OpenFolder(Settings.Default.path);
}
async void Update_Click(object sender, RoutedEventArgs e)
{
if (DataBase.Manager.Status != DataBase.ManagerStatus.Ready)
{
MessageBox.Show(Resources.SignInFirstly, Resources.UpdatingFailed);
return;
}
var result = DataBase.Manager.GetNames();
if (result.Item1 != DataBase.ReturnCode.Success)
MessageBox.Show(Resources.FilesNotUpdated + ". " + result.Item1.GetDescription(), Resources.UpdatingFailed);
await UpdateFolderAsync();
MessageBox.Show(Resources.FilesUpdated, Resources.Success);
}
void Properties_Click(object sender, RoutedEventArgs e)
{
new PropertiesWindow().ShowDialog();
}
async Task UpdateFolderAsync()
{
ClearFolder();
var names = (await DataBase.Manager.GetNamesAsync()).Item2;
foreach (var name in names)
SaveToFolder(name, (await DataBase.Manager.GetDataAsync(name)).Item3);
}
void SaveToFolder(string name, string text)
{
File.WriteAllText(Settings.Default.path + name + ".txt", text, Encoding.UTF8);
}
async Task SaveToCloudAsync(string name, string text)
{
var result = await DataBase.Manager.AddDataAsync(name, Resources.Name, app.Text);
if (result == DataBase.ReturnCode.Success)
MessageBox.Show(Resources.FileInCloud + ": " + name, Resources.Success);
else if (result == DataBase.ReturnCode.DataAlreadyExists)
{
if (MessageBox.Show(Resources.DoYouWantToReplace + $" \"{name}\"?", Resources.ReplacingFile, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
result = await DataBase.Manager.EditDescriptionAsync(name, Resources.Name);
if (result == DataBase.ReturnCode.Success)
result = await DataBase.Manager.EditTextAsync(name, app.Text);
if (result != DataBase.ReturnCode.Success)
MessageBox.Show(Resources.FileNotSaved + ". " + result.GetDescription(), Resources.FileNotSaved);
}
}
else
MessageBox.Show(Resources.FileNotSaved + ". " + result.GetDescription(), Resources.FileNotSaved);
}
private void ClearFolder()
{
foreach (var file in new DirectoryInfo(Settings.Default.path).GetFiles())
file.Delete();
}
}
}
<file_sep>using Microsoft.Win32;
using NotepadOnlineDesktopExtensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace NotepadOnlineDesktop.ViewModel
{
class MainWindow : INotifyPropertyChanged
{
class Instance : IApplicationInstance
{
public event InputHandler OnInput;
public string Text
{
get
{
return GetText();
}
set
{
SetText(value);
}
}
public string Name
{
get
{
return GetName();
}
}
public int SelectionStart
{
get
{
return GetSelectionStart();
}
set
{
SetSelectionStart(value);
}
}
public int SelectionLength
{
get
{
return GetSelectionLength();
}
set
{
SetSelectionLength(value);
}
}
public void Open(string name)
{
OpenFile(name);
}
public void OpenFolder(string path)
{
OpenDirectory(path);
}
public bool RaiseOnInput(char key)
{
var args = new NotepadOnlineDesktopExtensions.InputEventArgs(key);
OnInput?.Invoke(this, args);
return args.Handled;
}
public bool RaiseOnInput(SpecKey specKey)
{
var args = new NotepadOnlineDesktopExtensions.InputEventArgs(specKey);
OnInput?.Invoke(this, args);
return args.Handled;
}
public Func<string> GetText;
public Action<string> SetText;
public Func<string> GetName;
public Func<int> GetSelectionStart;
public Action<int> SetSelectionStart;
public Func<int> GetSelectionLength;
public Action<int> SetSelectionLength;
public Action<string> OpenFile;
public Action<string> OpenDirectory;
}
string name;
bool saved = true;
TextBox text;
string Name
{
get
{
return name;
}
set
{
name = value;
OnPropertyChanged("WindowTitle");
}
}
bool Saved
{
get
{
return saved;
}
set
{
saved = value;
OnPropertyChanged("WindowTitle");
}
}
public string WindowTitle
{
get
{
return "Notepad.Online" + (Saved ? "" : " (" + Properties.Resources.Edited + ")") + (Name == null ? "" : " | " + Name);
}
}
public bool TextWrap
{
get
{
return Properties.Settings.Default.textwrap;
}
set
{
Properties.Settings.Default.textwrap = value;
Properties.Settings.Default.Save();
OnPropertyChanged(nameof(TextWrap));
OnPropertyChanged(nameof(WrappingType));
}
}
public TextWrapping WrappingType
{
get
{
return Properties.Settings.Default.textwrap ? TextWrapping.Wrap : TextWrapping.NoWrap;
}
}
public Action Close { get; set; }
public List<CommandBinding> Bindings
{
get
{
return new List<CommandBinding>()
{
new CommandBinding(ApplicationCommands.New, New_Executed),
new CommandBinding(ApplicationCommands.Open, Open_Executed),
new CommandBinding(ApplicationCommands.Save, Save_Executed, Save_CanExecute),
new CommandBinding(ApplicationCommands.SaveAs, SaveAs_Executed),
new CommandBinding(ApplicationCommands.Close, Exit_Executed),
new CommandBinding(ApplicationCommands.Find, Find_Executed),
new CommandBinding(ApplicationCommands.Replace, Replace_Executed)
};
}
}
public Model.ActionCommand Settings
{
get
{
return new Model.ActionCommand(sender =>
{
var window = new View.SettingsWindow();
window.ViewModel.SettingsUpdated += (s, e) =>
{
Model.ThemeManager.Update();
UpdateMainTextBox();
};
window.ShowDialog();
});
}
}
public Model.ActionCommand Manager
{
get
{
return new Model.ActionCommand(sender =>
{
new View.ManagerWindow().ShowDialog();
});
}
}
public Model.ActionCommand About
{
get
{
return new Model.ActionCommand(sender =>
{
MessageBox.Show(Properties.Resources.Info, Properties.Resources.About, MessageBoxButton.OK, MessageBoxImage.Information);
});
}
}
public MainWindow(TextBox text, MenuItem extensionsParent)
{
if (Properties.Settings.Default.fontFamily is null)
Properties.Settings.Default.fontFamily = Fonts.SystemFontFamilies.Where(font => font.ToString() == "Consolas").First();
this.text = text;
UpdateMainTextBox();
text.TextChanged += Text_TextChanged;
TextWrap = Properties.Settings.Default.textwrap;
var args = Environment.GetCommandLineArgs();
if (args.Length > 1)
try
{
Open(args[1]);
}
catch (Exception e)
{
MessageBox.Show(Properties.Resources.UnableToLoadFile + ": " + e.Message, Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (Properties.Settings.Default.enableExtensions)
{
var instance = new Instance
{
GetName = () => name,
GetText = () => text.Text,
SetText = value => text.Text = value,
GetSelectionStart = () => text.SelectionStart,
SetSelectionStart = (value) => text.SelectionStart = value,
GetSelectionLength = () => text.SelectionLength,
SetSelectionLength = (value) => text.SelectionLength = value,
OpenFile = name => Open(name),
OpenDirectory = path =>
{
if (AskBeforeClear())
{
var name = GetNameToOpen(path);
if (name != null)
Open(name);
}
}
};
text.PreviewKeyDown += (s, e) =>
{
if (e.Key == Key.Tab)
e.Handled = instance.RaiseOnInput('\t');
if (e.Key == Key.Space)
e.Handled = instance.RaiseOnInput(' ');
if (e.Key == Key.Enter)
e.Handled = instance.RaiseOnInput('\r');
if (e.Key == Key.Back)
e.Handled = instance.RaiseOnInput(SpecKey.Backspace);
if (e.Key == Key.Escape)
e.Handled = instance.RaiseOnInput(SpecKey.Escape);
if (e.Key == Key.Delete)
e.Handled = instance.RaiseOnInput(SpecKey.Delete);
};
text.PreviewTextInput += (s, e) =>
{
if (e.Text.Length > 0)
e.Handled = instance.RaiseOnInput(e.Text[0]);
};
try
{
#if DEBUG
Model.ExtensionManager.Load(@"C:\Projects\NotepadOnlineDesktop\SnippetsExtension\bin\Debug\");
//Model.ExtensionManager.Load(@"C:\Projects\NotepadOnlineDesktop\CloudExtension\bin\Debug\");
#else
Model.ExtensionManager.Load(@"Extensions\");
#endif
Model.ExtensionManager.Initialize(instance, extensionsParent);
}
catch (DirectoryNotFoundException)
{ }
}
else
extensionsParent.Visibility = Visibility.Collapsed;
}
public void Closing(object sender, CancelEventArgs e)
{
if (Properties.Settings.Default.askonexit)
e.Cancel = !AskBeforeClear();
}
void Text_TextChanged(object sender, TextChangedEventArgs e)
{
Saved = false;
}
void New_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (AskBeforeClear())
{
text.Text = "";
Name = null;
Saved = true;
}
}
void Open_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (AskBeforeClear())
{
var name = GetNameToOpen();
if (name != null)
Open(name);
}
}
void Save_Executed(object sender, ExecutedRoutedEventArgs e)
{
Save(Name);
}
void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = Name != null && !Saved;
}
void SaveAs_Executed(object sender, ExecutedRoutedEventArgs e)
{
var name = GetNameToSave();
if (name != null)
Save(name);
}
void Exit_Executed(object sender, ExecutedRoutedEventArgs e)
{
Close();
}
void Find_Executed(object sender, ExecutedRoutedEventArgs e)
{
var findWindow = new View.FindWindow
{
Owner = View.MainWindow.Instance
};
findWindow.ViewModel.RequestFind += (s, args) =>
{
string block;
if (args.DownDirection)
block = text.Text.Substring(text.SelectionStart + text.SelectionLength);
else
block = text.Text.Substring(0, text.SelectionStart);
var word = args.Regex ? args.Word : Regex.Escape(args.Word);
var options = RegexOptions.Multiline;
if (args.IgnoreCase)
options |= RegexOptions.IgnoreCase;
if (args.UpDirection)
options |= RegexOptions.RightToLeft;
Match match = null;
try
{
match = Regex.Match(block, word, options);
}
catch (ArgumentException)
{
MessageBox.Show(Properties.Resources.IllegalArgument, Properties.Resources.Error, MessageBoxButton.OK);
text.Focus();
return;
}
if (!match.Success)
{
MessageBox.Show(Properties.Resources.NoMatches, Properties.Resources.Completed, MessageBoxButton.OK, MessageBoxImage.Information);
text.Focus();
return;
}
var index = match.Index;
if (args.DownDirection)
index += text.SelectionStart + text.SelectionLength;
text.Focus();
text.Select(index, match.Length);
};
findWindow.Show();
}
private void Replace_Executed(object sender, ExecutedRoutedEventArgs e)
{
var replaceWindow = new View.ReplaceWindow
{
Owner = View.MainWindow.Instance
};
replaceWindow.ViewModel.RequestReplace += (s, args) =>
{
var comp = args.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
try
{
text.Text = Regex.Replace(text.Text, args.Regex ? args.OldWord : Regex.Escape(args.OldWord), args.NewWord, comp);
}
catch (ArgumentException)
{
MessageBox.Show(Properties.Resources.IllegalArgument, Properties.Resources.Error, MessageBoxButton.OK);
}
text.Focus();
};
replaceWindow.Show();
}
bool AskBeforeClear()
{
if (Saved)
return true;
var result = MessageBox.Show(Properties.Resources.SaveResponse, Properties.Resources.ClosingText, MessageBoxButton.YesNoCancel);
switch (result)
{
case MessageBoxResult.Yes:
if (Name != null)
Save(Name);
else
{
var name = GetNameToSave();
if (name != null)
Save(name);
}
return true;
case MessageBoxResult.No:
return true;
default:
return false;
}
}
string GetNameToOpen(string defaultPath=null)
{
var dialog = new OpenFileDialog
{
Filter = Properties.Resources.TextFile + " (*.txt)|*.txt",
InitialDirectory = defaultPath
};
return dialog.ShowDialog() == true ? dialog.FileName : null;
}
string GetNameToSave(string defaultPath=null)
{
var dialog = new SaveFileDialog
{
Filter = Properties.Resources.TextFile + " (*.txt)|*.txt",
InitialDirectory = defaultPath
};
return dialog.ShowDialog() == true ? dialog.FileName : null;
}
void Open(string name)
{
text.Text = File.ReadAllText(name, Encoding.Default);
Name = name;
Saved = true;
}
void Save(string name)
{
File.WriteAllText(name, text.Text, Encoding.UTF8);
Name = name;
Saved = true;
}
void UpdateMainTextBox()
{
text.FontFamily = Properties.Settings.Default.fontFamily;
text.FontSize = Properties.Settings.Default.fontSize;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NotepadOnlineDesktop.Model
{
public enum ExtensionStatus
{
Enabled,
Disabled,
Loading
}
}
<file_sep>using NotepadOnlineDesktop.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace NotepadOnlineDesktop.ViewModel
{
public class SettingsWindow : INotifyPropertyChanged
{
public event EventHandler SettingsUpdated;
List<Model.SettingsPageItem> pages;
List<Model.SettingsPropertyItem> properties;
Model.SettingsPageItem selectedPage;
bool restartNotify;
Settings Settings
{
get
{
return Settings.Default;
}
}
public List<Model.SettingsPageItem> Pages
{
get
{
return pages;
}
set
{
pages = value;
OnPropertyChanged(nameof(Pages));
}
}
public List<Model.SettingsPropertyItem> Properties
{
get
{
return properties;
}
set
{
properties = value;
OnPropertyChanged(nameof(Properties));
}
}
public Model.SettingsPageItem SelectedPage
{
get
{
return selectedPage;
}
set
{
selectedPage = value;
OnPropertyChanged(nameof(SelectedPage));
}
}
public Model.ActionCommand PagesSelectionChanged
{
get
{
return new Model.ActionCommand(sender =>
{
Properties = SelectedPage.Properties;
});
}
}
public Model.ActionCommand Save
{
get
{
return new Model.ActionCommand(sender =>
{
Settings.Save();
SettingsUpdated?.Invoke(this, EventArgs.Empty);
MessageBox.Show(Resources.SettingsSaved + (restartNotify ? Resources.AcceptedAfterRestart : ""),
Resources.Settings,
MessageBoxButton.OK,
MessageBoxImage.Information);
});
}
}
public SettingsWindow()
{
var colorThemeComboBox = new ComboBox()
{
Width = 120,
SelectedIndex = Settings.theme == "light" ? 0 : 1,
ItemsSource = new[]
{
new TextBlock() { Text = Resources.Light },
new TextBlock() { Text = Resources.Dark }
}
};
colorThemeComboBox.SelectionChanged += (s, e) =>
{
if (((ComboBox)s).SelectedIndex == 0)
Settings.theme = "light";
else
Settings.theme = "dark";
};
var askSaveCheckBox = new CheckBox()
{
IsChecked = Settings.askonexit
};
askSaveCheckBox.Checked += (s, e) => Settings.askonexit = true;
askSaveCheckBox.Unchecked += (s, e) => Settings.askonexit = false;
var fontSize = new TextBox()
{
Width = 120,
Text = Settings.fontSize.ToString()
};
fontSize.SelectionChanged += (s, e) =>
{
var box = (TextBox)s;
if (!int.TryParse(box.Text, out int value) || value < 1 || value > 1000)
{
box.Background = (Brush)new BrushConverter().ConvertFrom("#E23D3D");
box.CaretBrush = Brushes.White;
box.Foreground = Brushes.White;
return;
}
else
{
box.Background = Brushes.White;
box.CaretBrush = Brushes.Black;
box.Foreground = Brushes.Black;
}
if (value != Settings.fontSize)
{
Settings.fontSize = value;
}
};
var source = new List<TextBlock>();
TextBlock selected = null;
foreach (var font in Fonts.SystemFontFamilies)
{
var current = new TextBlock() { Text = font.ToString(), FontFamily = font };
source.Add(current);
if (font.Source == Settings.fontFamily.Source)
selected = current;
}
var fontFamily = new ComboBox()
{
Width = 120,
SelectedItem = selected,
ItemsSource = source
};
fontFamily.SelectionChanged += (s, e) =>
{
var value = (TextBlock)((ComboBox)s).SelectedValue;
if (value.FontFamily != Settings.fontFamily)
{
Settings.fontFamily = value.FontFamily;
}
};
var enableExtensions = new CheckBox()
{
IsChecked = Settings.enableExtensions
};
enableExtensions.Checked += (s, e) =>
{
restartNotify = true;
Settings.enableExtensions = true;
};
enableExtensions.Unchecked += (s, e) =>
{
restartNotify = true;
Settings.enableExtensions = false;
};
Pages = new List<Model.SettingsPageItem>
{
new Model.SettingsPageItem()
{
Header = Resources.General,
Properties = new List<Model.SettingsPropertyItem>()
{
new Model.SettingsPropertyItem()
{
Header = Resources.ColorTheme,
Control = colorThemeComboBox
},
new Model.SettingsPropertyItem()
{
Header = Resources.AskOnExit,
Control = askSaveCheckBox
}
}
},
new Model.SettingsPageItem()
{
Header = Resources.Editor,
Properties = new List<Model.SettingsPropertyItem>()
{
new Model.SettingsPropertyItem()
{
Header = Resources.FontSize,
Control = fontSize
},
new Model.SettingsPropertyItem()
{
Header = Resources.FontFamily,
Control = fontFamily
}
}
},
new Model.SettingsPageItem()
{
Header = Resources.Extensions,
Properties = new List<Model.SettingsPropertyItem>()
{
new Model.SettingsPropertyItem()
{
Header = Resources.EnableExtensions,
Control = enableExtensions
}
}
}
};
SelectedPage = Pages[0];
Properties = SelectedPage.Properties;
}
public void Closed(object sender, EventArgs e)
{
Settings.Reload();
Model.ThemeManager.Update();
}
void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
<file_sep>using System.IO;
using System.Windows;
using static DataBase.ReturnCodeDescriptions;
namespace CloudExtension
{
public partial class PropertiesWindow : Window
{
public PropertiesWindow()
{
InitializeComponent();
Initialize();
}
void Initialize()
{
var properties = Properties.Settings.Default;
email.Text = properties.email;
password.Password = <PASSWORD>;
path.Text = properties.path;
accept.IsEnabled = false;
}
async void Login_Click(object sender, RoutedEventArgs e)
{
var log = email.Text.Trim();
var pass = <PASSWORD>.<PASSWORD>.Trim();
var result = await DataBase.Manager.LoginAsync(log, pass);
if (result != DataBase.ReturnCode.Success)
{
MessageBox.Show(Properties.Resources.LoginError + ". " + result.GetDescription(), Properties.Resources.NotSigned);
return;
}
var properties = Properties.Settings.Default;
properties.email = DataBase.Manager.Email;
properties.password = <PASSWORD>;
properties.token = DataBase.Manager.Token;
properties.Save();
MessageBox.Show(Properties.Resources.YouAreSigned, Properties.Resources.Success);
}
void Register_Click(object sender, RoutedEventArgs e)
{
new RegistrationWindow().ShowDialog();
Properties.Settings.Default.email = DataBase.Manager.Email;
Properties.Settings.Default.password = <PASSWORD>;
Initialize();
}
void Accept_Click(object sender, RoutedEventArgs e)
{
var info = new DirectoryInfo(path.Text.Trim() + "\\");
if (!info.Exists)
{
MessageBox.Show(Properties.Resources.DirectoryDoesntExist, Properties.Resources.Error);
return;
}
var properties = Properties.Settings.Default;
properties.path = info.FullName;
properties.Save();
accept.IsEnabled = false;
}
void Local_Changed(object sender, RoutedEventArgs e)
{
if (path.Text.Length > 0)
accept.IsEnabled = true;
}
}
}
<file_sep>namespace NotepadOnlineDesktopExtensions
{
public enum SpecKey
{
None,
Backspace,
Delete,
Escape
}
}
<file_sep>using System.Collections.ObjectModel;
namespace NotepadOnlineDesktop.ViewModel
{
public class ManagerWindow
{
public ObservableCollection<Model.ManagedExtension> Extensions
{
get
{
return Model.ExtensionManager.Extensions;
}
}
public Model.ManagedExtension SelectedExtension { get; set; }
public Model.ActionCommand Enable
{
get
{
return new Model.ActionCommand(sender =>
{
if (SelectedExtension?.Status == Model.ExtensionStatus.Disabled)
SelectedExtension.Enable();
});
}
}
public Model.ActionCommand Disable
{
get
{
return new Model.ActionCommand(sender =>
{
if (SelectedExtension?.Status == Model.ExtensionStatus.Enabled)
SelectedExtension.Disable();
});
}
}
}
}
<file_sep>using NotepadOnlineDesktopExtensions;
using System;
using System.IO;
using System.Windows;
using System.Text;
namespace SnippetsExtension
{
public partial class PropertiesWindow : Window
{
readonly string configPath = AppDomain.CurrentDomain.BaseDirectory + "Config\\";
IApplicationInstance app;
public PropertiesWindow(IApplicationInstance app)
{
InitializeComponent();
this.app = app;
snippets.IsChecked = Properties.Settings.Default.snippets;
brackets.IsChecked = Properties.Settings.Default.brackets;
spaces.IsChecked = Properties.Settings.Default.spaces;
tabs.IsChecked = Properties.Settings.Default.tabs;
}
void Snippets_Checked(object sender, RoutedEventArgs e)
{
var check = snippets.IsChecked == true;
Properties.Settings.Default.snippets = check;
Properties.Settings.Default.Save();
}
void Brackets_Checked(object sender, RoutedEventArgs e)
{
var check = brackets.IsChecked == true;
Properties.Settings.Default.brackets = check;
Properties.Settings.Default.Save();
}
void Spaces_Checked(object sender, RoutedEventArgs e)
{
var check = spaces.IsChecked == true;
Properties.Settings.Default.spaces = check;
Properties.Settings.Default.Save();
}
void Tabs_Checked(object sender, RoutedEventArgs e)
{
var check = tabs.IsChecked == true;
Properties.Settings.Default.tabs = check;
Properties.Settings.Default.Save();
}
void Snippets_Click(object sender, RoutedEventArgs e)
{
if (File.Exists(configPath + "Snippets.ini"))
{
app.Open(configPath + "Snippets.ini");
Close();
}
else
{
var res = MessageBox.Show(Properties.Resources.SnippetsNotFound, Properties.Resources.Error, MessageBoxButton.YesNo);
if (res == MessageBoxResult.Yes)
{
Directory.CreateDirectory(configPath);
using (var stream = new StreamWriter(configPath + "Snippets.ini", false, Encoding.UTF8))
{
stream.Write($"#\n# {Properties.Resources.SnippetsFile}\n#");
}
app.Open(configPath + "Snippets.ini");
Close();
}
}
}
void Brackets_Click(object sender, RoutedEventArgs e)
{
if (File.Exists(configPath + "Brackets.ini"))
{
app.Open(configPath + "Brackets.ini");
Close();
}
else
{
var res = MessageBox.Show(Properties.Resources.BracketsNotFound, Properties.Resources.Error, MessageBoxButton.YesNo);
if (res == MessageBoxResult.Yes)
{
Directory.CreateDirectory(configPath);
using (var stream = new StreamWriter(configPath + "Brackets.ini", false, Encoding.UTF8))
{
stream.Write($"#\n# {Properties.Resources.BracketsFile}\n#");
}
app.Open(configPath + "Brackets.ini");
Close();
}
}
}
}
}
<file_sep>namespace SnippetsExtension
{
public class Bracket
{
public char Start { get; set; }
public char End { get; set; }
}
}
<file_sep>using System.ComponentModel;
using System.Windows;
namespace CloudExtension
{
public partial class InputNameWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string text;
public string Text
{
get
{
return text;
}
set
{
text = value;
OnPropertyChanged(nameof(Text));
}
}
public bool Canceled;
public InputNameWindow()
{
InitializeComponent();
DataContext = this;
Text = Properties.Resources.NewFile;
}
public void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
void Submit_Click(object sender, RoutedEventArgs e)
{
Close();
}
void Cancel_Click(object sender, RoutedEventArgs e)
{
Canceled = true;
}
}
}
<file_sep>using System.Windows.Controls;
namespace NotepadOnlineDesktop.Model
{
public class SettingsPropertyItem
{
public string Header { get; set; }
public Control Control { get; set; }
}
}
<file_sep>using System;
namespace NotepadOnlineDesktopExtensions
{
public delegate void InputHandler(object sender, InputEventArgs e);
public class InputEventArgs : EventArgs
{
public char Key { get; }
public SpecKey SpecKey { get; }
public bool Handled { get; set; }
public InputEventArgs(char key)
{
Key = key;
SpecKey = SpecKey.None;
}
public InputEventArgs(SpecKey specKey)
{
Key = '\0';
SpecKey = specKey;
}
}
}
<file_sep>using System.Windows;
using static DataBase.ReturnCodeDescriptions;
namespace CloudExtension
{
public partial class RegistrationWindow : Window
{
public RegistrationWindow()
{
InitializeComponent();
}
void Register_Click(object sender, RoutedEventArgs e)
{
if (password.Password != <PASSWORD>)
{
MessageBox.Show(Properties.Resources.PasswordsDontMatch);
return;
}
var result = DataBase.Manager.Register(email.Text, password.Password);
if (result != DataBase.ReturnCode.Success)
{
MessageBox.Show(Properties.Resources.RegistrationFailed + ". " + result.GetDescription(), Properties.Resources.Error);
return;
}
MessageBox.Show(Properties.Resources.CodeMessage, Properties.Resources.Success);
}
void Confirm_Click(object sender, RoutedEventArgs e)
{
if (DataBase.Manager.Status != DataBase.ManagerStatus.RegistrationConfirmation)
{
MessageBox.Show(Properties.Resources.PerformRegistration);
return;
}
var result = DataBase.Manager.ConfirmRegistration(code.Text);
if (result != DataBase.ReturnCode.Success)
{
MessageBox.Show(Properties.Resources.ConfirmationFailed + ". " + result.GetDescription(), Properties.Resources.Error);
return;
}
MessageBox.Show(Properties.Resources.RegistrationCompleted, Properties.Resources.Success);
Close();
}
}
}
<file_sep>using System.Collections.Generic;
namespace NotepadOnlineDesktop.Model
{
public class SettingsPageItem
{
public string Header { get; set; }
public List<SettingsPropertyItem> Properties { get; set; }
}
}
<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace NotepadOnlineDesktopExtensions
{
public interface IExtension
{
string Name { get; }
string Version { get; }
string Author { get; }
string Description { get; }
List<MenuItem> Menu { get; }
Task OnStart(IApplicationInstance instance);
Task OnStop();
}
}
<file_sep>using System.ComponentModel;
namespace NotepadOnlineDesktop.ViewModel
{
public class ReplaceWindow : INotifyPropertyChanged
{
public delegate void ReplaceHandler(object sender, Model.ReplaceEventArgs e);
public event PropertyChangedEventHandler PropertyChanged;
public event ReplaceHandler RequestReplace;
string oldWord;
string newWord;
bool ignoreCase;
bool regex;
public string OldWord
{
get
{
return oldWord;
}
set
{
oldWord = value;
OnPropertyChanged(nameof(OldWord));
}
}
public string NewWord
{
get
{
return newWord;
}
set
{
newWord = value;
OnPropertyChanged(nameof(NewWord));
}
}
public bool IgnoreCase
{
get
{
return ignoreCase;
}
set
{
ignoreCase = value;
OnPropertyChanged(nameof(IgnoreCase));
}
}
public bool Regex
{
get
{
return regex;
}
set
{
regex = value;
OnPropertyChanged(nameof(Regex));
}
}
public Model.ActionCommand Replace
{
get
{
return new Model.ActionCommand(
sender =>
{
if (!string.IsNullOrEmpty(OldWord))
OnRequestReplace(new Model.ReplaceEventArgs(OldWord, NewWord ?? "", IgnoreCase, Regex));
});
}
}
public ReplaceWindow()
{
IgnoreCase = true;
}
private void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private void OnRequestReplace(Model.ReplaceEventArgs args)
{
RequestReplace?.Invoke(this, args);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace SnippetsExtension
{
static class Importer
{
static readonly string _snippet = "snippet";
public static Bracket[] LoadBrackets(string path)
{
if (!File.Exists(path))
return new Bracket[0];
var brackets = new List<Bracket>();
using (var stream = new StreamReader(path, Encoding.Default))
{
while (!stream.EndOfStream)
{
var line = stream.ReadLine();
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#"))
continue;
if (line.Length != 2)
throw new Exception(Properties.Resources.ExpectedTwo); // Ожидалось 2 символа
brackets.Add(new Bracket { Start = line[0], End = line[1] });
}
}
return brackets.ToArray();
}
public static Snippet[] LoadSnippets(string path)
{
if (!File.Exists(path))
return new Snippet[0];
var snippets = new List<Snippet>();
var state = ImporterState.ReadingTemplate;
var template = "";
var headers = "";
var value = "";
using (var stream = new StreamReader(path, Encoding.Default))
{
while (!stream.EndOfStream)
{
var line = stream.ReadLine();
if (state == ImporterState.ReadingTemplate)
if (line.StartsWith(_snippet))
{
line = line.Remove(0, _snippet.Length).Trim();
if (line[0] != '\'')
throw new Exception(Properties.Resources.ExpectedPattern); // После snippet нету кавычки
line = line.Substring(1);
int pos = -1;
for (int i = 0; i < line.Length - 1; i++)
if (line[i] != '\\' && line[i + 1] == '\'')
{
pos = i + 1;
break;
}
if (pos == -1)
throw new Exception(Properties.Resources.ExpectedEnd); // Нету символа окончания шаблона
template = line.Substring(0, pos);
headers = line.Substring(pos + 1).Trim();
state = ImporterState.ReadingValue;
continue;
}
else if (line.StartsWith("#") || string.IsNullOrEmpty(line))
continue;
else
throw new Exception(Properties.Resources.ExpectedSnippet); // Ожидалось слово snippet
if (state == ImporterState.ReadingValue)
{
if (line == "")
{
snippets.Add(DecodeSnippet(template, headers, value));
state = ImporterState.ReadingTemplate;
template = "";
headers = "";
value = "";
}
else if (line == ".")
value += "\n";
else if (line == "\\.")
value += ".";
else
value += (value.Length > 0 ? "\n" : "") + line;
continue;
}
}
snippets.Add(DecodeSnippet(template, headers, value));
}
for (int i = 0; i < snippets.Count; i++)
for (int j = 0; j < snippets.Count; j++)
if (snippets[i].Template.Contains(snippets[j].Template))
if (i > j)
{
var m = snippets[i];
snippets[i] = snippets[j];
snippets[j] = m;
}
return snippets.ToArray();
}
static Snippet DecodeSnippet(string template, string headers, string value)
{
headers = headers.ToUpper();
if (headers.Contains("B") && headers.Contains("R"))
template = @"(?<=^\s*)" + template;
//template = "^" + template;
if (headers.Contains("W"))
{
if (!headers.Contains("R"))
template = Regex.Escape(template);
template = @"(?<![a-zA-Z])" + template;
headers += "R";
}
var snippet = new Snippet
{
Template = template,
BeginOnly = headers.Contains("B"),
UsesRegex = headers.Contains("R"),
SelectTrigger = headers.Contains("S")
};
if (!headers.Contains("A") && !headers.Contains("S"))
snippet.Template += "\t";
// Python
var python = false;
var start = -1;
var end = -1;
for (int i = 0; i < value.Length; i++)
{
if (value[i] == '`' && i > 0 && value[i - 1] == '\\')
{
value = value.Remove(i - 1, 1);
continue;
}
if (value[i] == '`' && !python)
{
if (snippet.ContainsPythonCode)
throw new Exception(Properties.Resources.TooMuchPython); // Более одного блока Python
snippet.ContainsPythonCode = true;
snippet.PythonPosition = start = i;
python = true;
continue;
}
if (value[i] == '`' && python)
{
end = i;
python = false;
continue;
}
}
if (snippet.ContainsPythonCode)
{
snippet.PythonCode = value.Substring(start + 1, end - start - 1);
value = value.Substring(0, start) + value.Substring(end + 1);
}
if (Snippet.Index(value, 0) == -1)
value += "$0";
snippet.Value = value;
return snippet;
}
}
}
<file_sep>using System.Windows;
using System.Windows.Threading;
namespace NotepadOnlineDesktop
{
public partial class App : Application
{
void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
foreach (var extension in Model.ExtensionManager.LoadedExtensions)
if (e.Exception.Source == extension.GetType().Namespace)
{
MessageBox.Show($"Extension {extension.Name} throwed exception: {e.Exception.Message}\n\nCorrect work of this extension is not guarenteed", "Extension error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
MessageBox.Show($"Unhandled application exception occured: {e.Exception.Message}\nSource: {e.Exception.Source}\n\nStack trace: {e.Exception.StackTrace}\n\nIt's recommended to contact with the developer: <EMAIL>", "Unhandled exception", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
}
<file_sep>using NotepadOnlineDesktopExtensions;
using System;
using System.ComponentModel;
using System.Windows.Controls;
namespace NotepadOnlineDesktop.Model
{
public class ManagedExtension : INotifyPropertyChanged
{
IExtension extension;
IApplicationInstance instance;
MenuItem menu;
ExtensionStatus status = ExtensionStatus.Disabled;
public ManagedExtension(IExtension extension, IApplicationInstance instance, MenuItem menu)
{
this.extension = extension;
this.instance = instance;
this.menu = menu;
}
public ExtensionStatus Status
{
get
{
return status;
}
set
{
status = value;
OnPropertyChanged("Status");
}
}
public string Name => extension.Name;
public string Version => extension.Version;
public string Author => extension.Author;
public string Description => extension.Description;
public async void Enable()
{
if (Status == ExtensionStatus.Disabled)
{
Status = ExtensionStatus.Loading;
await extension.OnStart(instance);
Status = ExtensionStatus.Enabled;
menu.Visibility = System.Windows.Visibility.Visible;
var prop = Properties.Settings.Default;
prop.extStatus[prop.extNames.IndexOf(Name)] = "true";
prop.Save();
}
else
throw new Exception();
}
public async void Disable()
{
if (Status == ExtensionStatus.Enabled)
{
Status = ExtensionStatus.Loading;
await extension.OnStop();
Status = ExtensionStatus.Disabled;
menu.Visibility = System.Windows.Visibility.Collapsed;
var prop = Properties.Settings.Default;
prop.extStatus[prop.extNames.IndexOf(Name)] = "false";
prop.Save();
}
else
throw new Exception();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
<file_sep>using System.ComponentModel;
namespace NotepadOnlineDesktop.ViewModel
{
public class FindWindow : INotifyPropertyChanged
{
public delegate void FindHandler(object sender, Model.FindEventArgs e);
public event PropertyChangedEventHandler PropertyChanged;
public event FindHandler RequestFind;
string word;
bool ignoreCase;
bool regex;
bool upDirection;
bool downDirection;
public string Word
{
get
{
return word;
}
set
{
word = value;
OnPropertyChanged(nameof(Word));
}
}
public bool IgnoreCase
{
get
{
return ignoreCase;
}
set
{
ignoreCase = value;
OnPropertyChanged(nameof(IgnoreCase));
}
}
public bool Regex
{
get
{
return regex;
}
set
{
regex = value;
OnPropertyChanged(nameof(Regex));
}
}
public bool UpDirection
{
get
{
return upDirection;
}
set
{
upDirection = value;
OnPropertyChanged(nameof(UpDirection));
}
}
public bool DownDirection
{
get
{
return downDirection;
}
set
{
downDirection = value;
OnPropertyChanged(nameof(DownDirection));
}
}
public Model.ActionCommand Find
{
get
{
return new Model.ActionCommand(sender =>
OnRequestFind(new Model.FindEventArgs(Word ?? "", IgnoreCase, Regex, UpDirection, DownDirection))
);
}
}
public FindWindow()
{
IgnoreCase = true;
DownDirection = true;
}
private void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private void OnRequestFind(Model.FindEventArgs args)
{
RequestFind?.Invoke(this, args);
}
}
}
<file_sep>using System;
namespace NotepadOnlineDesktop.Model
{
public class ReplaceEventArgs : EventArgs
{
public string OldWord { get; private set; }
public string NewWord { get; private set; }
public bool IgnoreCase { get; private set; }
public bool Regex { get; private set; }
public ReplaceEventArgs(string oldWord, string newWord, bool ignoreCase, bool regex)
{
OldWord = oldWord ?? throw new ArgumentNullException(nameof(oldWord));
NewWord = newWord ?? throw new ArgumentNullException(nameof(newWord));
IgnoreCase = ignoreCase;
Regex = regex;
}
}
}
<file_sep>using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using NotepadOnlineDesktopExtensions;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace SnippetsExtension
{
[Export(typeof(IExtension))]
class Main : IExtension
{
public string Name => Properties.Resources.Name;
public string Version => "1.0";
public string Author => "DMSoft";
public string Description => Properties.Resources.Info;
readonly string configPath = AppDomain.CurrentDomain.BaseDirectory;
Snippet[] snippets;
Bracket[] brackets;
ScriptEngine engine;
ScriptScope scope;
bool middle;
int middleIndex;
string middleWord;
string middleValue;
int currentPos;
int currentLength;
public List<MenuItem> Menu
{
get
{
return new List<MenuItem>()
{
properties
};
}
}
MenuItem properties;
IApplicationInstance app;
public Main()
{
properties = new MenuItem() { Header = Properties.Resources.Properties };
properties.Click += Properties_Click;
try
{
snippets = Importer.LoadSnippets(configPath + "\\Config\\Snippets.ini");
}
catch (Exception e)
{
MessageBox.Show(Properties.Resources.SnippetsLoadError + ". " + e.Message, Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
snippets = new Snippet[0];
}
try
{
brackets = Importer.LoadBrackets(configPath + "\\Config\\Brackets.ini");
}
catch (Exception e)
{
MessageBox.Show(Properties.Resources.BracketsLoadError + ". " + e.Message, Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
brackets = new Bracket[0];
}
engine = Python.CreateEngine();
scope = engine.CreateScope();
}
public async Task OnStart(IApplicationInstance instance)
{
app = instance;
app.OnInput += App_OnInput;
await Task.CompletedTask;
}
public async Task OnStop()
{
app.OnInput -= App_OnInput;
await Task.CompletedTask;
}
void App_OnInput(object sender, InputEventArgs e)
{
if (e.SpecKey == SpecKey.Escape)
{
middle = false;
return;
}
// Selection snippets
if (app.SelectionLength > 0)
{
middle = false;
if (e.Key != '\t')
return;
var selected = app.Text.Substring(app.SelectionStart, app.SelectionLength);
var caret = app.SelectionStart;
var length = app.SelectionLength;
foreach (var snippet in snippets)
{
if (!snippet.SelectTrigger)
continue;
if (snippet.UsesRegex)
{
var match = Regex.Match(selected, snippet.Template);
if (!(match.Success && match.Length == selected.Length))
continue;
}
else
{
if (snippet.Template != selected)
continue;
}
var value = snippet.Value;
if (snippet.ContainsPythonCode)
{
scope.SetVariable("word", selected);
engine.Execute(snippet.PythonCode, scope);
value = value.Insert(snippet.PythonPosition, scope.GetVariable("value"));
}
var index = Snippet.Index(value, 0);
value = Snippet.ClearValue(value);
app.Text = app.Text.Remove(caret, length).Insert(caret, value);
app.SelectionStart = caret + index;
app.SelectionLength = 0;
e.Handled = true;
return;
}
return;
}
// Spaces
if (Properties.Settings.Default.spaces)
{
if (e.Key == '\r' && !middle && app.SelectionStart != 0)
{
var remember_pos = app.SelectionStart;
var txt = app.Text.Substring(0, remember_pos);
var ind = txt.LastIndexOf('\n');
var t = txt.Substring(ind + 1);
int c = 0;
for (int i = 0; i < t.Length; i++)
if (t[i] == ' ')
c++;
else
break;
if (c == 0)
return;
var s = new String(' ', c);
app.Text = app.Text.Insert(app.SelectionStart, "\n" + s);
app.SelectionStart = remember_pos + c + 1;
e.Handled = true;
return;
}
}
var text = app.Text;
var pos = app.SelectionStart;
// Middle input
if (middle && (app.SelectionStart < currentPos + Snippet.Index(middleValue, middleIndex) || app.SelectionStart > currentPos + Snippet.Index(middleValue, middleIndex) + middleWord.Length))
middle = false;
if (middle)
{
var delta = 0;
var newCursorPos = pos - currentPos - Snippet.Index(middleValue, middleIndex);
var newMiddle = "";
var recog = "";
if (e.SpecKey == SpecKey.None)
{
newMiddle = InsertText(middleWord, e.Key, ref newCursorPos);
recog = RecognizeSimpleSnippets(newMiddle, newCursorPos, out delta);
}
if (e.Key != '\t' || newMiddle != recog)
{
string value;
if (e.SpecKey == SpecKey.Backspace)
{
if (newCursorPos > 0)
{
newMiddle = middleWord.Remove(newCursorPos - 1, 1);
value = Snippet.MiddleUpdate(middleValue, middleWord, newMiddle, middleIndex);
middleWord = newMiddle;
newCursorPos--;
}
else
{
e.Handled = true;
return;
}
}
else if (e.SpecKey == SpecKey.Delete)
{
if (newCursorPos < middleWord.Length)
{
newMiddle = middleWord.Remove(newCursorPos, 1);
value = Snippet.MiddleUpdate(middleValue, middleWord, newMiddle, middleIndex);
middleWord = newMiddle;
}
else
{
e.Handled = true;
return;
}
}
else
{
var oldword = middleWord;
middleWord = recog;
value = Snippet.MiddleUpdate(middleValue, oldword, middleWord, middleIndex);
}
middleValue = value;
value = Snippet.ClearValue(value);
text = text.Remove(currentPos, currentLength);
text = text.Insert(currentPos, value);
currentLength = value.Length;
app.Text = text;
app.SelectionStart = currentPos + Snippet.Index(middleValue, middleIndex) + newCursorPos + delta;
e.Handled = true;
return;
}
else
{
middleValue = Snippet.ClearValue(middleValue, middleIndex);
if (Snippet.Index(middleValue, ++middleIndex) != -1)
{
middleWord = "";
app.SelectionStart = currentPos + Snippet.Index(middleValue, middleIndex);
}
else
{
if (Snippet.Index(middleValue, 0) != -1)
{
app.SelectionStart = currentPos + Snippet.Index(middleValue, 0);
}
middle = false;
}
e.Handled = true;
return;
}
}
// Snippets
if (Properties.Settings.Default.snippets && e.SpecKey == SpecKey.None)
{
var _text = text.Insert(pos, e.Key.ToString());
var _pos = pos + 1;
var tail = _text.Substring(_pos);
var head = _text.Substring(0, _pos);
foreach (var snippet in snippets)
{
if (snippet.SelectTrigger)
continue;
if (snippet.UsesRegex)
{
var match = Regex.Match(head, snippet.Template + @"\Z", RegexOptions.Multiline | RegexOptions.RightToLeft);
if (!match.Success)
continue;
var value = snippet.Value;
if (snippet.ContainsPythonCode)
{
scope.SetVariable("word", match.Value);
engine.Execute(snippet.PythonCode, scope);
value = value.Insert(snippet.PythonPosition, scope.GetVariable("value"));
}
middleValue = value;
value = Snippet.ClearValue(value);
var customMiddlePositions = Snippet.Index(middleValue, 1) != -1;
if (customMiddlePositions)
{
middle = true;
middleIndex = 1;
middleWord = "";
currentPos = _pos - match.Value.Length;
currentLength = value.Length;
}
_text = head;
_text = _text.Remove(_pos - match.Value.Length, match.Value.Length);
_text = _text.Insert(_pos - match.Value.Length, value);
app.Text = _text + tail;
app.SelectionStart = _pos - match.Value.Length;
if (customMiddlePositions)
{
app.SelectionStart += Snippet.Index(middleValue, 1);
}
else
{
app.SelectionStart += Snippet.Index(middleValue, 0);
}
e.Handled = true;
return;
}
else if (_pos >= snippet.Template.Length && _text.Substring(_pos - snippet.Template.Length, snippet.Template.Length) == snippet.Template)
{
var value = snippet.Value;
if (pos >= snippet.Template.Length)
{
var subtext = text.Substring(0, pos - snippet.Template.Length + 1);
var textForBeginCheck = subtext.TrimEnd(' ');
if (snippet.BeginOnly && !(textForBeginCheck.Length == 0 || textForBeginCheck.Last() == '\n'))
continue;
value = value.Replace("\n", "\n" + new string(' ', subtext.Length - textForBeginCheck.Length));
}
if (snippet.ContainsPythonCode)
{
engine.Execute(snippet.PythonCode, scope);
value = value.Insert(snippet.PythonPosition, scope.GetVariable("value"));
}
middleValue = value;
value = Snippet.ClearValue(value);
var customMiddlePositions = Snippet.Index(middleValue, 1) != -1;
if (customMiddlePositions)
{
middle = true;
middleIndex = 1;
middleWord = "";
currentPos = _pos - snippet.Template.Length;
currentLength = value.Length;
}
_text = _text.Remove(_pos - snippet.Template.Length, snippet.Template.Length);
_text = _text.Insert(_pos - snippet.Template.Length, value);
app.Text = _text;
app.SelectionStart = _pos - snippet.Template.Length;
if (customMiddlePositions)
{
app.SelectionStart += Snippet.Index(middleValue, 1);
}
else
{
app.SelectionStart += Snippet.Index(middleValue, 0);
}
e.Handled = true;
return;
}
}
}
if (Properties.Settings.Default.brackets && e.SpecKey == SpecKey.None)
{
for (int i = 0; i < brackets.Length; i++)
if (e.Key == brackets[i].Start || e.Key == brackets[i].End)
{
var inserted = InsertBracket(text, e.Key, ref pos, brackets[i].Start, brackets[i].End);
if (inserted != null)
{
app.Text = inserted;
app.SelectionStart = pos;
e.Handled = true;
}
break;
}
}
if (Properties.Settings.Default.tabs && e.SpecKey == SpecKey.None)
{
var inserted = InsertTab(text, e.Key, ref pos);
if (inserted != null)
{
app.Text = inserted;
app.SelectionStart = pos;
e.Handled = true;
}
}
}
string InsertText(string text, char key, ref int pos)
{
if (Properties.Settings.Default.brackets)
{
for (int i = 0; i < brackets.Length; i++)
if (key == brackets[i].Start || key == brackets[i].End)
{
var inserted = InsertBracket(text, key, ref pos, brackets[i].Start, brackets[i].End);
if (inserted != null)
return inserted;
else
break;
}
}
return text.Insert(pos++, key.ToString());
}
string InsertBracket(string text, char key, ref int pos, char start, char end)
{
// Skip braces
if (key == end && pos < text.Length && text[pos] == end)
{
pos++;
return text;
}
// Double braces
if (key == start)
{
text = text.Insert(pos, start.ToString() + end);
pos++;
return text;
}
return null;
}
string InsertTab(string text, char key, ref int pos)
{
if (key == '\t')
{
text = text.Insert(pos, " ");
pos += 4;
return text;
}
return null;
}
string RecognizeSimpleSnippets(string word, int pos, out int delta)
{
var part1 = word.Substring(0, pos);
var part2 = word.Length > pos ? word.Substring(pos) : "";
foreach (var snippet in snippets)
{
if (snippet.SelectTrigger)
continue;
if (Snippet.Index(snippet.Value, 1) == -1 && !snippet.BeginOnly)
if (snippet.UsesRegex)
{
var matches = Regex.Matches(part1, snippet.Template);
if (matches.Count == 0)
continue;
var match = matches[matches.Count - 1];
if (match.Index + match.Length < part1.Count())
continue;
var value = snippet.Value;
if (snippet.ContainsPythonCode)
{
scope.SetVariable("word", match.Value);
engine.Execute(snippet.PythonCode, scope);
value = value.Insert(snippet.PythonPosition, scope.GetVariable("value"));
}
var middleValue = value;
value = Snippet.ClearValue(value);
delta = Snippet.Index(middleValue, 0) - match.Value.Length;
return part1.Substring(0, part1.Length - match.Value.Length) + value + part2;
}
else if (part1.Length >= snippet.Template.Length && part1.Substring(part1.Length - snippet.Template.Length, snippet.Template.Length) == snippet.Template)
{
var value = snippet.Value;
if (snippet.ContainsPythonCode)
{
engine.Execute(snippet.PythonCode, scope);
value = value.Insert(snippet.PythonPosition, scope.GetVariable("value"));
}
var middleValue = value;
value = Snippet.ClearValue(value);
delta = Snippet.Index(middleValue, 0) - snippet.Template.Length;
return part1.Substring(0, part1.Length - snippet.Template.Length) + value + part2;
}
}
delta = 0;
return word;
}
void Properties_Click(object sender, RoutedEventArgs e)
{
new PropertiesWindow(app).ShowDialog();
}
}
}
<file_sep>using NotepadOnlineDesktopExtensions;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Windows.Controls;
namespace NotepadOnlineDesktop.Model
{
public class ExtensionManager
{
public static ObservableCollection<ManagedExtension> Extensions { get; private set; }
public static MenuItem ParentMenu { get; private set; }
[ImportMany]
public static List<IExtension> LoadedExtensions { get; private set; }
public static void Load(string path)
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog(path));
var container = new CompositionContainer(catalog);
LoadedExtensions = new List<IExtension>(container.GetExportedValues<IExtension>());
}
public static void Initialize(IApplicationInstance instance, MenuItem parent)
{
ParentMenu = parent;
Extensions = new ObservableCollection<ManagedExtension>();
foreach (var extension in LoadedExtensions)
{
var menu = new MenuItem
{
Header = extension.Name,
Visibility = System.Windows.Visibility.Collapsed,
Template = (ControlTemplate)App.Current.Resources["SubRootMenuItemTemplate"]
};
var curExt = new ManagedExtension(extension, instance, menu);
foreach (var item in extension.Menu)
menu.Items.Add(item);
parent.Items.Add(menu);
Extensions.Add(curExt);
var prop = Properties.Settings.Default;
if (prop.extNames == null)
prop.extNames = new System.Collections.Specialized.StringCollection();
if (prop.extStatus == null)
prop.extStatus = new System.Collections.Specialized.StringCollection();
if (prop.extNames.Contains(curExt.Name))
{
if (prop.extStatus[prop.extNames.IndexOf(curExt.Name)] == "true")
curExt.Enable();
}
else
{
prop.extNames.Add(curExt.Name);
prop.extStatus.Add("false");
prop.Save();
}
}
}
}
}
<file_sep>namespace NotepadOnlineDesktopExtensions
{
public interface IApplicationInstance
{
event InputHandler OnInput;
string Text { get; set; }
string Name { get; }
int SelectionStart { get; set; }
int SelectionLength { get; set; }
void Open(string name);
void OpenFolder(string path);
}
}
| ff4aa9691425f12b6401e77a31b7e2f66b194b7b | [
"C#"
]
| 32 | C# | damoldavskiy/Notepad.Online-Desktop | 469211a44d298224e520c0a90d36b78a5a1cf00d | b477b24dac6c49402695bcafcbb051d3ea5ac826 |
refs/heads/master | <repo_name>mauricioLopezRamirez/node-crypto-the-x.cn<file_sep>/crypto.js
const crypto = require("crypto");
const iv = Buffer.from('00000000000000000000000000000000', 'hex');
const key = Buffer.from('11328F38F29BA5B60C2AA633DB78281C', 'hex');
encrypt = (str) => {
const string = Buffer.from(str)
const padding = Buffer.alloc(setPadding(str))
const s_p = [string, padding];
const s_p_concat = Buffer.concat(s_p);
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv)
cipher.setAutoPadding(false)
let encrypted = cipher.update(s_p_concat, 'utf8', 'base64')
encrypted += cipher.final('base64')
return encrypted
}
setPadding = (str) => {
if (!str) { return 16 }
const length = str.length
if (length % 16 === 0) {
return 16
}
const multiplicador = Math.ceil(length / 16)
console.log(multiplicador)
return (16 * multiplicador) - length
}
const enc = encrypt('Mauricio');
console.log(enc); | bf4764ad4c79ac1e344a6e169e74f6dc5eef39bb | [
"JavaScript"
]
| 1 | JavaScript | mauricioLopezRamirez/node-crypto-the-x.cn | e3d753363d7161443580e08c98b66a2dd17239e1 | 0486bb6ebc042075868a5670ee010fc875b0d57b |
refs/heads/master | <file_sep># gdashboard
qml tests dinamic with render
<file_sep>var component;
var sprite;
function createLayoutObjects(currentLayout, parentObj) {
component = Qt.createComponent("../layouts/"+ currentLayout+".qml");
if (component.status === Component.Ready)
finishCreation(parentObj);
else
component.statusChanged.connect(finishCreation);
}
function finishCreation(parentObj) {
if (component.status === Component.Ready) {
sprite = component.createObject(parentObj);
if (sprite === null) {
// Error Handling
console.log("Error creating object");
}
} else if (component.status === Component.Error) {
// Error Handling
console.log("Error loading component:", component.errorString());
}
}
| 0909da2e6e5f1e00f88e616e12d19814e067f07d | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | jotalinux2/gdashboard | b2e87fa37735591f70e8f6dd211d9c621c4f3f71 | 8974aea860df4af858b8818e002e7001299a793d |
refs/heads/master | <file_sep>package com.uploadfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class UploadServlet
*/
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
//DB Connection
String url = "jdbc:sqlserver://***.database.windows.net:1433;database=Quiz3DB;user=****;password=*****";
Connection connection = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url);
System.out.println("******* ");
String feedUrl = "C:\\Users\\PM\\Desktop\\images\\test.csv";
// URL url = new URL(feedUrl);
// InputStreamReader isr = new InputStreamReader();
FileReader fr = new FileReader(feedUrl);
BufferedReader br = new BufferedReader(fr);
String line = "";
String splitBy = ",";
String selectSql = "INSERT INTO EducationTest(UNITID,OPEID,OPEID6,INSTNM,CITY,STATE,INSTURL,SAT_AVG,GRADDEBT) values (?, ?, ?,?,?,?,?,?,?)";
while ((line = br.readLine()) != null) {
PreparedStatement statement = connection.prepareStatement(selectSql);
String[] data = line.split(splitBy);
// System.out.println("CARS [year= " + cars[0] + " , make="
// + cars[1] );
statement.setInt(1, Integer.parseInt((data[0])));
statement.setInt(2, Integer.parseInt((data[1])));
statement.setInt(3, Integer.parseInt((data[2])));
statement.setString(4, (data[3]));
statement.setString(5, (data[4]));
statement.setString(6, (data[5]));
statement.setString(7, (data[6]));
statement.setFloat(8, Float.parseFloat((data[7])));
statement.setFloat(9, Float.parseFloat((data[8])));
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
System.out.print("File uploaded and saved into database");
}
}
connection.close();
response.sendRedirect("Upload.jsp");
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect("Upload.jsp");
}
}
}
| a705dbddae855e9567b0f4f7cd4bdb72a61df2e2 | [
"Java"
]
| 1 | Java | pm777/RedisAndRDSDifference | 530fd099551038a3346fad026a66e9da829da6a6 | 62edcc386f2ad941e2eaa10775740f867959be86 |
refs/heads/master | <file_sep>package der.proxy.CGlibproxy;
/**
* Created by dev2 on 2018/7/5.
*/
public class StudentDao {
public void save() {
System.out.println("--------已保存数据-------");
}
}
<file_sep>package der.threadpool;
import java.util.concurrent.*;
/**
* Created by dev2 on 2018/5/29.
*/
public class SingleThreadPool {
static int time = 500;
public void getPool(){
Executor executor = Executors.newSingleThreadExecutor();
FutureTask futureTask = new FutureTask(()-> print());
executor.execute(futureTask);
try {
futureTask.get(time, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
public int print() throws InterruptedException {
Thread.sleep(300);
System.out.println("a task");
return 1;
}
}
<file_sep>package der.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Hashtable;
/**
* Created by dev2 on 2018/5/21.
*/
public class ReflectDerRead {
public static void main(String[] args) throws Exception {
Class stuClass = Class.forName("com.der.reflect.Student");
Constructor constructor = stuClass.getConstructor(String.class,String.class);
Student student = (Student) constructor.newInstance("der","12345678");
Field[] fields = stuClass.getDeclaredFields();
for (Field field:fields){
System.out.println(field.getName()+" : ");
field.setAccessible(true);
System.out.println(field.get(student));
}
}
}
class Student{
public String username;
private String password;
public Student (String username,String password){
this.username = username;
this.password = <PASSWORD>;
}
public void changePassword(){
System.out.println("new password : "+this.password);
Hashtable hashtable = new Hashtable();
hashtable.keySet();
}
}<file_sep>package der.wheels;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by dev2 on 2018/7/4.
*/
public class MyHashTable {
public static void main(String[] args) {
Hashtable studentInfo = new Hashtable<String,String>();
studentInfo.put("name","aiyuyao");
HashMap newStudentInfo = new HashMap();
newStudentInfo.put("name","ayy");
ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<String,String>();
concurrentHashMap.put("name","der");
concurrentHashMap.containsKey("name");
concurrentHashMap.remove("name");
concurrentHashMap.size();
}
}
<file_sep>package der.threadpool;
/**
* Created by dev2 on 2018/5/29.
*/
public class Request {
public static void main(String[] args) {
MyThread thread = new MyThread();
for (int i=0;i<2000;i++){
new Thread(thread).start();
}
}
}
class MyThread implements Runnable{
@Override
public void run() {
new SingleThreadPool().getPool();
}
}
| 67080a3d6e5042528fbb83a59b2a6c3c9fa534ac | [
"Java"
]
| 5 | Java | aiyuyao/small_instance | f72355108b40531330de42a50488fcee165ca3b1 | 03c20d46bd3b3b8f61bc02e9d3ade8c21427394f |
refs/heads/master | <file_sep>class Chef
class Dist
# This class is not fully implemented, depending on it is not recommended!
# When referencing a product directly, like Chef (Now Chef Infra)
PRODUCT = "Chef Infra Client".freeze
# The name of the server product
SERVER_PRODUCT = "Chef Infra Server".freeze
# The client's alias (chef-client)
CLIENT = "chef-client".freeze
# name of the automate product
AUTOMATE = "Chef Automate".freeze
# The chef executable, as in `chef gem install` or `chef generate cookbook`
EXEC = "chef".freeze
# product website address
WEBSITE = "https://chef.io".freeze
# Chef-Zero's product name
ZERO = "Chef Infra Zero".freeze
# Chef-Solo's product name
SOLO = "Chef Infra Solo".freeze
# The chef-zero executable (local mode)
ZEROEXEC = "chef-zero".freeze
# The chef-solo executable (legacy local mode)
SOLOEXEC = "chef-solo".freeze
end
end
| dbb66e0ab8c676068f990f6bd846aafbf79ea020 | [
"Ruby"
]
| 1 | Ruby | ncerny/chef | cc6c31616126c38d93dafd1f0475ac3ae5815a65 | c4f5cc7e9a488bb34978eec7869babce9316708b |
refs/heads/master | <file_sep>#!/bin/sh
nix-shell --argstr compiler ghc802
<file_sep>#!/bin/sh
nix-build
mkdir -p dist
./result/bin/c172-preflight
<file_sep># Cessna 172 pre-flight checks
| 82ac6f7693cf9d8e723003f1d4141399228497c8 | [
"Markdown",
"Shell"
]
| 3 | Shell | tonymorris/c172-preflight | d7a25be73d9a737cfa2c2d1db9b132021f4a239f | b16782533bd8f3865ea425f1344fd4ffebf06b8c |
refs/heads/master | <repo_name>accenture-schuylervo/RomanNumeralCalcInC<file_sep>/src/romancalc.c
#include "romancalc.h"
char *ltrim(char *s)
{
while(isspace(*s)) s++;
return s;
}
char *rtrim(char *s)
{
char* back = s + strlen(s);
while(isspace(*--back));
*(back+1) = '\0';
return s;
}
char *trim(char *s)
{
return rtrim(ltrim(s));
}
typedef struct {
char first_term[BUFFER_SIZE];
char second_term[BUFFER_SIZE];
} uppercaseTerms;
#define additionOperation() strcmp(operator, "+" ) == 0
enum CalculatorStatus RomanCalculator(char *first, char* operator, char* second, char* result) {
int returnCode;
uppercaseTerms terms;
if( ( returnCode = validateInputParametersPresent(first, operator, second, result) ) != Success ) {
return returnCode;
}
if( ( returnCode = validateInputTermsProperSize(first, second) ) != Success ) {
return returnCode;
}
memset(terms.first_term, 0x00, sizeof(terms.first_term));
strcat(terms.first_term, first);
uppercase(terms.first_term);
memset(terms.second_term, 0x00, sizeof(terms.second_term));
strcat(terms.second_term, second);
uppercase(terms.second_term);
if( ( returnCode = validateInputParametersValid(terms.first_term, operator, terms.second_term) ) != Success ) {
return returnCode;
}
int first_in_arabic;
int second_in_arabic;
first_in_arabic = convertRomanToArabic(terms.first_term);
if( first_in_arabic > MAX_ARABIC_VALUE ) {
return FirstTermOverflow;
}
second_in_arabic = convertRomanToArabic(terms.second_term);
if( second_in_arabic > MAX_ARABIC_VALUE ) {
return SecondTermOverflow;
}
char romanNumeral[BUFFER_SIZE];
memset(romanNumeral, 0x00, sizeof(romanNumeral));
if(additionOperation()) {
int sum = first_in_arabic + second_in_arabic;
if( sum > MAX_ARABIC_VALUE ) {
return ResultOverflow;
}
strcpy(result, convertArabicToRoman(sum, romanNumeral));
}
else {
int difference = first_in_arabic - second_in_arabic;
if( difference < 1 ) {
return ResultUnderflow;
}
strcpy(result, convertArabicToRoman(difference, romanNumeral));
}
return Success;
}<file_sep>/README.md
# RomanNumeralCalcInC
A simple TDD roman numeral calculator in C
## Packages and Environment
* Installed Pathogen, SuperTab, Syntastic, NERDTree, and AutoPairs vim plugins
* set up .gitignore
* used set tabstop=4 in vim
* installed check using apt-get
```
sudo apt-get install check
```
## Running the tests
clone the repository
change to the project directory
```
make tests
```<file_sep>/src/romancalc.h
#ifndef ROMAN_CALC_H_DEFINED
#define ROMAN_CALC_H_DEFINED
#include "validate.h"
#include "convert.h"
enum CalculatorStatus RomanCalculator(char *first, char* operator, char* second, char* result);
#endif
<file_sep>/src/convert.h
#ifndef CONVERT_H_DEFINED
#define CONVERT_H_DEFINED
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
int convertRomanToArabic(char* romanNumeral);
char* convertArabicToRoman(int arabic_number, char* romanNumeral);
typedef struct arabicRomanPair {
int arabic;
char* roman;
int romanLength;
} arabicRomanPair;
extern arabicRomanPair roman_arabic_lookup[];
extern arabicRomanPair arabic_roman_lookup[];
extern arabicRomanPair* lastRomanArabicLookupEntry;
extern arabicRomanPair* lastArabicRomanLookupEntry;
#define ROMAN_I "I" /* 1 */
#define ROMAN_II "II" /* 2 */
#define ROMAN_III "III" /* 3 */
#define ROMAN_IV "IV" /* 4 */
#define ROMAN_V "V" /* 5 */
#define ROMAN_IX "IX" /* 9 */
#define ROMAN_X "X" /* 10 */
#define ROMAN_XL "XL" /* 40 */
#define ROMAN_L "L" /* 50 */
#define ROMAN_XC "XC" /* 90 */
#define ROMAN_C "C" /* 100 */
#define ROMAN_CD "CD" /* 400 */
#define ROMAN_D "D" /* 500 */
#define ROMAN_CM "CM" /* 900 */
#define ROMAN_M "M" /* 1000 */
#define MAX_ARABIC_VALUE 3999
#endif<file_sep>/src/convert.c
#include "convert.h"
arabicRomanPair roman_arabic_lookup[] = {
{ 3, ROMAN_III, sizeof(ROMAN_III) - 1},
{ 2, ROMAN_II , sizeof(ROMAN_II) - 1 },
{ 4, ROMAN_IV , sizeof(ROMAN_IV) - 1 },
{ 9, ROMAN_IX , sizeof(ROMAN_IX) - 1 },
{ 40, ROMAN_XL , sizeof(ROMAN_XL) - 1 },
{ 90, ROMAN_XC , sizeof(ROMAN_XC) - 1 },
{ 400, ROMAN_CD , sizeof(ROMAN_CD) - 1 },
{ 900, ROMAN_CM , sizeof(ROMAN_CM) - 1 },
{ 1, ROMAN_I , sizeof(ROMAN_I) - 1 },
{ 5, ROMAN_V , sizeof(ROMAN_V) - 1 },
{ 10, ROMAN_X , sizeof(ROMAN_X) - 1 },
{ 50, ROMAN_L , sizeof(ROMAN_L) - 1 },
{ 100, ROMAN_C , sizeof(ROMAN_C) - 1 },
{ 500, ROMAN_D , sizeof(ROMAN_D) - 1 },
{1000, ROMAN_M , sizeof(ROMAN_M) - 1 }
};
arabicRomanPair* lastRomanArabicLookupEntry = &roman_arabic_lookup[sizeof(roman_arabic_lookup) /
sizeof(arabicRomanPair) - 1];
arabicRomanPair arabic_roman_lookup[] = {
{ 1, ROMAN_I , sizeof(ROMAN_I) - 1 },
{ 2, ROMAN_II , sizeof(ROMAN_II) - 1 },
{ 3, ROMAN_III, sizeof(ROMAN_III) - 1},
{ 4, ROMAN_IV , sizeof(ROMAN_IV) - 1 },
{ 5, ROMAN_V , sizeof(ROMAN_V) - 1 },
{ 9, ROMAN_IX , sizeof(ROMAN_IX) - 1 },
{ 10, ROMAN_X , sizeof(ROMAN_X) - 1 },
{ 40, ROMAN_XL , sizeof(ROMAN_XL) - 1 },
{ 50, ROMAN_L , sizeof(ROMAN_L) - 1 },
{ 90, ROMAN_XC , sizeof(ROMAN_XC) - 1 },
{ 100, ROMAN_C , sizeof(ROMAN_C) - 1 },
{ 400, ROMAN_CD , sizeof(ROMAN_CD) - 1 },
{ 500, ROMAN_D , sizeof(ROMAN_D) - 1 },
{ 900, ROMAN_CM , sizeof(ROMAN_CM) - 1 },
{1000, ROMAN_M , sizeof(ROMAN_M) - 1 }
};
arabicRomanPair* lastArabicRomanLookupEntry = &arabic_roman_lookup[sizeof(roman_arabic_lookup) /
sizeof(arabicRomanPair) - 1];
#define romanNumeralComponentIsFound() strncmp(position_in_roman_numeral, pair->roman, pair->romanLength) == 0
#define charactersRemainInRomanNumeral() strlen(position_in_roman_numeral) != 0
#define notPastEndOfLookupTable() pair <= lastRomanArabicLookupEntry
#define advanceToNextPositionInRomanNumeral() position_in_roman_numeral += pair->romanLength
int convertRomanToArabic(char* romanNumeral) {
char* position_in_roman_numeral = romanNumeral;
int accumulator = 0;
while( charactersRemainInRomanNumeral() ) {
arabicRomanPair* pair = roman_arabic_lookup;
while( notPastEndOfLookupTable() ) {
if(romanNumeralComponentIsFound()) {
accumulator += pair->arabic;
break;
}
pair++;
}
advanceToNextPositionInRomanNumeral();
}
return accumulator;
}
#define arabicValueNotDepleted() arabic_value > 0
#define exactMatchToArabicValue() pair->arabic == arabic_value
#define tableEntryExceedsArabicValue() pair->arabic > arabic_value
#define lastTableEntryIsLessOrEqualToArabicValue() pair == lastArabicRomanLookupEntry && pair->arabic <= arabic_value
#define arabicValueAndTableEntriesRemain() pair <= lastArabicRomanLookupEntry && arabic_value > 0
char* convertArabicToRoman(int arabic_number, char *romanNumeral){
int arabic_value = arabic_number;
while(arabicValueNotDepleted()) {
arabicRomanPair* pair = arabic_roman_lookup;
do {
if(lastTableEntryIsLessOrEqualToArabicValue()) {
strcat(romanNumeral, pair->roman);
arabic_value -= pair->arabic;
break;
}
if(tableEntryExceedsArabicValue()) {
strcat(romanNumeral, (pair - 1)->roman);
arabic_value -= (pair - 1)->arabic;
break;
}
else if (exactMatchToArabicValue()) {
strcat(romanNumeral, pair->roman);
arabic_value -= pair->arabic;
break;
}
pair++;
} while(arabicValueAndTableEntriesRemain());
}
return romanNumeral;
}<file_sep>/test/tests.c
#include <stdlib.h>
#include <stdio.h>
#include <check.h>
#include "romancalctest.h"
int main() {
int failed_test_count = 0;
Suite* calculator_suite = CalculatorSuite();
SRunner* runner = srunner_create(calculator_suite);
srunner_run_all(runner, CK_VERBOSE);
failed_test_count = srunner_ntests_failed(runner);
srunner_free(runner);
return failed_test_count;
}
<file_sep>/test/romancalctest.h
#ifndef ROMANCALCTEST_H_DEFINED
#define ROMANCALCTEST_H_DEFINED
#include <check.h>
Suite* CalculatorSuite(void);
#endif
<file_sep>/makefile
CFLAGS:=-std=c99 -Wall -Werror -g -pedantic
objects:=$(patsubst src/%.c,src/%.o,$(wildcard src/*.c))
test_objects:=$(patsubst test/%.c,test/%.o,$(wildcard test/*.c))
clean:
@clear
@echo "*** Cleaning project ***\n"
@cd ~/projects/kata/c/RomanNumeralCalcInC
@rm -r -f src/*.o test/*.o output
build: clean $(objects) $(test_objects)
@echo "\n*** Building RomanNumeralCalcInC ***\n"
@mkdir -p output
@gcc $(CFLAGS) -o output/tests $(test_objects) $(objects) `pkg-config --cflags --libs check`
test: build
@echo "\n*** Running tests ***\n"
@output/tests
<file_sep>/src/validate.c
#include "validate.h"
char* uppercase(char* parm){
int parm_length = strlen(parm);
for(int i = 0 ; i < parm_length ; i++) {
parm[i] = toupper((int) parm[i]);
}
return parm;
}
#define isNotValidOperator() strcmp(operator, "+") && strcmp(operator, "-" )
int validateInputParametersValid(char* first, char* operator, char* second) {
if(isNotValidOperator()) {
return OperatorInvalid;
}
if( !validateRomanNumeral(first) ) {
return FirstTermInvalid;
}
if( !validateRomanNumeral(second) ) {
return SecondTermInvalid;
}
return Success;
}
int validateInputTermsProperSize(char* first, char* second) {
if(strlen(first) > BUFFER_SIZE)
return FirstTermInvalid;
if( strlen(second) > BUFFER_SIZE )
return SecondTermInvalid;
return Success;
}
int validateInputParametersPresent(char* first, char* operator, char* second, char* result) {
if( first == NULL ) {
return FirstTermMissing;
}
if( second == NULL ) {
return SecondTermMissing;
}
if( operator == NULL ) {
return OperatorMissing;
}
if( result == NULL ) {
return OutputBufferMissing;
}
return Success;
}
#define notFinishedParsingRomanNumeral() current_index > 0
#define endOfRomanNumeralString() strlen(romanNumeral)
#define romanSubstringMatchesCurrentTableEntry() memcmp(&romanNumeral[current_index - pair->romanLength], pair->roman, pair->romanLength) == 0
#define valueNotFoundOrIsLessThanPrevious() !romanNumeralIsValid || current_value < previous_value
#define entireRomanNumeralProcessed() current_index == 0
_Bool validateRomanNumeral(char *romanNumeral) {
int current_value = 0;
int previous_value = 0;
int current_index = endOfRomanNumeralString();
_Bool romanNumeralIsValid = false;
if(current_index > BUFFER_SIZE)
return romanNumeralIsValid;
while(notFinishedParsingRomanNumeral()) {
romanNumeralIsValid = false;
for( arabicRomanPair* pair = roman_arabic_lookup ; pair <= lastRomanArabicLookupEntry ; pair++ ) {
if(romanSubstringMatchesCurrentTableEntry()) {
current_index -= pair->romanLength;
current_value = pair->arabic;
romanNumeralIsValid = true;
break;
}
}
if(valueNotFoundOrIsLessThanPrevious() ) {
romanNumeralIsValid = false;
break;
}
if(entireRomanNumeralProcessed()) {
break;
}
previous_value = current_value;
}
return romanNumeralIsValid;
}<file_sep>/test/romancalctest.c
#include <stdio.h>
#include <stdlib.h>
#include <check.h>
#include "romancalctest.h"
#include "../src/romancalc.h"
char result[BUFFER_SIZE];
void setup(void) {
memset(result, 0x00, sizeof(result));
}
void teardown(void) {
}
START_TEST(test_NULL_plus_I_Returns_FirstTermMissing) {
ck_assert_int_eq(RomanCalculator(NULL, "+", "I", result), FirstTermMissing);
}
END_TEST
START_TEST(test_IIIIIIIIIIIIIIIII_plus_I_Returns_FirstTermInvalid) {
ck_assert_int_eq(RomanCalculator("IIIIIIIIIIIIIIIII", "+","I", result), FirstTermInvalid);
}
END_TEST
START_TEST(test_I_plus_NULL_Returns_SecondTermMissing) {
ck_assert_int_eq(RomanCalculator("I", "+", NULL, result), SecondTermMissing);
}
END_TEST
START_TEST(test_I_plus_IIIIIIIIIIIIIIIII_Returns_SecondTermInvalid) {
ck_assert_int_eq(RomanCalculator("I", "+","IIIIIIIIIIIIIIIII", result), SecondTermInvalid);
}
END_TEST
START_TEST(test_I_NULL_I_Returns_OperatorMissing ) {
ck_assert_int_eq(RomanCalculator("I", NULL, "I", result), OperatorMissing);
}
END_TEST
START_TEST(test_I_plus_I_With_No_Result_Buffer_Returns_OutputBufferMissing) {
ck_assert_int_eq(RomanCalculator("I", "+", "I", NULL), OutputBufferMissing);
}
END_TEST
START_TEST(test_I_invalidOperator_I_Returns_OperatorInvalid) {
ck_assert_int_eq(RomanCalculator("I", "*", "I", result), OperatorInvalid);
}
END_TEST
START_TEST(test_IXC_plus_I_Returns_FirstTermInvalid) {
ck_assert_int_eq(RomanCalculator("IXC", "+", "I", result), FirstTermInvalid);
}
END_TEST
START_TEST(test_IC_plus_I_Returns_FirstTermInvalid) {
ck_assert_int_eq(RomanCalculator("IC", "+", "I", result), FirstTermInvalid);
}
END_TEST
START_TEST(test_DM_plus_I_Returns_FirstTermInvalid) {
ck_assert_int_eq(RomanCalculator("DM", "+", "I", result), FirstTermInvalid);
}
END_TEST
START_TEST(test_I_plus_DM_Returns_SecondTermInvalid) {
ck_assert_int_eq(RomanCalculator("I", "+", "DM", result), SecondTermInvalid);
}
END_TEST
START_TEST(test_W_plus_I_Returns_FirstTermInvalid) {
ck_assert_int_eq(RomanCalculator("W", "+", "I", result), FirstTermInvalid);
}
END_TEST
START_TEST(test_I_plus_W_Returns_SecondTermInvalid) {
ck_assert_int_eq(RomanCalculator("I", "+", "W", result), SecondTermInvalid);
}
END_TEST
START_TEST(test_I_plus_I_Returns_II){
RomanCalculator("I", "+", "I", result);
ck_assert_str_eq(result, "II");
}
END_TEST
START_TEST(test_i_plus_I_Returns_II){
RomanCalculator("i", "+", "I", result);
ck_assert_str_eq(result, "II");
}
END_TEST
START_TEST(test_I_plus_i_Returns_II){
RomanCalculator("I", "+", "i", result);
ck_assert_str_eq(result, "II");
}
END_TEST
START_TEST(test_I_plus_II_Returns_III){
RomanCalculator("I", "+", "II", result);
ck_assert_str_eq(result, "III");
}
END_TEST
START_TEST(test_I_plus_III_Returns_IV){
RomanCalculator("I", "+", "III", result);
ck_assert_str_eq(result, "IV");
}
END_TEST
START_TEST(test_I_plus_V_Returns_VI){
RomanCalculator("I", "+", "V", result);
ck_assert_str_eq(result, "VI");
}
END_TEST
START_TEST(test_LIII_plus_DCDLIX_returns_MXII){
RomanCalculator("LIII", "+", "DCDLIX", result);
ck_assert_str_eq(result, "MXII");
}
END_TEST
START_TEST(test_XLIX_plus_I_returns_L){
RomanCalculator("XLIX", "+", "I", result);
ck_assert_str_eq(result, "L");
}
END_TEST
START_TEST(test_MMMM_plus_I_returns_FirstTermOverflow){
ck_assert_int_eq( RomanCalculator("MMMM","+","I", result), FirstTermOverflow);
}
END_TEST
START_TEST(test_I_plus_MMMM_returns_SecondTermOverflow){
ck_assert_int_eq( RomanCalculator("I","+","MMMM", result), SecondTermOverflow);
}
END_TEST
START_TEST(test_MMM_plus_MMM_returns_ResultOverflow){
ck_assert_int_eq( RomanCalculator("MMM","+","MMM", result), ResultOverflow);
}
END_TEST
START_TEST(test_all_values_returns_correct_results){
for( int i = 1 ; i < (MAX_ARABIC_VALUE - 1) ; i++ ){
char term1[BUFFER_SIZE];
int j = (MAX_ARABIC_VALUE - 1) - i;
char term2[BUFFER_SIZE];
char romanNumeral[BUFFER_SIZE];
char result[BUFFER_SIZE];
memset(term1, 0x00, sizeof(term1));
memset(term2, 0x00, sizeof(term2));
memset(result, 0x00, sizeof(result));
memset(romanNumeral,0x00,sizeof(romanNumeral));
strcat(term1, convertArabicToRoman(i, romanNumeral));
memset(romanNumeral,0x00,sizeof(romanNumeral));
strcat(term2, convertArabicToRoman(j, romanNumeral));
ck_assert_int_eq(RomanCalculator(term1, "+", term2, result), Success);
}
ck_assert_int_eq(0,0);
}
END_TEST
START_TEST(test_II_minus_I_returns_I){
RomanCalculator("II", "-", "I", result);
ck_assert_str_eq( result, "I");
}
END_TEST
START_TEST(test_I_minus_I_returns_ResultUnderflow){
ck_assert_int_eq(RomanCalculator("I", "-", "I", result), ResultUnderflow);
}
END_TEST
Suite* CalculatorSuite(void) {
Suite* suite = suite_create("Roman Numeral Calculator Tests");
TCase* inputs_case = tcase_create("Validate Input Arguments");
tcase_add_checked_fixture(inputs_case, setup, NULL);
tcase_add_test(inputs_case, test_NULL_plus_I_Returns_FirstTermMissing);
tcase_add_test(inputs_case, test_IIIIIIIIIIIIIIIII_plus_I_Returns_FirstTermInvalid);
tcase_add_test(inputs_case, test_I_plus_NULL_Returns_SecondTermMissing);
tcase_add_test(inputs_case, test_I_plus_IIIIIIIIIIIIIIIII_Returns_SecondTermInvalid);
tcase_add_test(inputs_case, test_I_NULL_I_Returns_OperatorMissing);
tcase_add_test(inputs_case, test_I_plus_I_With_No_Result_Buffer_Returns_OutputBufferMissing);
tcase_add_test(inputs_case, test_I_invalidOperator_I_Returns_OperatorInvalid);
tcase_add_test(inputs_case, test_IXC_plus_I_Returns_FirstTermInvalid);
tcase_add_test(inputs_case, test_IC_plus_I_Returns_FirstTermInvalid);
tcase_add_test(inputs_case, test_DM_plus_I_Returns_FirstTermInvalid);
tcase_add_test(inputs_case, test_I_plus_DM_Returns_SecondTermInvalid);
suite_add_tcase(suite, inputs_case);
TCase* invalid_numeral_case = tcase_create("Check for Invalid Characters");
tcase_add_test(invalid_numeral_case, test_W_plus_I_Returns_FirstTermInvalid);
tcase_add_test(invalid_numeral_case, test_I_plus_W_Returns_SecondTermInvalid);
suite_add_tcase(suite, invalid_numeral_case);
TCase* case_insensitive_case = tcase_create("Allow Case Insensitive Terms");
tcase_add_test(case_insensitive_case, test_i_plus_I_Returns_II);
tcase_add_test(case_insensitive_case, test_I_plus_i_Returns_II);
suite_add_tcase(suite, case_insensitive_case);
TCase* adding_case = tcase_create("Addition tests");
tcase_add_checked_fixture(adding_case, setup, NULL);
tcase_add_test(adding_case, test_I_plus_I_Returns_II);
tcase_add_test(adding_case, test_I_plus_II_Returns_III);
tcase_add_test(adding_case, test_I_plus_III_Returns_IV);
tcase_add_test(adding_case, test_I_plus_V_Returns_VI);
tcase_add_test(adding_case, test_LIII_plus_DCDLIX_returns_MXII);
tcase_add_test(adding_case, test_XLIX_plus_I_returns_L);
tcase_add_test(adding_case, test_MMMM_plus_I_returns_FirstTermOverflow);
tcase_add_test(adding_case, test_I_plus_MMMM_returns_SecondTermOverflow);
tcase_add_test(adding_case, test_MMM_plus_MMM_returns_ResultOverflow);
tcase_add_test(adding_case, test_all_values_returns_correct_results);
suite_add_tcase(suite, adding_case);
TCase* subtraction_case = tcase_create("Subtraction tests");
tcase_add_test(subtraction_case, test_II_minus_I_returns_I);
tcase_add_test(subtraction_case, test_I_minus_I_returns_ResultUnderflow);
suite_add_tcase(suite, subtraction_case);
return suite;
}
<file_sep>/src/validate.h
#ifndef VALIDATE_H_DEFINED
#define VALIDATE_H_DEFINED
#include "convert.h"
char* uppercase(char* parm);
_Bool validateRomanNumeral(char *romanNumeral);
int validateInputParametersPresent(char* first, char* operator, char* second, char* result);
int validateInputParametersValid(char* first, char* operator, char* second);
int validateInputTermsProperSize(char* first, char* second);
#define BUFFER_SIZE 16
enum CalculatorStatus {
Success,
FirstTermMissing,
FirstTermInvalid,
FirstTermOverflow,
SecondTermMissing,
SecondTermInvalid,
SecondTermOverflow,
OperatorMissing,
OperatorInvalid,
OutputBufferMissing,
ResultUnderflow,
ResultOverflow
};
#endif | db487fccb3deff564d4612e25395998a421bdcee | [
"Markdown",
"C",
"Makefile"
]
| 11 | C | accenture-schuylervo/RomanNumeralCalcInC | 2a54f598dccd72fb3d9fd34d6e43d0321cfdcd90 | 0d4e215c2e42a990fe377fc5fbcbb45de575361f |
refs/heads/master | <repo_name>jatin77/taskManagerBackUp<file_sep>/src/app/models/notifications.ts
export class Notifications {
constructor(public id: number, public created_on: string) {}
}
<file_sep>/src/app/services/sync-service.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { SyncServiceService } from './sync-service.service';
describe('SyncServiceService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: SyncServiceService = TestBed.get(SyncServiceService);
expect(service).toBeTruthy();
});
});
<file_sep>/src/app/components/sign-in/sign-in.component.ts
import { Component, OnInit } from "@angular/core";
import { SignInService } from "src/app/services/sign-in.service";
import { Router } from "@angular/router";
@Component({
selector: "app-sign-in",
templateUrl: "./sign-in.component.html",
styleUrls: ["./sign-in.component.scss"]
})
export class SignInComponent implements OnInit {
error: boolean = false;
hello: boolean = true;
username: string = "";
password: string = "";
constructor(private signInService: SignInService, private router: Router) {}
clearFields() {
this.username = "";
this.password = "";
}
ngOnInit() {}
onSubmit = () => {
if (this.username === "" || this.password === "") {
console.log("error");
this.error = true;
this.setErrorToFalse();
} else {
const authDetail = {
username: this.username,
password: <PASSWORD>
};
this.signInService.signIn(authDetail).subscribe(
response => {
console.log(response, "success");
localStorage.setItem("token", response.token);
this.hello = false;
this.router.navigate(["/allTask"]);
},
error => {
console.log("error");
this.error = true;
this.setErrorToFalse();
}
);
this.clearFields();
}
};
setErrorToFalse() {
setTimeout(() => {
this.error = false;
}, 5000);
}
}
<file_sep>/src/app/components/users/users.component.ts
import { Component, OnInit, OnDestroy } from "@angular/core";
import { Users } from "src/app/models/users";
import { UserService } from "src/app/services/user.service";
import { TaskService } from "src/app/services/task.service";
import { Task } from "src/app/models/task";
import { Subscription } from "rxjs";
@Component({
selector: "app-users",
templateUrl: "./users.component.html",
styleUrls: ["./users.component.scss"]
})
export class UsersComponent implements OnInit, OnDestroy {
private getTaskSubscription: Subscription;
private getUsersSubscription: Subscription;
tasks: Task[];
users: Users[];
constructor(
private userService: UserService,
private taskService: TaskService
) {}
ngOnInit() {
this.getUsersSubscription = this.userService
.getUsers()
.subscribe(users => (this.users = users));
this.getTaskSubscription = this.taskService
.getTasks()
.subscribe(tasks => (this.tasks = tasks));
}
trackByFunction(index, item) {
return index;
}
showUserDetail(id) {
let selectedUser = this.users.filter(user => user.id === id);
let selectedUserTask = this.tasks.filter(task => id === task.remind_to);
this.taskService.showSelectedTask = selectedUserTask;
this.userService.showSelectedUser = selectedUser;
}
ngOnDestroy(): void {
this.getUsersSubscription.unsubscribe();
this.getTaskSubscription.unsubscribe();
}
}
<file_sep>/src/app/services/task.service.ts
import { Injectable } from "@angular/core";
import { SyncServiceService } from "./sync-service.service";
@Injectable({
providedIn: "root"
})
export class TaskService {
showSelectedTask;
constructor(private syncService: SyncServiceService) {}
getTasks() {
return this.syncService.getSyncTasks();
}
addTask(task) {
return this.syncService.addSyncTask(task);
}
}
<file_sep>/src/app/components/all-task/all-task.component.ts
import { Component, OnInit, OnDestroy } from "@angular/core";
import { Task } from "src/app/models/task";
import { TaskService } from "src/app/services/task.service";
import { Subscription } from "rxjs";
@Component({
selector: "app-all-task",
templateUrl: "./all-task.component.html",
styleUrls: ["./all-task.component.scss"]
})
export class AllTaskComponent implements OnInit, OnDestroy {
private getTaskSubscription: Subscription;
tasks: Task[];
constructor(private taskService: TaskService) {}
ngOnInit() {
this.getTaskSubscription = this.taskService
.getTasks()
.subscribe(tasks => (this.tasks = tasks));
}
trackByFunction(index, item) {
return index;
}
ngOnDestroy(): void {
this.getTaskSubscription.unsubscribe();
}
}
<file_sep>/src/app/services/sync-service.service.ts
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Task } from "../models/task";
import { Notifications } from "../models/notifications";
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json"
})
};
@Injectable({
providedIn: "root"
})
export class SyncServiceService {
notificationUrl: string = "http://localhost:8000/notifications/";
signInUrl: string = "http://localhost:8000/api-token-auth/";
taskUrl: string = "http://127.0.0.1:8000/api/create-task/";
constructor(private http: HttpClient) {}
signInSync(authDetail): Observable<any> {
return this.http.post(this.signInUrl, authDetail, httpOptions);
}
getSyncTasks(): Observable<Task[]> {
return this.http.get<Task[]>(this.taskUrl, {
headers: new HttpHeaders({
Authorization: "Bearer " + localStorage.getItem("token")
})
});
}
addSyncTask(task): Observable<any> {
return this.http.post(this.taskUrl, task, httpOptions);
}
getSyncNotifications(): Observable<Notifications[]> {
return this.http.get<Notifications[]>(this.notificationUrl, {
headers: new HttpHeaders({
Authorization: "Bearer " + localStorage.getItem("token")
})
});
}
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { SignInComponent } from "./components/sign-in/sign-in.component";
import { AddTaskComponent } from "./components/add-task/add-task.component";
import { AllTaskComponent } from "./components/all-task/all-task.component";
import { UsersComponent } from "./components/users/users.component";
import { NotificationsComponent } from "./components/notifications/notifications.component";
import { UserDetailComponent } from "./components/user-detail/user-detail.component";
import { AuthGuard } from "./authGuard/auth.guard";
const routes: Routes = [
{ path: "", redirectTo: "/signIn", pathMatch: "full" },
{ path: "signIn", component: SignInComponent },
{ path: "addTask", component: AddTaskComponent, canActivate: [AuthGuard] },
{ path: "allTask", component: AllTaskComponent, canActivate: [AuthGuard] },
{ path: "users", component: UsersComponent, canActivate: [AuthGuard] },
{
path: "notifications",
component: NotificationsComponent,
canActivate: [AuthGuard]
},
{
path: "userDetail/:id",
component: UserDetailComponent,
canActivate: [AuthGuard]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
<file_sep>/src/app/services/notifications.service.ts
import { Injectable } from "@angular/core";
import { SyncServiceService } from "./sync-service.service";
@Injectable({
providedIn: "root"
})
export class NotificationsService {
constructor(private syncService: SyncServiceService) {}
getNotifications() {
return this.syncService.getSyncNotifications();
}
}
<file_sep>/src/app/components/notifications/notifications.component.ts
import { Component, OnInit, OnDestroy } from "@angular/core";
import { NotificationsService } from "src/app/services/notifications.service";
import { Notifications } from "src/app/models/notifications";
import { Subscription } from "rxjs";
@Component({
selector: "app-notifications",
templateUrl: "./notifications.component.html",
styleUrls: ["./notifications.component.scss"]
})
export class NotificationsComponent implements OnInit, OnDestroy {
private getNotifySubscription: Subscription;
interval;
notifications: Notifications[];
constructor(private notifyService: NotificationsService) {}
ngOnInit() {
this.interval = setInterval(() => {
this.notifyInterval();
}, 1000);
}
notifyInterval = () => {
this.getNotifySubscription = this.notifyService
.getNotifications()
.subscribe(notifications => (this.notifications = notifications));
};
trackByFunction(index, item) {
return index;
}
ngOnDestroy(): void {
this.getNotifySubscription.unsubscribe();
clearInterval(this.interval);
}
}
<file_sep>/src/app/components/user-detail/user-detail.component.ts
import { Component, OnInit } from "@angular/core";
import { TaskService } from "src/app/services/task.service";
import { UserService } from "src/app/services/user.service";
@Component({
selector: "app-user-detail",
templateUrl: "./user-detail.component.html",
styleUrls: ["./user-detail.component.scss"]
})
export class UserDetailComponent implements OnInit {
userTasks;
selectedUser;
constructor(
private taskService: TaskService,
private userService: UserService
) {}
ngOnInit() {
this.userTasks = this.taskService.showSelectedTask;
this.selectedUser = this.userService.showSelectedUser[0];
}
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { HeaderComponent } from "./components/header/header.component";
import { FooterComponent } from "./components/footer/footer.component";
import { SignInComponent } from "./components/sign-in/sign-in.component";
import { AddTaskComponent } from "./components/add-task/add-task.component";
import { AllTaskComponent } from "./components/all-task/all-task.component";
import { UsersComponent } from "./components/users/users.component";
import { NotificationsComponent } from "./components/notifications/notifications.component";
import { UserDetailComponent } from "./components/user-detail/user-detail.component";
import { FormsModule } from "@angular/forms";
import { ErrorComponent } from "./components/error/error.component";
import { AuthGuard } from "./authGuard/auth.guard";
import { AuthInterceptor } from "./authInterceptor/auth.interceptor";
import { SuccessComponent } from './components/success/success.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
SignInComponent,
AddTaskComponent,
AllTaskComponent,
UsersComponent,
NotificationsComponent,
UserDetailComponent,
ErrorComponent,
SuccessComponent
],
imports: [BrowserModule, AppRoutingModule, FormsModule, HttpClientModule],
providers: [
AuthGuard,
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule {}
<file_sep>/src/app/services/sign-in.service.ts
import { Injectable } from "@angular/core";
import { SyncServiceService } from "./sync-service.service";
@Injectable({
providedIn: "root"
})
export class SignInService {
constructor(private syncService: SyncServiceService) {}
signIn(authDetail) {
return this.syncService.signInSync(authDetail);
}
getToken() {
return localStorage.getItem("token");
}
}
<file_sep>/src/app/models/task.ts
export class Task {
constructor(
public title: string,
public remind_to: number,
public created_by: number,
public remainder_date: string,
public created_date: string,
public id: number
) {}
}
<file_sep>/src/app/components/add-task/add-task.component.ts
import {
Component,
OnInit,
Output,
EventEmitter,
OnDestroy
} from "@angular/core";
import { Users } from "src/app/models/users";
import { Task } from "src/app/models/task";
import { UserService } from "src/app/services/user.service";
import { TaskService } from "src/app/services/task.service";
import { Subscription } from "rxjs";
@Component({
selector: "app-add-task",
templateUrl: "./add-task.component.html",
styleUrls: ["./add-task.component.scss"]
})
export class AddTaskComponent implements OnInit, OnDestroy {
private addTaskSubscription: Subscription;
error: boolean = false;
success: boolean = false;
displayTasksPage: boolean = false;
users: Users[];
title: string = "";
remind_to: number = null;
created_by: number = null;
remainder_date: string = "";
created_date: string = "";
id: number = Math.floor(Math.random() * 100);
constructor(
private userService: UserService,
private taskService: TaskService
) {}
ngOnInit() {
this.addTaskSubscription = this.userService
.getUsers()
.subscribe(users => (this.users = users));
}
clearFields() {
this.title = "";
this.remind_to = null;
this.remainder_date = null;
}
onSubmit = () => {
if (
this.title === "" ||
this.remind_to === null ||
this.remainder_date === null
) {
console.log("error");
this.error = true;
setTimeout(() => {
this.error = false;
}, 5000);
} else {
let task = {
title: this.title,
remind_to: this.remind_to,
remainder_date: this.remainder_date
};
this.taskService.addTask(task).subscribe(
response => {
console.log("task assigned", task);
this.success = true;
setTimeout(() => {
this.success = false;
}, 5000);
},
error => {
console.log("error", task);
this.error = true;
setTimeout(() => {
this.error = false;
}, 5000);
}
);
this.clearFields();
}
};
ngOnDestroy(): void {
this.addTaskSubscription.unsubscribe();
}
}
| e77ab1bbd5dd2e4c3412f9565128a2cfa2dc15f2 | [
"TypeScript"
]
| 15 | TypeScript | jatin77/taskManagerBackUp | a349459e6f81f900c8f8a3d0bf0f80a74debea51 | 579c771442a80c17cd44dc76344bcb99168a456b |
refs/heads/master | <file_sep>package tk.yaxin.thread;
/**
* 交替线程执行
* @author Administrator
*
*/
public class AlternateThread {
public static void main(String[] args){
byte[] aa = new byte[0];
byte[] bb = new byte[0];
Thread a = new Thread(new B(-1,bb,aa));
a.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread b = new Thread(new B(0,aa,bb));
b.start();
}
}
/**
* 主要的目的就是ThreadA->ThreadB->ThreadC->ThreadA循环执行三个线程。
* 为了控制线程执行的顺序,那么就必须要确定唤醒、等待的顺序,
* 所以每一个线程必须同时持有两个对象锁,才能继续执行。一个对象锁是prev,
* 就是前一个线程所持有的对象锁。还有一个就是自身对象锁。主要的思想就是,
* 为了控制执行的顺序,必须要先持有prev锁,也就前一个线程要释放自身对象锁,
* 再去申请自身对象锁,两者兼备时打印,之后首先调用self.notify()释放自身对象锁,
* 唤醒下一个等待线程,再调用prev.wait()释放prev对象锁,终止当前线程,
* 等待循环结束后再次被唤醒
*
* 交替线程执行
* @author Administrator
*
*/
class B implements Runnable{
volatile int i=0;
private byte[] pre;
private byte[] self;
public B(int i,byte[] pre,byte[] self){
this.i=i;
this.pre=pre;
this.self=self;
}
public void run() {
while(i<100){
synchronized (pre) {
i+=2;
System.out.println(i);
synchronized (self) {
self.notifyAll();
}
try {
pre.wait();//线程阻塞,停止在这里,后面的内容暂停
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized (self){
self.notify();
}
}
}<file_sep>java-thread
===========
java线程-程序例子<br />
功能:<br />
1、交替线程之间的等待和唤醒。
| 89a372c3f56083e135a8e340ce9c803536650710 | [
"Markdown",
"Java"
]
| 2 | Java | fashionfz/java-thread | 3442718f23d40b8d9c8621495159a740864f5a52 | 945c77331cdf0ae7d69f13a1722a7be46261602c |
refs/heads/master | <repo_name>NamelessCoder/typo3-repository-gizzle<file_sep>/README.md
<img src="https://release.namelesscoder.net/typo3-repository-gizzle-logo.svg"
alt="TYPO3 GitHub Repository Releaser" style="width: 100%;" />
[](https://jenkins.fluidtypo3.org/job/typo3-repository-gizzle/) [](https://coveralls.io/r/NamelessCoder/typo3-repository-gizzle)
This project allows any GitHub-hosted repository containing a TYPO3 CMS
extension to be released to the official TYPO3 Extension Repository
(hereafter referred to as TER) by adding a very simple GitHub web hook.
The official endpoint of this service is `https://release.namelesscoder.net`
but you are welcome to install this package on your own and use that
installation location as endpoint.
The project uses Gizzle to listen for GitHub events and uses Gizzle TYPO3
plugins to do the actual uploading. Internally, the Gizzle TYPO3 plugins
use the TYPO3 Repository Client.
* https://github.com/NamelessCoder/gizzle
* https://github.com/NamelessCoder/gizzle-typo3-plugins
* https://github.com/NamelessCoder/typo3-repository-client
Requirements
------------
* A **public** GitHub repository containing your extension's source code.
* For custom endpoints only: access to the `git` and `php` CLI commands as
well as some way to serve the `web/index.php` file through HTTP/HTTPS.
Installation
------------
1. Edit the settings of your repository and locate "Webhooks & services".
2. Click "Add webhook" to create a new hook.
3. In "Payload URL", fill in the endpoint URL you wish to use. The default
URL is `https://release.namelesscoder.net`
4. Add your unique credentials and information to the URL. There are two
possible URL formats:
* If your GitHub repository name is **not the same** as your TER extension
key, a URL like `https://release.namelesscoder.net/my_extension/user:password`.
must be used - which will release the repository as key `my_extension`.
* If your GitHub repository is already named the same as your extension
key you can leave out that part of the URL and use a shorter URL like
`https://release.namelesscoder.net/user:password`.
* Alternatively, if you feel more comfortable with it and the endpoint
supports it, use `https://username:[email protected]/my_extension`.
This method only works if the server supports the `authnz_external_module`
or corresponding external authentications - see below.
5. Enter a "Secret". We use a fixed secret for now - enter the text `typo3rocks`.
6. Leave the "Which events..." selectors as-is. We only need the `push` event.
Unfortunately there is no way to isolate an event that only gets dispatched
when you create new tags - which is why we have to listen to all `push`es.
We simply ignore those that do not refer to a tag.
Security
--------
Because your credentials are included in the URL, we are doing the following
on the default endpoint and you should definitely do the same if you create one:
* The URL is protected by SSL.
* The full URL of requests is never logged.
Please note that this credentials-in-URL approach is considered *temporary* and
is only implemented because there currently are no other ways. The end goal is
to use a token solution both for the "Secret" that is currently fixed, as well
as for the credentials that must be passed to TER. The former will be solved
by creating an official GitHub Service but the latter will depend on work that
has to be done on TER or even TYPO3 SSO itself.
If your web server supports it (Apache does via `authnz_external_module`) then
you can register an external authenticator (change/move the path if needed):
```
<IfModule authnz_external_module>
DefineExternalAuth fake environment /var/www/release.namelesscoder.net/fake-auth.sh
</IfModule>
```
...which goes in your virtual host or root server configuration. The `fake-auth.sh`
script is a dummy that allows any username and password to be authenticated -
and if done this way, this project will instead read those (fake) credentials.
This means you can specify the credentials to use when uploading to TER, as
`https://username:[email protected]/my_extension`.
Usage
-----
To create a new TER release from your GitHub repository simply create a new
tag and push it. The uploader will then use the message of the commit you tag
as the upload comment on TER. To create and push a new tag:
```
git tag 1.2.3
git push origin 1.2.3
```
Which creates a new tag called `1.2.3` and pushes it to the remote called `origin`.
Viewing results
---------------
The results of uploads triggered this way can be read in two different places:
* The **publicly available** message that the release was created gets added
as a comment to the commit that was HEAD of the repository when tagging.
* The **privately available** debugging information can be viewed by locating
the "Webhooks & services" panel as described in the installation section, and
clicking the URL that was added. A short list of most recent transactions is
displayed and clicking each one will allow you to read any technical errors.
Behavior
--------
The behavior of this plugin is very easily described:
1. Whenever you push to GitHub, we receive an event.
2. We analyse the Payload HEAD:
* If it is not a new tag we exit.
* If it is a new tag we upload a new release.
3. We set a "success" status flag on the commit you tagged.
4. We add a comment to the commit you tagged, saying it was released to TER.
5. We assign a bit of debugging information and send our response to GitHub.
The whole process should only take a couple of seconds, depending on how large
your extension is. If at any point during the process an error occurs, it is
caught and can be inspected in the web hook response as described above.
<file_sep>/tests/unit/GizzlePlugins/ExtensionRepositoryReleasePluginTest.php
<?php
namespace NamelessCoder\TYPO3RepositoryGizzle\Tests\Unit\GizzlePlugins;
use NamelessCoder\Gizzle\Payload;
use NamelessCoder\Gizzle\Repository;
use NamelessCoder\TYPO3RepositoryGizzle\GizzlePlugins\ExtensionRepositoryReleasePlugin;
/**
* Class ExtensionRepositoryReleasePluginTest
*/
class ExtensionRepositoryReleasePluginTest extends \PHPUnit_Framework_TestCase {
/**
* @return void
*/
public function testValidateCredentialsFileReturnsNullOnNoError() {
$credentials = array('foo', 'bar');
$instance = $this->getMock(ExtensionRepositoryReleasePlugin::class, array('readUploadCredentials'));
$instance->expects($this->once())->method('readUploadCredentials')->willReturn($credentials);
$method = new \ReflectionMethod($instance, 'validateCredentialsFile');
$method->setAccessible(TRUE);
$result = $method->invokeArgs($instance, array(NULL));
$this->assertNull($result);
}
/**
* @return void
*/
public function testValidateCredentialsFileThrowsExceptionOnMissingUriParameters() {
$credentials = array('foo');
$instance = $this->getMock(ExtensionRepositoryReleasePlugin::class, array('readUploadCredentials'));
$instance->expects($this->once())->method('readUploadCredentials')->willReturn($credentials);
$method = new \ReflectionMethod($instance, 'validateCredentialsFile');
$method->setAccessible(TRUE);
$this->setExpectedException('RuntimeException');
$method->invokeArgs($instance, array(NULL));
}
/**
* @return void
*/
public function testReadUploadCredentials() {
$uri = array('foo:bar');
$instance = $this->getMock(ExtensionRepositoryReleasePlugin::class, array('readRequestUriParameters'));
$instance->expects($this->once())->method('readRequestUriParameters')->willReturn($uri);
$method = new \ReflectionMethod($instance, 'readUploadCredentials');
$method->setAccessible(TRUE);
$result = $method->invokeArgs($instance, array(NULL));
$this->assertEquals(array('foo', 'bar'), $result);
}
/**
* @dataProvider getWorkingDirectoryTestValues
* @param array $uri
* @param string $expected
* @return void
*/
public function testGetWorkingDirectoryName(array $uri, $expected) {
$instance = $this->getMock(ExtensionRepositoryReleasePlugin::class, array('readRequestUriParameters'));
$instance->expects($this->once())->method('readRequestUriParameters')->willReturn($uri);
$method = new \ReflectionMethod($instance, 'getWorkingDirectoryName');
$method->setAccessible(TRUE);
$repository = new Repository();
$repository->setName('default');
$payload = $this->getMock(Payload::class, array('getRepository'), array(), '', FALSE);
$payload->expects($this->once())->method('getRepository')->willReturn($repository);
$result = $method->invokeArgs($instance, array($payload));
$this->assertEquals($expected, $result);
}
/**
* @return array
*/
public function getWorkingDirectoryTestValues() {
return array(
array(array(), 'default'),
array(array('foo:bar'), 'default'),
array(array('foo'), 'foo'),
);
}
/**
* @return void
*/
public function testReadRequestUriParameters() {
$instance = new ExtensionRepositoryReleasePlugin();
$method = new \ReflectionMethod($instance, 'readRequestUriParameters');
$method->setAccessible(TRUE);
$_SERVER['REQUEST_URI'] = '/foo/bar/';
$result = $method->invoke($instance);
$this->assertEquals(array('foo', 'bar'), $result);
unset($_SERVER['REQUEST_URI']);
}
/**
* @return void
*/
public function testReadRequestUriParametersReturnsHttpAuthenticationIfSet() {
$instance = new ExtensionRepositoryReleasePlugin();
$method = new \ReflectionMethod($instance, 'readRequestUriParameters');
$method->setAccessible(TRUE);
$_SERVER['REQUEST_URI'] = '/foo/bar/';
$_SERVER['PHP_AUTH_USER'] = 'dummy';
$_SERVER['PHP_AUTH_PW'] = '<PASSWORD>';
$result = $method->invoke($instance);
$this->assertEquals(array('dummy:password'), $result);
unset($_SERVER['REQUEST_URI'], $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
}
}
<file_sep>/src/GizzlePlugins/ExtensionRepositoryReleasePlugin.php
<?php
namespace NamelessCoder\TYPO3RepositoryGizzle\GizzlePlugins;
use NamelessCoder\Gizzle\Payload;
use NamelessCoder\GizzleTYPO3Plugins\GizzlePlugins\ExtensionRepositoryReleasePlugin as BaseExtensionRepositoryReleasePlugin;
/**
* Class ExtensionRepositoryReleasePlugin
*/
class ExtensionRepositoryReleasePlugin extends BaseExtensionRepositoryReleasePlugin {
/**
* Validates the credentials "file" - by inspecting
* the potential credentials returned from the
* readUploadCredentials() method.
*
* @param string $credentialsFile
* @throws \RuntimeException
*/
protected function validateCredentialsFile($credentialsFile) {
$credentials = $this->readUploadCredentials(NULL);
if (2 !== count($credentials)) {
throw new \RuntimeException(
'Invalid credentials provided; must be a string of "username:password" including the colon'
);
}
}
/**
* @param string $credentialsFile
* @return array
*/
protected function readUploadCredentials($credentialsFile) {
$uri = $this->readRequestUriParameters();
return explode(':', (string) end($uri));
}
/**
* Returns a working directory name either specified in the
* URL as very first segment, or if that segment does not
* contain the directory name, taken from the name of the
* repository from which Payload comes.
*
* @param Payload $payload
* @return string
*/
protected function getWorkingDirectoryName(Payload $payload) {
$uri = $this->readRequestUriParameters();
$suspect = reset($uri);
$directory = $payload->getRepository()->getName();
if (FALSE !== $suspect && FALSE === strpos($suspect, ':')) {
$directory = $suspect;
}
return $directory;
}
/**
* @return array
*/
protected function readRequestUriParameters() {
if (FALSE === empty($_SERVER['PHP_AUTH_USER'])) {
return array($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']);
}
return explode('/', trim($_SERVER['REQUEST_URI'], '/'));
}
}
<file_sep>/src/GizzlePlugins/PluginList.php
<?php
namespace NamelessCoder\TYPO3RepositoryGizzle\GizzlePlugins;
use NamelessCoder\Gizzle\PluginListInterface;
/**
* Class PluginList
*/
class PluginList implements PluginListInterface {
/**
* @var array
*/
protected $settings = array();
/**
* Initialize the plugin lister with an array of settings.
*
* @param array $settings
* @return void
*/
public function initialize(array $settings) {
$this->settings = $settings;
}
/**
* Get all class names of plugins delivered from implementer package.
*
* @return string[]
*/
public function getPluginClassNames() {
return array(
'NamelessCoder\\TYPO3RepositoryGizzle\\GizzlePlugins\\ExtensionReleasePlugin'
);
}
}
<file_sep>/tests/unit/GizzlePlugins/PluginListTest.php
<?php
namespace NamelessCoder\TYPO3RepositoryGizzle\Tests\Unit\GizzlePlugins;
use NamelessCoder\TYPO3RepositoryGizzle\GizzlePlugins\PluginList;
/**
* Class PluginListTest
*/
class PluginListTest extends \PHPUnit_Framework_TestCase {
/**
* @return void
*/
public function testInitializeSettings() {
$instance = new PluginList();
$settings = array('foo' => 'bar');
$instance->initialize($settings);
$this->assertAttributeEquals($settings, 'settings', $instance);
}
/**
* @return void
*/
public function testGetPluginClassNames() {
$instance = new PluginList();
$classes = $instance->getPluginClassNames();
$this->assertContains('NamelessCoder\\TYPO3RepositoryGizzle\\GizzlePlugins\\ExtensionReleasePlugin', $classes);
}
}
| 7a0d90b991e82b937f267be7c3667d407172da14 | [
"Markdown",
"PHP"
]
| 5 | Markdown | NamelessCoder/typo3-repository-gizzle | b4e47f2514e426134c77f60ca74221f45bf99bfa | 06b42c18b60b028923588c93f0e8c3c314daada2 |
refs/heads/master | <repo_name>carlocaetano/redux-boilerplate<file_sep>/src/scripts/components/scenes/index.js
'use strict';
export Dashboard from './dashboard';
export NotFound from './notFound';
<file_sep>/src/scripts/components/scenes/dashboard/index.js
'use strict';
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Immutable from 'immutable';
import { example } from 'actions';
import { mapActions } from 'utils';
import css from 'react-css-modules';
import styles from './dasbhoard.css';
const mapState = (state) => {
return {
example: state.example
};
};
@connect(mapState, mapActions(example))
@css(styles)
export default class Dashboard extends Component {
static propTypes = {
actions: PropTypes.shape({
increment: PropTypes.function,
decrement: PropTypes.function
}).isRequired,
example: PropTypes.instanceOf(Immutable.Map)
}
increment() {
this.props.actions.increment(1);
}
decrement() {
this.props.actions.decrement(1);
}
render() {
return (
<div>
<h1 styleName='heading'>Dashboard</h1>
<p>Counter: { this.props.example.get('counter') }</p>
<button onClick={ ::this.increment }>Add</button>
<button onClick={ ::this.decrement }>Remove</button>
</div>
);
}
}
<file_sep>/src/scripts/utils/index.js
'use strict';
export * from './mapActions.js';
<file_sep>/src/scripts/index.js
'use strict';
// App entrypoint
import ReactDOM from 'react-dom';
import { Routes } from './routes.js';
ReactDOM.render(Routes, document.getElementById('content'));
<file_sep>/README.md
# Redux boilerplate
This project contains:
Tooling:
- `webpack 1.12`
- `babel 5.8`
- `eslint 1.7`
- `react-transform-hmr`: hot reloading
- `react-transform-hmr-catch-errors`: nice error screens
- `postcss 5`
- `postcss-nested 1`
- `postcss-constants 0.1`
- `postcss-nested 1`
- `cssnext 1.8`
- `normalize.css 3`
- `lost 6`: grid system
- `mocha 2`: testing
- `chai 3`: assertions
- `jsdom 7`: virtual rendering of react components within tests
Libraries:
- `react 0.14`
- `immutable 3.7`
- `redux 3`
- `redux-simple-router 1`: for storing router state in redux
- `react-css-modules`: for applying `css-modules` to react components
### NPM commands:
`npm run-script start`: Starts the dev server on http://localhost:3000/ with hot
reload. This uses `webpack.config.dev.js`
`npm run-script watch`: Starts webpack compilation to dist/bundle.{js,css} and
*watches* for file changes. This uses `webpack.config.dev.js`
`npm run-script build`: Starts webpack compilation to dist/bundle.{js,css} using
the production config
<file_sep>/src/scripts/reducers/index.js
'use strict';
// Import all reducers and export a single combined reducer
import { combineReducers } from 'redux';
import example from './example';
import { routeReducer } from 'redux-simple-router';
export default combineReducers({
router: routeReducer,
// app-specific reducers
example
});
<file_sep>/src/scripts/app.js
'use strict';
import React, { Component, PropTypes } from 'react';
import css from 'react-css-modules';
import styles from './app.css';
@css(styles)
export default class App extends Component {
static propTypes = {
children: PropTypes.node.isRequired
}
render() {
return (
<div styleName='wrap'>
<p>Container for your app: add global headers/footers/wrapper components such as modals here.</p>
{ this.props.children }
</div>
);
}
}
<file_sep>/src/scripts/routes.js
'use strict';
import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { syncReduxAndRouter } from 'redux-simple-router';
import { createHistory } from 'history';
// Import all of our custom reducers from reducers/index.js
import reducer from 'reducers';
const store = createStore(reducer);
const history = createHistory();
syncReduxAndRouter(history, store, (state) => state.router);
import App from './app.js';
import {
Dashboard,
NotFound
} from 'components/scenes';
export const Routes = (
<Provider store={ store }>
<Router history={ history }>
<Route path='/' component={ App }>
<IndexRoute component={ Dashboard } />
<Route path='*' component={ NotFound } />
</Route>
</Router>
</Provider>
);
| c6fe8695940a88af6705a4759d1930d2ce5e6557 | [
"JavaScript",
"Markdown"
]
| 8 | JavaScript | carlocaetano/redux-boilerplate | 14aea2b22b1d96b15734d4b13b1388af76aa7fac | 8eff7445a7a54e9fc733f24f448d4d243b11c0b4 |
refs/heads/master | <repo_name>ionic-toolbox-work/IonicAdvancedWorkshop<file_sep>/FirebaseContactsApp/src/models/contacts.ts
export interface IContact{
name:string;
last_name:string;
birth_date:string;
address:string;
postal_code:number;
phone_number:string;
}
export class Contact implements IContact{
public name:string = "";
public last_name:string = "";
public birth_date:string = "";
public address:string = "";
public postal_code:number = 0;
public phone_number:string = "";
constructor(contact?:IContact){
if(contact){
this.name = contact.name;
this.last_name = contact.last_name;
this.birth_date = contact.birth_date;
this.address = contact.address;
this.postal_code = contact.postal_code;
this.phone_number = contact.phone_number;
}
}
}<file_sep>/FirebaseContactsServer/README.MD
# FirebaseContactsServer
This is a demo API REST built with firebase, in order to test API requests from the related FirebaseContactsApp ionic app
## Develop
This app is built with Typescript.
Your code changes must be compiled from Typescript to plain Javascript.
In order to do so, you can launch a process that keeps track of your TS files and compiles them when a change is detected. To do so, run:
```bash
cd functions
npm run ts-watch
```
## Upload to firebase
In order to upload new functions (or modifications) to firebase, run:
```bash
firebase use --add fir-contactsserver
firebase deploy --only-functions
```<file_sep>/FirebaseContactsApp/src/providers/index.ts
import { Api } from './api/api';
import { ContactsProvider } from './contacts/contacts';
export {
Api,
ContactsProvider
}<file_sep>/FirebaseContactsApp/src/providers/interceptors/ErrorInterceptor.ts
import 'rxjs/add/operator/do';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
export class ErrorInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do(event => {
if (event instanceof HttpResponse) {
if(event.status == 404){
throw(new Error("Not found"));
}
else{
return event;
}
}
})
.catch(err=>{
return Observable.throw(err);
})
}
}
<file_sep>/FirebaseContactsApp/src/providers/api/api.ts
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
/**
* Api is a generic REST Api handler. Set your API url first.
*/
@Injectable()
export class Api {
url: string = 'https://us-central1-fir-contactsserver.cloudfunctions.net';
constructor(public http: HttpClient) { }
get<T>(endpoint: string, queryParams: any, reqOpts?: any) {
console.log(queryParams);
if (!reqOpts) {
reqOpts = {
params: new HttpParams()
};
}
// Support easy query params for GET requests
if (queryParams) {
//HttpParams is inmutable
reqOpts.params = new HttpParams();
for (let k in queryParams) {
reqOpts.params = reqOpts.params.set(k, queryParams[k]);
}
}
return this.http.get<T>(this.url + '/' + endpoint, reqOpts);
}
post(endpoint: string, body: any, reqOpts?: any) {
return this.http.post(this.url + '/' + endpoint, body, reqOpts);
}
put(endpoint: string, body: any, reqOpts?: any) {
return this.http.put(this.url + '/' + endpoint, body, reqOpts);
}
delete(endpoint: string, reqOpts?: any) {
return this.http.delete(this.url + '/' + endpoint, reqOpts);
}
patch(endpoint: string, body: any, reqOpts?: any) {
return this.http.put(this.url + '/' + endpoint, body, reqOpts);
}
}
<file_sep>/FirebaseContactsServer/functions/src/index.ts
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
const cors = require('cors')({origin: true});
import { Contact, IContact } from './models';
import { ContactApi } from './api/contactApi';
//initialize FB realtime database
admin.initializeApp(functions.config().firebase);
/**
* API REST contact endpoint
* - GET: get list of contacts from FB database
* - POST: method to add a contact to the FB database
*
*/
exports.contact = functions.https.onRequest((req, res) => {
return cors(req, res, ()=>{
switch(req.method){
case 'POST':
return ContactApi.post(req, res);
case 'GET':
return ContactApi.get(req, res);
default:
return res.status(403).send('Method not allowed');
}
});
})
<file_sep>/FirebaseContactsApp/src/providers/contacts/contacts.ts
import { Injectable } from '@angular/core';
import { Api } from '../api/api';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/share';
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import { IContact } from '../../models/index';
import { Observable } from 'rxjs/Observable';
import { HttpParams } from '@angular/common/http';
/*
Generated class for the ContactsProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class ContactsProvider {
constructor(public api: Api) {
}
getContacts():Observable<IContact[]>{
const observable = this.api.get('contact',null)
.map(data => Object.keys(data).map(k => data[k]))
.catch(error => {
console.log("error here ", error);
return [];
})
.share()
observable.subscribe(items => {
return <IContact[]>items;
});
return observable;
}
addContact(contact:IContact){
return this.api.post('contact', {...contact}, new HttpParams().set('Content-Type', 'application/json'));
}
}
<file_sep>/FirebaseContactsServer/functions/src/models/index.ts
import { Contact, IContact } from './contact';
export {
Contact,
IContact
}<file_sep>/FirebaseContactsApp/src/pages/home/home.ts
import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import 'rxjs/add/operator/map';
import { IContact } from '../../models';
import { ContactsProvider } from '../../providers';
import { AddContactPage } from '../add-contact/add-contact';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public contacts:IContact[] = null;
constructor(
public navCtrl: NavController,
public contactsProvider: ContactsProvider,
public modalCtrl: ModalController
) { }
ionViewDidLoad(){
this.contactsProvider.getContacts()
.subscribe(items => {
this.contacts = items;
})
}
presentAddContactPage(){
let modal = this.modalCtrl.create(AddContactPage);
modal.present();
modal.onDidDismiss(()=>{
this.contactsProvider.getContacts().subscribe(items => {
this.contacts = items;
});
})
}
}
<file_sep>/FirebaseContactsApp/src/pages/add-contact/add-contact.ts
import { Component } from '@angular/core';
import { IonicPage, ViewController } from 'ionic-angular';
import { Contact } from '../../models';
import { ContactsProvider } from '../../providers/index';
/**
* AddContactPage. This view allows to create a new contact
* and upload it to the server
*
*/
@IonicPage()
@Component({
selector: 'page-add-contact',
templateUrl: 'add-contact.html',
})
export class AddContactPage {
public contact:Contact = new Contact();
constructor(
public contactsProvider: ContactsProvider,
public viewCtrl: ViewController ) {
}
ionViewDidLoad() {
}
addContact(){
this.contactsProvider.addContact(this.contact)
.subscribe(item=>{}, error => alert(error), ()=>{
this.viewCtrl.dismiss();
})
}
}
<file_sep>/FirebaseContactsServer/functions/src/api/contactApi.ts
import { Contact, IContact } from '../models';
import * as admin from 'firebase-admin';
export class ContactApi{
static post(req:any, res:any){
console.log(req.body);
let contact = new Contact(<IContact>req.body);
return admin.database().ref('/contacts').push(contact).then(snapshot=>{
return res.status(201).send({object:contact});
})
}
static get(req:any, res:any){
return admin.database().ref('/contacts').once('value').then(snapshot=>{
return res.status(201).send(snapshot.val());
});
}
}<file_sep>/FirebaseContactsApp/src/models/index.ts
import { Contact, IContact} from './contacts';
export {
Contact,
IContact
} | 92de11ad099a083f7969b90f82c4f047b4b68c53 | [
"Markdown",
"TypeScript"
]
| 12 | TypeScript | ionic-toolbox-work/IonicAdvancedWorkshop | a94a65df53c58af71959dfa11bbc65634b300759 | abd5ed93b107325ece97aa41f83c70d34f4cccb4 |
refs/heads/master | <repo_name>ayudhien/pydap.responses.wms<file_sep>/pydap/responses/wms/__init__.py
from __future__ import division
from StringIO import StringIO
import re
import operator
import bisect
from paste.request import construct_url, parse_dict_querystring
from paste.httpexceptions import HTTPBadRequest
from paste.util.converters import asbool
import numpy as np
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.cm import get_cmap
from matplotlib.colorbar import ColorbarBase
from matplotlib.colors import Normalize
from matplotlib import rcParams
rcParams['xtick.labelsize'] = 'small'
rcParams['ytick.labelsize'] = 'small'
import iso8601
import coards
try:
from PIL import Image
except:
PIL = None
from pydap.model import *
from pydap.responses.lib import BaseResponse
from pydap.util.template import GenshiRenderer, StringLoader, TemplateNotFound
from pydap.util.safeeval import expr_eval
from pydap.lib import walk, encode_atom
WMS_ARGUMENTS = ['request', 'bbox', 'cmap', 'layers', 'width', 'height', 'transparent', 'time']
DEFAULT_TEMPLATE = """<?xml version='1.0' encoding="UTF-8" standalone="no" ?>
<!DOCTYPE WMT_MS_Capabilities SYSTEM "http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd"
[
<!ELEMENT VendorSpecificCapabilities EMPTY>
]>
<WMT_MS_Capabilities version="1.1.1"
xmlns="http://www.opengis.net/wms"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xlink="http://www.w3.org/1999/xlink">
<Service>
<Name>${dataset.name}</Name>
<Title>WMS server for ${dataset.attributes.get('long_name', dataset.name)}</Title>
<OnlineResource xlink:href="$location"></OnlineResource>
</Service>
<Capability>
<Request>
<GetCapabilities>
<Format>application/vnd.ogc.wms_xml</Format>
<DCPType>
<HTTP>
<Get><OnlineResource xlink:href="$location"></OnlineResource></Get>
</HTTP>
</DCPType>
</GetCapabilities>
<GetMap>
<Format>image/png</Format>
<DCPType>
<HTTP>
<Get><OnlineResource xlink:href="$location"></OnlineResource></Get>
</HTTP>
</DCPType>
</GetMap>
</Request>
<Exception>
<Format>application/vnd.ogc.se_blank</Format>
</Exception>
<VendorSpecificCapabilities></VendorSpecificCapabilities>
<UserDefinedSymbolization SupportSLD="1" UserLayer="0" UserStyle="1" RemoteWFS="0"/>
<Layer>
<Title>WMS server for ${dataset.attributes.get('long_name', dataset.name)}</Title>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox minx="${lon_range[0]}" miny="${lat_range[0]}" maxx="${lon_range[1]}" maxy="${lat_range[1]}"></LatLonBoundingBox>
<BoundingBox CRS="EPSG:4326" minx="${lon_range[0]}" miny="${lat_range[0]}" maxx="${lon_range[1]}" maxy="${lat_range[1]}"/>
<Layer py:for="grid in layers">
<Name>${grid.name}</Name>
<Title>${grid.attributes.get('long_name', grid.name)}</Title>
<Abstract>${grid.attributes.get('history', '')}</Abstract>
<?python
import numpy as np
from pydap.responses.wms import get_lon, get_lat, get_time
lon = get_lon(grid, dataset)
lat = get_lat(grid, dataset)
time = get_time(grid, dataset)
minx, maxx = np.min(lon), np.max(lon)
miny, maxy = np.min(lat), np.max(lat)
?>
<LatLonBoundingBox minx="${minx}" miny="${miny}" maxx="${maxx}" maxy="${maxy}"></LatLonBoundingBox>
<BoundingBox CRS="EPSG:4326" minx="${minx}" miny="${miny}" maxx="${maxx}" maxy="${maxy}"/>
<Dimension py:if="time is not None" name="time" units="ISO8601"/>
<Extent py:if="time is not None" name="time" default="${time[0].isoformat()}/${time[-1].isoformat()}" nearestValue="0">${time[0].isoformat()}/${time[-1].isoformat()}</Extent>
</Layer>
</Layer>
</Capability>
</WMT_MS_Capabilities>"""
class WMSResponse(BaseResponse):
__description__ = "Web Map Service image"
renderer = GenshiRenderer(
options={}, loader=StringLoader( {'capabilities.xml': DEFAULT_TEMPLATE} ))
def __init__(self, dataset):
BaseResponse.__init__(self, dataset)
self.headers.append( ('Content-description', 'dods_wms') )
def __call__(self, environ, start_response):
# Create a Beaker cache dependent on the query string, since
# most (all?) pre-computed values will depend on the specific
# dataset. We strip all WMS related arguments since they don't
# affect the dataset.
query = parse_dict_querystring(environ)
try:
dap_query = ['%s=%s' % (k, query[k]) for k in query
if k.lower() not in WMS_ARGUMENTS]
dap_query = [pair.rstrip('=') for pair in dap_query]
dap_query.sort() # sort for uniqueness
dap_query = '&'.join(dap_query)
location = construct_url(environ,
with_query_string=True,
querystring=dap_query)
self.cache = environ['beaker.cache'].get_cache(
'pydap.responses.wms+' + location)
except KeyError:
self.cache = None
# Handle GetMap and GetCapabilities requests
type_ = query.get('REQUEST', 'GetMap')
if type_ == 'GetCapabilities':
self.serialize = self._get_capabilities(environ)
self.headers.append( ('Content-type', 'text/xml') )
self.headers.append( ('Access-Control-Allow-Origin', '*') )
elif type_ == 'GetMap':
self.serialize = self._get_map(environ)
self.headers.append( ('Content-type', 'image/png') )
elif type_ == 'GetColorbar':
self.serialize = self._get_colorbar(environ)
self.headers.append( ('Content-type', 'image/png') )
else:
raise HTTPBadRequest('Invalid REQUEST "%s"' % type_)
return BaseResponse.__call__(self, environ, start_response)
def _get_colorbar(self, environ):
w, h = 90, 300
query = parse_dict_querystring(environ)
dpi = float(environ.get('pydap.responses.wms.dpi', 80))
figsize = w/dpi, h/dpi
cmap = query.get('cmap', environ.get('pydap.responses.wms.cmap', 'jet'))
def serialize(dataset):
fix_map_attributes(dataset)
fig = Figure(figsize=figsize, dpi=dpi)
fig.figurePatch.set_alpha(0.0)
ax = fig.add_axes([0.05, 0.05, 0.45, 0.85])
ax.axesPatch.set_alpha(0.5)
# Plot requested grids.
layers = [layer for layer in query.get('LAYERS', '').split(',')
if layer] or [var.id for var in walk(dataset, GridType)]
layer = layers[0]
names = [dataset] + layer.split('.')
grid = reduce(operator.getitem, names)
actual_range = self._get_actual_range(grid)
norm = Normalize(vmin=actual_range[0], vmax=actual_range[1])
cb = ColorbarBase(ax, cmap=get_cmap(cmap), norm=norm,
orientation='vertical')
for tick in cb.ax.get_yticklabels():
tick.set_fontsize(14)
tick.set_color('white')
#tick.set_fontweight('bold')
# Save to buffer.
canvas = FigureCanvas(fig)
output = StringIO()
canvas.print_png(output)
if hasattr(dataset, 'close'): dataset.close()
return [ output.getvalue() ]
return serialize
def _get_actual_range(self, grid):
try:
actual_range = self.cache.get_value((grid.id, 'actual_range'))
except (KeyError, AttributeError):
try:
actual_range = grid.attributes['actual_range']
except KeyError:
data = fix_data(np.asarray(grid.array[:]), grid.attributes)
actual_range = np.min(data), np.max(data)
if self.cache:
self.cache.set_value((grid.id, 'actual_range'), actual_range)
return actual_range
def _get_map(self, environ):
# Calculate appropriate figure size.
query = parse_dict_querystring(environ)
dpi = float(environ.get('pydap.responses.wms.dpi', 80))
w = float(query.get('WIDTH', 256))
h = float(query.get('HEIGHT', 256))
time = query.get('TIME')
figsize = w/dpi, h/dpi
bbox = [float(v) for v in query.get('BBOX', '-180,-90,180,90').split(',')]
cmap = query.get('cmap', environ.get('pydap.responses.wms.cmap', 'jet'))
def serialize(dataset):
fix_map_attributes(dataset)
fig = Figure(figsize=figsize, dpi=dpi)
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
# Set transparent background; found through http://sparkplot.org/browser/sparkplot.py.
if asbool(query.get('TRANSPARENT', 'true')):
fig.figurePatch.set_alpha(0.0)
ax.axesPatch.set_alpha(0.0)
# Plot requested grids (or all if none requested).
layers = [layer for layer in query.get('LAYERS', '').split(',')
if layer] or [var.id for var in walk(dataset, GridType)]
for layer in layers:
names = [dataset] + layer.split('.')
grid = reduce(operator.getitem, names)
if is_valid(grid, dataset):
self._plot_grid(dataset, grid, time, bbox, (w, h), ax, cmap)
# Save to buffer.
ax.axis( [bbox[0], bbox[2], bbox[1], bbox[3]] )
ax.axis('off')
canvas = FigureCanvas(fig)
output = StringIO()
# Optionally convert to paletted png
paletted = asbool(environ.get('pydap.responses.wms.paletted', 'false'))
if paletted:
# Read image
buf, size = canvas.print_to_buffer()
im = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
# Find number of colors
colors = im.getcolors(256)
# Only convert if the number of colors is less than 256
if colors is not None:
ncolors = len(colors)
# Get alpha band
alpha = im.split()[-1]
# Convert to paletted image
im = im.convert("RGB")
im = im.convert("P", palette=Image.ADAPTIVE, colors=ncolors)
# Set all pixel values below ncolors to 1 and the rest to 0
mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)
# Paste the color of index ncolors and use alpha as a mask
im.paste(ncolors, mask)
# Truncate palette to actual size to save space
im.palette.palette = im.palette.palette[:3*(ncolors+1)]
im.save(output, 'png', optimize=False, transparency=ncolors)
else:
canvas.print_png(output)
else:
canvas.print_png(output)
if hasattr(dataset, 'close'): dataset.close()
return [ output.getvalue() ]
return serialize
def _plot_grid(self, dataset, grid, time, bbox, size, ax, cmap='jet'):
# Get actual data range for levels.
actual_range = self._get_actual_range(grid)
V = np.linspace(actual_range[0], actual_range[1], 10)
# Slice according to time request (WMS-T).
if time is not None:
values = np.array(get_time(grid, dataset))
l = np.zeros(len(values), bool) # get no data by default
tokens = time.split(',')
for token in tokens:
if '/' in token: # range
start, end = token.strip().split('/')
start = iso8601.parse_date(start, default_timezone=None)
end = iso8601.parse_date(end, default_timezone=None)
l[(values >= start) & (values <= end)] = True
else:
instant = iso8601.parse_date(token.strip().rstrip('Z'), default_timezone=None)
l[values == instant] = True
else:
l = None
# Plot the data over all the extension of the bbox.
# First we "rewind" the data window to the begining of the bbox:
lon = get_lon(grid, dataset)
cyclic = hasattr(lon, 'modulo')
lon = np.asarray(lon[:])
lat = np.asarray(get_lat(grid, dataset)[:])
while np.min(lon) > bbox[0]:
lon -= 360.0
# Now we plot the data window until the end of the bbox:
w, h = size
while np.min(lon) < bbox[2]:
# Retrieve only the data for the request bbox, and at the
# optimal resolution (avoiding oversampling).
if len(lon.shape) == 1:
i0, i1 = find_containing_bounds(lon, bbox[0], bbox[2])
j0, j1 = find_containing_bounds(lat, bbox[1], bbox[3])
istep = max(1, np.floor( (len(lon) * (bbox[2]-bbox[0])) / (w * abs(lon[-1]-lon[0])) ))
jstep = max(1, np.floor( (len(lat) * (bbox[3]-bbox[1])) / (h * abs(lat[-1]-lat[0])) ))
lons = lon[i0:i1:istep]
lats = lat[j0:j1:jstep]
data = np.asarray(grid.array[...,j0:j1:jstep,i0:i1:istep])
# Fix cyclic data.
if cyclic:
lons = np.ma.concatenate((lons, lon[0:1] + 360.0), 0)
data = np.ma.concatenate((
data, grid.array[...,j0:j1:jstep,0:1]), -1)
X, Y = np.meshgrid(lons, lats)
elif len(lon.shape) == 2:
i, j = np.arange(lon.shape[1]), np.arange(lon.shape[0])
I, J = np.meshgrid(i, j)
xcond = (lon >= bbox[0]) & (lon <= bbox[2])
ycond = (lat >= bbox[1]) & (lat <= bbox[3])
if not xcond.any() or not ycond.any():
lon += 360.0
continue
i0, i1 = np.min(I[xcond]), np.max(I[xcond])
j0, j1 = np.min(J[ycond]), np.max(J[ycond])
istep = max(1, int(np.floor( (lon.shape[1] * (bbox[2]-bbox[0])) / (w * abs(np.max(lon)-np.amin(lon))) )))
jstep = max(1, int(np.floor( (lon.shape[0] * (bbox[3]-bbox[1])) / (h * abs(np.max(lat)-np.amin(lat))) )))
X = lon[j0:j1:jstep,i0:i1:istep]
Y = lat[j0:j1:jstep,i0:i1:istep]
data = grid.array[...,j0:j1:jstep,i0:i1:istep]
# Plot data.
if data.shape:
# apply time slices
if l is not None:
data = np.asarray(data)[l]
# reduce dimensions and mask missing_values
data = fix_data(data, grid.attributes)
# plot
if data.any():
ax.contourf(X, Y, data, V, cmap=get_cmap(cmap))
lon += 360.0
def _get_capabilities(self, environ):
def serialize(dataset):
fix_map_attributes(dataset)
grids = [grid for grid in walk(dataset, GridType) if is_valid(grid, dataset)]
# Set global lon/lat ranges.
try:
lon_range = self.cache.get_value('lon_range')
except (KeyError, AttributeError):
try:
lon_range = dataset.attributes['NC_GLOBAL']['lon_range']
except KeyError:
lon_range = [np.inf, -np.inf]
for grid in grids:
lon = np.asarray(get_lon(grid, dataset)[:])
lon_range[0] = min(lon_range[0], np.min(lon))
lon_range[1] = max(lon_range[1], np.max(lon))
if self.cache:
self.cache.set_value('lon_range', lon_range)
try:
lat_range = self.cache.get_value('lat_range')
except (KeyError, AttributeError):
try:
lat_range = dataset.attributes['NC_GLOBAL']['lat_range']
except KeyError:
lat_range = [np.inf, -np.inf]
for grid in grids:
lat = np.asarray(get_lat(grid, dataset)[:])
lat_range[0] = min(lat_range[0], np.min(lat))
lat_range[1] = max(lat_range[1], np.max(lat))
if self.cache:
self.cache.set_value('lat_range', lat_range)
# Remove ``REQUEST=GetCapabilites`` from query string.
location = construct_url(environ, with_query_string=True)
base = location.split('REQUEST=')[0].rstrip('?&')
context = {
'dataset': dataset,
'location': base,
'layers': grids,
'lon_range': lon_range,
'lat_range': lat_range,
}
# Load the template using the specified renderer, or fallback to the
# default template since most of the people won't bother installing
# and/or creating a capabilities template -- this guarantees that the
# response will work out of the box.
try:
renderer = environ['pydap.renderer']
template = renderer.loader('capabilities.xml')
except (KeyError, TemplateNotFound):
renderer = self.renderer
template = renderer.loader('capabilities.xml')
output = renderer.render(template, context, output_format='text/xml')
if hasattr(dataset, 'close'): dataset.close()
return [output.encode('utf-8')]
return serialize
def is_valid(grid, dataset):
return (get_lon(grid, dataset) is not None and
get_lat(grid, dataset) is not None)
def get_lon(grid, dataset):
def check_attrs(var):
if (re.match('degrees?_e', var.attributes.get('units', ''), re.IGNORECASE) or
var.attributes.get('axis', '').lower() == 'x' or
var.attributes.get('standard_name', '') == 'longitude'):
return var
# check maps first
for dim in grid.maps.values():
if check_attrs(dim) is not None:
return dim
# check curvilinear grids
if hasattr(grid, 'coordinates'):
coords = grid.coordinates.split()
for coord in coords:
if coord in dataset and check_attrs(dataset[coord].array) is not None:
return dataset[coord].array
return None
def get_lat(grid, dataset):
def check_attrs(var):
if (re.match('degrees?_n', var.attributes.get('units', ''), re.IGNORECASE) or
var.attributes.get('axis', '').lower() == 'y' or
var.attributes.get('standard_name', '') == 'latitude'):
return var
# check maps first
for dim in grid.maps.values():
if check_attrs(dim) is not None:
return dim
# check curvilinear grids
if hasattr(grid, 'coordinates'):
coords = grid.coordinates.split()
for coord in coords:
if coord in dataset and check_attrs(dataset[coord].array) is not None:
return dataset[coord].array
return None
def get_time(grid, dataset):
for dim in grid.maps.values():
if ' since ' in dim.attributes.get('units', ''):
try:
return [coards.parse(value, dim.units) for value in np.asarray(dim)]
except:
pass
return None
def fix_data(data, attrs):
if 'missing_value' in attrs:
data = np.ma.masked_equal(data, attrs['missing_value'])
elif '_FillValue' in attrs:
data = np.ma.masked_equal(data, attrs['_FillValue'])
if attrs.get('scale_factor'): data *= attrs['scale_factor']
if attrs.get('add_offset'): data += attrs['add_offset']
while len(data.shape) > 2:
##data = data[0]
data = np.ma.mean(data, 0)
return data
def fix_map_attributes(dataset):
for grid in walk(dataset, GridType):
for map_ in grid.maps.values():
if not map_.attributes and map_.name in dataset:
map_.attributes = dataset[map_.name].attributes.copy()
def find_containing_bounds(axis, v0, v1):
"""
Find i0, i1 such that axis[i0:i1] is the minimal array with v0 and v1.
For example::
>>> from numpy import *
>>> a = arange(10)
>>> i0, i1 = find_containing_bounds(a, 1.5, 6.5)
>>> print a[i0:i1]
[1 2 3 4 5 6 7]
>>> i0, i1 = find_containing_bounds(a, 1, 6)
>>> print a[i0:i1]
[1 2 3 4 5 6]
>>> i0, i1 = find_containing_bounds(a, 4, 12)
>>> print a[i0:i1]
[4 5 6 7 8 9]
>>> i0, i1 = find_containing_bounds(a, 4.5, 12)
>>> print a[i0:i1]
[4 5 6 7 8 9]
>>> i0, i1 = find_containing_bounds(a, -4, 7)
>>> print a[i0:i1]
[0 1 2 3 4 5 6 7]
>>> i0, i1 = find_containing_bounds(a, -4, 12)
>>> print a[i0:i1]
[0 1 2 3 4 5 6 7 8 9]
>>> i0, i1 = find_containing_bounds(a, 12, 19)
>>> print a[i0:i1]
[]
It also works with decreasing axes::
>>> b = a[::-1]
>>> i0, i1 = find_containing_bounds(b, 1.5, 6.5)
>>> print b[i0:i1]
[7 6 5 4 3 2 1]
>>> i0, i1 = find_containing_bounds(b, 1, 6)
>>> print b[i0:i1]
[6 5 4 3 2 1]
>>> i0, i1 = find_containing_bounds(b, 4, 12)
>>> print b[i0:i1]
[9 8 7 6 5 4]
>>> i0, i1 = find_containing_bounds(b, 4.5, 12)
>>> print b[i0:i1]
[9 8 7 6 5 4]
>>> i0, i1 = find_containing_bounds(b, -4, 7)
>>> print b[i0:i1]
[7 6 5 4 3 2 1 0]
>>> i0, i1 = find_containing_bounds(b, -4, 12)
>>> print b[i0:i1]
[9 8 7 6 5 4 3 2 1 0]
>>> i0, i1 = find_containing_bounds(b, 12, 19)
>>> print b[i0:i1]
[]
"""
ascending = axis[1] > axis[0]
if not ascending: axis = axis[::-1]
i0 = i1 = len(axis)
for i, value in enumerate(axis):
if value > v0 and i0 == len(axis):
i0 = i-1
if not v1 > value and i1 == len(axis):
i1 = i+1
if not ascending: i0, i1 = len(axis)-i1, len(axis)-i0
return max(0, i0), min(len(axis), i1)
<file_sep>/pydap/responses/wms/prepare.py
import sys
import numpy
from pydap.handlers.netcdf import nc, var_attrs
from pydap.responses.wms import fix_data
def prepare_netcdf():
filename = sys.argv[1]
if nc.__module__ == 'pupynere':
raise Exception, "Pupynere cannot open netcdf files in append mode. Please install either PyNIO, netCDF4, Scientific.IO.NetCDF or pynetcdf."
f = nc(filename, 'a')
# set actual range
for name, var in f.variables.items():
if name in f.dimensions or hasattr(var, 'actual_range'): continue
data = fix_data(numpy.asarray(var[:]), var_attrs(var))
var.actual_range = numpy.amin(data), numpy.amax(data)
f.close()
| 47d56cd61436b930c36e522116c3359bb55c675f | [
"Python"
]
| 2 | Python | ayudhien/pydap.responses.wms | c30f348a27fc39c27195eb9f0de1f067ebbd6c37 | dbf4bbf08751fbfaec04b027a154920deeff83d9 |
refs/heads/main | <file_sep>'use strict'
import mascota from './estructuras.js'
const perros = [];
const gatos = []
perros.push(new mascota('perro', 'Chester', 'Golden retriever', '3 Meses', './imagenes/masculino.png'), new mascota('perro', 'Papi', 'Chihuahua', '4 Meses', './imagenes/masculino.png'), new mascota('perro', 'Rocky', 'Rottweiler', '5 Meses', './imagenes/masculino.png'), new mascota('perro', 'Pelusa', 'Bichón frisé', '1 Año', './imagenes/femenino.png'));
gatos.push(new mascota('gato', 'Matilde', 'British Shorthair', '6 Meses', './imagenes/femenino.png'), new mascota('gato', 'Pelusa', 'Birmano', '1 Año', './imagenes/femenino.png'), new mascota('gato', 'Kity', 'Bombay', '2 Meses', './imagenes/femenino.png'), new mascota('gato', 'Bombon', 'Gato Americano', '4 Meses', './imagenes/femenino.png'));
// Funciones para opacidad de botones
const dispararOpacidadGato = () => {
cat_boton.classList.remove('opacity_inactiva');
cat_boton.classList.add('.opacity_activa');
dog_boton.classList.remove('.opacity_activa')
dog_boton.classList.add('opacity_inactiva');
}
const dispararOpacidadPerro = () => {
cat_boton.classList.remove('.opacity_activa');
cat_boton.classList.add('opacity_inactiva');
dog_boton.classList.remove('opacity_inactiva');
dog_boton.classList.add('.opacity_activa');
}
const dibujarPerros = () =>{
// Mascotas 1
document.querySelector(".mascota1").setAttribute("src",`${imagenes_perros[0]}`)
document.querySelector(".mascota1").classList.remove('Matilde');
document.querySelector(".mascota1").classList.add('Chester');
// Mascotas 2
document.querySelector(".mascota2").setAttribute("src",`${imagenes_perros[1]}`)
document.querySelector(".mascota2").classList.remove('Pelusa');
document.querySelector(".mascota2").classList.add('Papi');
//Mascotas 3
document.querySelector(".mascota3").setAttribute("src",`${imagenes_perros[2]}`)
document.querySelector(".mascota3").classList.remove('Kity');
document.querySelector(".mascota3").classList.add('Rocky');
// Mascotas 4
document.querySelector(".mascota4").setAttribute("src",`${imagenes_perros[3]}`)
document.querySelector(".mascota4").classList.remove('Bombon');
document.querySelector(".mascota4").classList.add('Pelusa');
}
const dibujarGatos = () =>{
// Mascotas 1
document.querySelector(".mascota1").setAttribute("src",`${imagenes_gatos[0]}`)
document.querySelector(".mascota1").classList.remove('Chester');
document.querySelector(".mascota1").classList.add('Matilde');
// Mascotas 2
document.querySelector(".mascota2").setAttribute("src",`${imagenes_gatos[1]}`)
document.querySelector(".mascota2").classList.remove('Papi');
document.querySelector(".mascota2").classList.add('Pelusa');
// Mascotas 3
document.querySelector(".mascota3").setAttribute("src",`${imagenes_gatos[2]}`)
document.querySelector(".mascota3").classList.remove('Rocky');
document.querySelector(".mascota3").classList.add('Kity');
// Mascotas4
document.querySelector(".mascota4").setAttribute("src",`${imagenes_gatos[3]}`)
document.querySelector(".mascota4").classList.remove('Pelusa');
document.querySelector(".mascota4").classList.add('Bombon');
}
// Botones con opacity
const imagenes_perros = ['./imagenes/chester.svg', './imagenes/papi.svg', './imagenes/rocky.svg','./imagenes/pelusa.svg']
const imagenes_gatos = ['./imagenes/matilde.png', './imagenes/pelusa.png', './imagenes/kity.png', './imagenes/bombon.png'];
const dog_boton = document.querySelector('.dog_icon');
const cat_boton = document.querySelector('.cat_icon');
cat_boton.addEventListener("click", dispararOpacidadGato);
dog_boton.addEventListener("click", dispararOpacidadPerro);
const cards_perros = document.querySelector('#cards-perros');
cards_perros.addEventListener("click", dibujarPerros);
const cards_gatos = document.querySelector('#cards-gatos');
cards_gatos.addEventListener("click", dibujarGatos);
// let chester = document.querySelector('.mascota1');
// chester.addEventListener("click", ocultarSeccion);
let pruebas = [];
let imagenGrande;
const descripcionMascota = () => {
document.querySelector('.home-title-container').style.display = 'none';
document.querySelector('.main-container').style.display = 'none';
document.querySelector('.cards-mascotas').style.display = 'none';
document.querySelector('#footer-container').style.display = 'none';
const c = document.querySelector('#body')
c.innerHTML = `
<a class = 'back' href = "home.html">
<img src = './imagenes/atras.svg'>
</a>
<header class = "imagen-grande-mascota">
<img src = ${imagenGrande}>
</header>
<main class = 'mascota-container'>
<div class = "informacion-container">
<div class = "title-container">
<div>${pruebas[0].nombre}
</div>
<img src = ${pruebas[0].sexo}>
</div>
<div class = "icono-favoritos">
<img src = './imagenes/favoritos-circulo.png'>
</div>
</div>
<div class = "title-container-two">
<div class = 'raza-container'>
<img src = './imagenes/pergamino-1.svg'>
<div>
${pruebas[0].raza}
</div>
</div>
<div class = 'edad-container'>
<div>
<img src = './imagenes/mascota-peque.png'>
</div>
<div class = "title-container"> ${pruebas[0].edad}</div>
</div>
</div>
<div class = 'ubication-container'>
<img src = './imagenes/ubicacion.png'>
<div>4140 Parker Rd. Allentown, </br>
New Mexico 31134</div>
</div>
<div class = 'personalidades-container'>
<div class = 'personalidad-title'> Personalidad </div>
<div class = 'personalidades-img'>
<img src = './imagenes/cariñoso.png' style = "padding-right: 24px;">
<img src = './imagenes/inquieto.png' style = "padding-right: 24px;">
<img src = './imagenes/jugueton.png'>
</div>
</div>
<div class = 'description-container'>
<div> Historia de ${pruebas[0].nombre} </div>
<p> ${pruebas[0].nombre} es un ${pruebas[0].categoria} muy lindo y cariñoso, tiene 5 hermanitos más y por cuestiones de espacio y tiempo no podremos cuidar a todos, nuestra misión es encontrar la familia ideal para él y seguro que tú eres la persona indicada. </p>
</div>
<div class = 'contacto-description'>
<div class = 'persona-description'>
<img src = './imagenes/mifoto.jpg' width = '42px' height = '42px'>
<div>
<span class = 'publicado-por'>Publicado por </span>
<span class = 'name-publicacion'> <NAME> </span>
</div>
</div>
<button>
Contactar
</button>
</div>
</main>
`;
pruebas = [];
}
const mascotas1 = () => {
if(mascota1.classList.contains('Chester')){
pruebas.push(new mascota('perro', 'Chester', 'Golden retriever', '3 Meses', './imagenes/masculino.png'))
imagenGrande = './imagenes/rocky-grande.png';
descripcionMascota();
}
else if(mascota1.classList.contains('Matilde')){
pruebas.push(new mascota('gato', 'Matilde', 'British Shorthair', '6 Meses', './imagenes/femenino.png'))
imagenGrande = './imagenes/gato-grande.png'
descripcionMascota();
}
}
const mascotas2 = () => {
if(mascota2.classList.contains('Papi')){
pruebas.push(new mascota('perro', 'Papi', 'Chihuahua', '4 Meses', './imagenes/masculino.png'));
imagenGrande = './imagenes/rocky-grande.png';
descripcionMascota();
}
else if(mascota2.classList.contains('Pelusa')){
pruebas.push(new mascota('gato', 'Pelusa', 'Birmano', '1 Año', './imagenes/femenino.png'))
imagenGrande = './imagenes/gato-grande.png'
descripcionMascota();
}
}
const mascotas3 = () => {
if(mascota3.classList.contains('Rocky')){
pruebas.push(new mascota('perro', 'Rocky', 'Rottweiler', '5 Meses', './imagenes/masculino.png'));
imagenGrande = './imagenes/rocky-grande.png';
descripcionMascota();
}
else if(mascota3.classList.contains('Kity')){
pruebas.push(new mascota('gato', 'Kity', 'Bombay', '2 Meses', './imagenes/femenino.png'))
imagenGrande = './imagenes/gato-grande.png'
descripcionMascota();
}
}
const mascotas4 = () => {
if(mascota4.classList.contains('Pelusa')){
pruebas.push(new mascota('perro', 'Pelusa', 'Bichón frisé', '1 Año', './imagenes/femenino.png'));
imagenGrande = './imagenes/rocky-grande.png';
descripcionMascota();
}
else if(mascota4.classList.contains('Bombon')){
pruebas.push(new mascota('gato', 'Bombon', 'Gato Americano', '4 Meses', './imagenes/femenino.png'))
imagenGrande = './imagenes/gato-grande.png'
descripcionMascota();
}
}
let mascota1 = document.getElementById('mascota1');
mascota1.addEventListener("click", mascotas1);
let mascota2 = document.getElementById('mascota2');
mascota2.addEventListener("click", mascotas2 );
let mascota3 = document.getElementById('mascota3');
mascota3.addEventListener("click", mascotas3 );
let mascota4 = document.getElementById('mascota4');
mascota4.addEventListener("click", mascotas4 );
<file_sep># aplicacionAdopcion
Repositorio para el desarrollo de la aplicación de adopción
<file_sep>'use strict';
// Evento Load
setInterval(function () {
loadEvent();
}, 2000);
function loadEvent() {
document.getElementById('loader-event').classList.add('hide');
}
// Funciones a utilizar
// Funciones para quitar secciones
function ocultarSeccion() {
const ocultarOnePage = document.querySelector('.container-description');
ocultarOnePage.classList.add('hide');
const secondPage = document.querySelector('.container-description-second');
secondPage.classList.remove('hide');
}
// Evento de boton siguiente uno
const activarSecondPage = document.getElementById('container-description');
activarSecondPage.addEventListener("click", ocultarSeccion);
| 2b22e830ea0765e74f847a670264b429d0f7bd2d | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | ysnaldojlopez/adoptionApplication | 02694d5635e0eb7134be6c6ddc8bace7413c0ff4 | 44ae134ec0efe148a6808c2cb87bbef239202e43 |
refs/heads/main | <repo_name>JeeGajDev/Hands_on<file_sep>/README.md
# Hands_on
myp-3
myp-8
| 931590012d71a1b0d78292503883bf4eb37fee43 | [
"Markdown"
]
| 1 | Markdown | JeeGajDev/Hands_on | bbefce74983d650d8ea859e1449881e5617e7413 | b824c469d9a0499580b796ff5cca9144347e6f2d |
refs/heads/master | <file_sep>require 'net/http'
require 'uri'
require 'yaml'
module MintyRb
class Binder
def initialize file
@scope ||= "default"
@config = YAML.load_file(file)[@scope]
end
def bind identifier, options
options.each_pair do |key, value|
run identifier, key.to_s, value
end
end
private
def run identifier, key, value
http = Net::HTTP.new(@config['host'], @config['port'])
http.use_ssl = @config['use_ssl']
request = Net::HTTP::Put.new [
@config['path'],
URI.escape(identifier),
URI.escape(key),
URI.escape(value),
].join('/')
response = http.request(request)
if response.code == "200"
response.body
end
end
end
class Minter
def initialize file
@scope ||= "default"
@config = YAML.load_file(file)[@scope]
end
def mint
run
end
private
def run
uri = URI.parse(@config['host'])
response = Net::HTTP.post_form(uri, query)
if response.code == "200"
parse_identifier response.body
end
end
def query
{shoulder: @config['shoulder']}
end
def parse_identifier(body)
identifier = /id:\s+(\S+)/.match(body)[1]
if @config['elide_string']
identifier.sub!(@config['elide_string'], '')
end
identifier
end
end
end
if __FILE__ == $0
file = File.join File.dirname(File.dirname(__FILE__)),
'config',
'minter.yml'
m = MintyRb::Minter.new file
puts m.mint
end
<file_sep>minty-rb
========
Partial [Identity](https://wiki.ucop.edu/display/Curation/Identity)
client in Ruby (minting only).
This is based on [minty](https://github.com/cokernel/minty),
a PHP version of the same program, and directly extracted
from [Presence](https://github.com/uklibraries/presence).
This is geared toward the Identity service we are running at the
University of Kentucky Libraries. You might need to modify the
code if your Identity service does not present the same interface.
Installation
------------
Add the line
```ruby
gem "minty-rb", :git => "git://github.com/uklibraries/minty-rb.git"
```
to your Gemfile and run bundle install.
Example
-------
```ruby
require 'minty-rb'
m = MintyRb::Minter.new "path/to/minter.yml"
identifier = m.mint
```
Configuration
-------------
A sample configuration file is provided in config/minter.yml.example.
Settings:
* host: where is the Identity service located?
* shoulder: what prefix do you want to use for identifiers? (This must already exist.)
* elide_string: at the University of Kentucky, we use this to elide our namespace (16417)
from identifiers. If you use multiple namespaces for identifiers, you should leave this
set to false. Otherwise, set elide_string to an explicit string (such as "16417/") that
you would like to be removed from minted identifiers before returning them.
---
See LICENSE for terms.
| 225b4d782d8847121092dd8f8c10140c42313532 | [
"Markdown",
"Ruby"
]
| 2 | Ruby | uklibraries/minty-rb | 7b7a4d4f8ff141c6196cb76bc1eaa4e266f731ad | cd4dbccec90b7b208aae5ff286a989d0a4226d8f |
refs/heads/master | <repo_name>NateMS/fhnw-wodss-frontend<file_sep>/src/utils.ts
/**
* Looks whether the provided object contains the property.
*
* @param object
* @param property
*/
import { ToastMessage } from './actions/toast.actions';
import { Role } from './api/role';
import moment, { Moment } from 'moment';
import { DATE_FORMAT_STRING } from './constants';
import { Project } from './api/dto/project';
import { EmployeeModel } from './api/dto/employee.model';
export function hasProp(object: {}, property: string): boolean {
if (object == null) {
return false;
}
return object.hasOwnProperty(property);
}
/**
* Helper function to create toast message for API errors.
*
* @param title
* @param error
*/
export const getApiErrorToast: (title: string, error: Error) => ToastMessage = (title, error) => ({
title,
message: `${error}`,
});
/**
* Creates a toast just containing a message.
*
* @param message
*/
export const getToastMessage = (message: string): ToastMessage => ({
message,
});
/**
* Checks if user has one of the roles.
* @param roles
*/
export const hasRole = (...roles: Role[]) => (role: Role): boolean => {
return roles.indexOf(role) > -1;
};
/**
* Checks if user is administrator.
*/
export const hasAdminRole = hasRole(Role.ADMINISTRATOR);
/**
* Checks if user is project manager.
*/
export const hasProjectManagerRole = hasRole(Role.PROJECTMANAGER);
/**
* User is either administrator or project manager.
*/
export const hasPrivilegedRole = hasRole(Role.ADMINISTRATOR, Role.PROJECTMANAGER);
/**
* Formats the received dates the following way: end date - start date
* @param from
* @param to
*/
export const formatDateRange = (from: Moment, to: Moment): string => {
return `${from.format(DATE_FORMAT_STRING)} - ${to.format(DATE_FORMAT_STRING)}`;
};
/**
* Returns the number of days from a date range.
*
* @param from
* @param to
* @param includeEod - if set to true, considers the end date as a full day (+1)
*/
export const getDaysOfDateRange = (from: Moment, to: Moment, includeEod: boolean = false): number => {
return to.diff(from, 'days') + (includeEod ? 1 : 0);
};
/**
* Checks if a provided date is between two dates.
* @param start
* @param end
* @param date
*/
export const isBetweenDates = (start: Moment, end: Moment, date: Moment): boolean => {
return date.isSameOrAfter(start) && date.isSameOrBefore(end);
};
/**
* Returns a sequential list of days starting from a specific day.
* @param start
* @param numberOfDays
*/
export const createDateList = (start: Moment, numberOfDays: number): Moment[] => {
return Array.from(
Array(numberOfDays),
(_, index) => moment(start).add(index, 'days'),
);
};
/**
* Generates a deterministic random hex color.
*
* @param unique1
* @param unique2
*/
export const getRandomHexColor = (unique1: string, unique2?: string): string => {
let hash = 0;
const str = `${unique1}${unique2}`;
let colour = '#';
for (let i = 0; i < str.length; i = i + 1) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
for (let i = 0; i < 3; i = i + 1) {
const value = (hash >> (i * 8)) & 0xFF;
colour += `00${value.toString(16)}`.substr(-2);
}
return colour;
};
/**
* Compares project by name. Useful for sort functions
*
* @param p1
* @param p2
*/
export const compareProjectByName = (p1: Project, p2: Project): number => {
const name1 = p1.name.toUpperCase();
const name2 = p2.name.toUpperCase();
return (name1 < name2) ? -1 : (name1 > name2) ? 1 : 0;
};
/**
* Compares employees by name. Useful for sort functions
*
* @param p1
* @param p2
*/
export const compareEmployeeByName = (e1: EmployeeModel, e2: EmployeeModel): number => {
const name1 = e1.fullName.toUpperCase();
const name2 = e2.fullName.toUpperCase();
return (name1 < name2) ? -1 : (name1 > name2) ? 1 : 0;
};
<file_sep>/src/api/dto/employee.model.ts
import { Employee } from './employee';
import { Role, roleNameMap } from '../role';
import { EmployeeBaseModel } from './employee.base.model';
import { ContractModel } from './contract.model';
export class EmployeeModel extends EmployeeBaseModel {
public readonly id: string;
public readonly role: Role;
public get fullName(): string {
return `${this.firstName} ${this.lastName}`;
}
public get roleName(): string {
return roleNameMap[this.role];
}
constructor(employee: Employee) {
super(employee);
if (employee.id != null) {
this.id = employee.id;
} else {
throw new Error(`The field 'id' is missing.`);
}
if (employee.role != null) {
this.role = employee.role;
} else {
throw new Error(`The field 'role' is missing.`);
}
}
/**
* Filters a list of employees containing only employees that have contracts.
* @param employees
* @param contracts
*/
public static filterByContracts(employees: EmployeeModel[], contracts: ContractModel[]): EmployeeModel[] {
const employeeIdsWithContracts: Set<string> = new Set();
contracts.forEach((contract) => {
employeeIdsWithContracts.add(contract.employeeId);
});
return employees.filter(employee => employeeIdsWithContracts.has(employee.id));
}
}
<file_sep>/src/state/view/planning-view.state.ts
import moment, { Moment } from 'moment';
export interface PlanningViewState {
startDate: Moment;
granularity: number;
filterString: string;
}
export const defaultPlanningViewState: PlanningViewState = {
startDate: moment()
.startOf('day'),
granularity: 30,
filterString: '',
};
<file_sep>/src/api/dto/contract.ts
import { Moment } from 'moment';
/**
* Represents the contract an employee can have (Multiple contracts are possible, but date overlapping is not allowed)
* @export
* @interface Contract
*/
export interface Contract {
/**
* Contract ID
* @type {string}
* @memberof Contract
*/
id?: string;
/**
* Contract start date (YYYY-MM-DD)
* @type {string}
* @memberof Contract
*/
startDate: string | Moment;
/**
* Contract end date (YYYY-MM-DD)
* @type {string}
* @memberof Contract
*/
endDate: string | Moment;
/**
* Full time equivalent for the contract as percentage value (0.5 FTE = 50)
* @type {number}
* @memberof Contract
*/
pensumPercentage: number;
/**
* Employee ID of the contract
* @type {string}
* @memberof Contract
*/
employeeId: string;
}
<file_sep>/src/actions/view/index.ts
import { employeesViewActions, EmployeesViewActions } from './employees-view.actions';
import { ActionsType } from 'hyperapp';
import { ViewState } from '../../state/view';
import { projectsViewActions, ProjectsViewActions } from './projects-view.actions';
import { planningViewActions, PlanningViewActions } from './planning-view.actions';
export interface ViewActions {
employees: EmployeesViewActions;
projects: ProjectsViewActions;
planning: PlanningViewActions;
}
export const viewActions: ActionsType<ViewState, ViewActions> = {
employees: employeesViewActions,
projects: projectsViewActions,
planning: planningViewActions,
};
<file_sep>/src/actions/toast.actions.ts
import { ToastState } from '../state';
import { ActionResult, ActionsType } from 'hyperapp';
import { TOAST_DURATION } from '../constants';
enum ToastLevel {
Info = 'info',
Success = 'success',
Warn = 'warning',
Error = 'danger',
}
export interface ToastMessage {
message: string;
title?: string;
}
export interface Toast extends ToastMessage {
id: number;
type: ToastLevel;
}
export interface ToastActions {
info: (toast: ToastMessage) =>
(state: ToastState) =>
ActionResult<ToastState>;
success: (toast: ToastMessage) =>
(state: ToastState) =>
ActionResult<ToastState>;
warning: (toast: ToastMessage) =>
(state: ToastState) =>
ActionResult<ToastState>;
error: (toast: ToastMessage) =>
(state: ToastState) =>
ActionResult<ToastState>;
hide: (index?: number) => (state: ToastState) => ActionResult<ToastState>;
}
/**
* Adds the toasts and removes them after some time.
*
* @param toast
* @param state
* @param actions
*/
const addToast:
(toast: Toast, state: ToastState, actions: ToastActions) => ToastState =
(toast, state, actions) => {
if (toast.type !== ToastLevel.Error) {
setTimeout(
() => {
actions.hide(toast.id);
},
TOAST_DURATION,
);
}
return {
list: [toast, ...state.list],
};
};
const createToast = (message: string, title: string, type: ToastLevel): Toast => {
const id = +new Date();
return { id, message, title, type };
};
export const toastActions: ActionsType<ToastState, ToastActions> = {
info: ({ message, title }) => (state, actions) => {
const toast = createToast(message, title, ToastLevel.Info);
return addToast(toast, state, actions);
},
success: ({ message, title }) => (state, actions) => {
const toast = createToast(message, title, ToastLevel.Success);
return addToast(toast, state, actions);
},
warning: ({ message, title }) => (state, actions) => {
const toast = createToast(message, title, ToastLevel.Warn);
return addToast(toast, state, actions);
},
error: ({ message, title }) => (state, actions) => {
const toast = createToast(message, title, ToastLevel.Error);
return addToast(toast, state, actions);
},
hide: (id?: number) => ({ list }) => (
{ list: list.filter(t => t.id !== id) }
),
};
<file_sep>/src/api/dto/employee.ts
import { Role } from '../role';
/**
* Represents the employee of the FHNW.
* An employee can have several non-overlapping contracts.
* In addition he can work in multiple projects and act as project leader.
* @export
* @interface Employee
*/
export interface Employee {
/**
* Employee ID
* @type {string}
*/
id?: string;
/**
* @type {boolean}
*/
active?: boolean;
/**
* Employee first name
* @type {string}
*/
firstName: string;
/**
* Employee last name
* @type {string}
*/
lastName: string;
/**
* Employee email address
* @type {string}
*/
emailAddress: string;
/**
* Single employee role
* @type {string}
*/
role?: Role;
}
<file_sep>/src/api/dto/token-payload.ts
import { Employee } from './employee';
export interface TokenPayload {
employee: Employee;
sub?: string;
exp?: number;
iat?: number;
}
<file_sep>/src/api/dto/contract.request.model.ts
import { DATE_FORMAT_STRING } from '../../constants';
import { Contract } from './contract';
import { ContractModel } from './contract.model';
import { ContractBaseModel } from './contract.base.model';
export class ContractRequestModel implements Contract {
public readonly startDate: string;
public readonly endDate: string;
public readonly pensumPercentage: number;
public readonly employeeId: string;
constructor(contract: ContractBaseModel | ContractModel) {
if (contract.startDate != null) {
this.startDate = contract.startDate.format(DATE_FORMAT_STRING);
} else {
throw new Error(`'Start date' is missing`);
}
if (contract.endDate != null) {
this.endDate = contract.endDate.format(DATE_FORMAT_STRING);
} else {
throw new Error(`'End date' is missing`);
}
if (contract.pensumPercentage != null) {
this.pensumPercentage = +contract.pensumPercentage;
} else {
throw new Error(`'Pensum' is missing`);
}
if (contract.employeeId != null) {
this.employeeId = contract.employeeId;
} else {
throw new Error(`'Employee' is missing`);
}
}
}
<file_sep>/src/api/dto/contract.model.ts
import { Contract } from './contract';
import { ContractBaseModel } from './contract.base.model';
export class ContractModel extends ContractBaseModel {
public readonly id: string;
constructor(contract: Contract) {
super(contract);
if (contract.id != null) {
this.id = contract.id;
} else {
throw new Error(`The field 'id' is missing.`);
}
}
}
<file_sep>/src/actions/allocation.actions.ts
import { AllocationState } from '../state';
import { ActionResult, ActionsType } from 'hyperapp';
import { allocationService } from '../services/allocation.service';
import { AllocationModel } from '../api/dto/allocation.model';
import { AllocationRequestModel } from '../api/dto/allocation.request.model';
export interface AllocationActions {
setLoading: (isLoading: boolean) => (state: AllocationState) => ActionResult<AllocationState>;
fetchAll: () => (state: AllocationState, actions: AllocationActions) => Promise<AllocationModel[]>;
setList: (allocations: AllocationModel[]) => (state: AllocationState) => ActionResult<AllocationState>;
create: (allocation: AllocationRequestModel) => () => Promise<AllocationModel>;
update: (update: AllocationUpdateModel) => () => Promise<AllocationModel>;
delete: (id: string) => () => Promise<void>;
}
interface AllocationUpdateModel {
allocation: AllocationRequestModel;
id: string;
}
export const allocationActions: ActionsType<AllocationState, AllocationActions> = {
setLoading: isLoading => state => (
Object.assign({}, state, {
isLoading,
})
),
setList: allocations => state => (
Object.assign({}, state, {
list: [...allocations],
})
),
fetchAll: () => (_, actions) => {
actions.setLoading(true);
allocationService
.getAll()
.then((allocations) => {
actions.setLoading(false);
actions.setList(allocations);
return allocations;
});
},
create: (allocation: AllocationRequestModel) => () => {
return allocationService.create(allocation);
},
update: (update: AllocationUpdateModel) => () => {
const { allocation, id } = update;
return allocationService.update(allocation, id);
},
delete: (id: string) => () => {
return allocationService.delete(id);
},
};
<file_sep>/src/state/form/employee-form.state.ts
import { BaseForm, FormControl } from './types';
import { textRequiredValidator, emailValidator, selectValidator } from './validators';
export interface EmployeeFormState extends BaseForm {
controls: {
id: FormControl<string>;
firstName: FormControl<string>;
lastName: FormControl<string>;
emailAddress: FormControl<string>;
password: FormControl<string>;
role: FormControl<string>;
};
}
export const initEmployeeForm: () => EmployeeFormState = () => ({
isOpen: false,
isSaving: false,
controls: {
id: {
name: 'id',
value: null,
},
firstName: {
name: 'firstName',
value: null,
validators: [
textRequiredValidator,
],
},
lastName: {
name: 'lastName',
value: null,
validators: [
textRequiredValidator,
],
},
role: {
name: 'role',
value: null,
validators: [
selectValidator,
],
},
emailAddress: {
name: 'emailAddress',
value: null,
validators: [
textRequiredValidator,
emailValidator,
],
},
password: {
name: '<PASSWORD>',
value: null,
validators: [
textRequiredValidator,
],
},
},
});
<file_sep>/src/actions/form/index.ts
import { ActionResult, ActionsType } from 'hyperapp';
import { FormControl, BaseForm, ValidatorFunction } from '../../state/form/types';
import { hasProp } from '../../utils';
import { AuthenticationFormState } from '../../state/form/authentication-form.state';
import { EmployeeFormState } from '../../state/form/employee-form.state';
import { FormState } from '../../state/form';
import { employeeFormActions } from './employee-form.actions';
import { authenticationFormActions } from './authentication-form.actions';
import { ProjectFormState } from '../../state/form/project-form.state';
import { projectFormActions } from './project-form.actions';
import { contractFormActions, ContractFormActions } from './contract-form.actions';
import { AllocationFormState } from '../../state/form/allocation-form.state';
import { allocationFormActions } from './allocation-form.actions';
export interface GenericFormActions<S> {
patch: (newValues: {[key: string]: any}) => (state: S) => ActionResult<S>;
updateValue: (updatedControl: FormControl<any>) => (state: S) => ActionResult<S>;
reset: () => (state: S) => ActionResult<S>;
setSaving: (isSaving: boolean) => (state: S) => ActionResult<S>;
setOpen: (isOpen: boolean) => (state: S) => ActionResult<S>;
}
export const setSaving = (isSaving: boolean, state: BaseForm): BaseForm => ({
...state,
isSaving,
});
export const setOpen = (isOpen: boolean, state: BaseForm): BaseForm => ({
...state,
isOpen,
});
export const updateValue = (updatedControl: FormControl<any>, state: BaseForm): BaseForm => {
const { name } = updatedControl;
if (!hasProp(state.controls, name)) {
throw new Error(`There is no '${updatedControl.name}' in form available.`);
}
const currentControl = state.controls[name];
let errors = {};
let hasErrors = false;
if (hasProp(currentControl, 'validators')) {
// Validate control
currentControl
.validators
.forEach((validator: ValidatorFunction<any>) => {
errors = {
...errors,
...validator(updatedControl, state),
};
});
hasErrors = Object.keys(errors).length > 0;
}
return {
...state,
controls: {
...state.controls,
[updatedControl.name]: {
...state.controls[updatedControl.name],
errors: hasErrors ? errors : undefined,
value: updatedControl.value,
},
},
};
};
export const patch = (values: {[key: string]: any}, state: BaseForm): BaseForm => {
const newValues = { ...values };
Object
.keys(newValues)
.forEach((key) => {
newValues[key] = {
...state.controls[key],
value: newValues[key],
};
});
return {
...state,
controls: {
...state.controls,
...newValues,
},
};
};
export interface FormActions {
authentication: GenericFormActions<AuthenticationFormState>;
employee: GenericFormActions<EmployeeFormState>;
project: GenericFormActions<ProjectFormState>;
allocation: GenericFormActions<AllocationFormState>;
contract: ContractFormActions;
}
export const formActions: ActionsType<FormState, FormActions> = {
authentication: authenticationFormActions,
employee: employeeFormActions,
project: projectFormActions,
contract: contractFormActions,
allocation: allocationFormActions,
};
<file_sep>/src/components/FormControlProps.ts
import { FormControl } from '../state/form/types';
export interface FormControlProps<T> extends FormControl<T> {
onInputChange: (control: FormControl<T>) => void;
placeholder?: string;
disabled?: boolean;
isLoading?: boolean;
}
<file_sep>/src/actions/form/authentication-form.actions.ts
import { ActionsType } from 'hyperapp';
import {
AuthenticationFormState,
initAuthenticationForm,
} from '../../state/form/authentication-form.state';
import { GenericFormActions, patch, setSaving, updateValue } from './index';
export const authenticationFormActions: ActionsType<AuthenticationFormState, GenericFormActions<AuthenticationFormState>> = {
setSaving: isSaving => state => setSaving(isSaving, state),
setOpen: () => state => state,
patch: newValues => state => patch(newValues, state),
updateValue: control => state => updateValue(control, state),
reset: () => (state) => {
return Object.assign({}, state, initAuthenticationForm());
},
};
<file_sep>/src/actions/employee.actions.ts
import { EmployeeState } from '../state';
import { ActionResult, ActionsType } from 'hyperapp';
import { employeeService } from '../services/employee.service';
import { EmployeeModel } from '../api/dto/employee.model';
import { Role } from '../api/role';
import { EmployeeRequestModel } from '../api/dto/employee.request.model';
import { Actions } from './index';
import { getApiErrorToast, getToastMessage } from '../utils';
export interface EmployeeActions {
setLoading: (isLoading: boolean) => (state: EmployeeState) => ActionResult<EmployeeState>;
fetchAll: () => (state: EmployeeState, actions: EmployeeActions) => Promise<EmployeeModel[]>;
setList: (employees: EmployeeModel[]) => (state: EmployeeState) => ActionResult<EmployeeState>;
create: (create: EmployeeCreateModel) => () => Promise<EmployeeModel>;
update: (update: EmployeeUpdateModel) => () => Promise<EmployeeModel>;
delete: (id: string) => () => Promise<void>;
}
interface EmployeeCreateModel {
employee: EmployeeRequestModel;
password: string;
role: Role;
}
interface EmployeeUpdateModel {
employee: EmployeeRequestModel;
id: string;
}
export const employeeActions: ActionsType<EmployeeState, EmployeeActions> = {
setLoading: isLoading => state => (
Object.assign({}, state, {
isLoading,
})
),
setList: employees => state => (
Object.assign({}, state, {
list: [...employees],
})
),
fetchAll: () => (_, actions) => {
actions.setLoading(true);
employeeService
.getAll()
.then((employees) => {
actions.setLoading(false);
actions.setList(employees);
return employees;
});
},
create: (create: EmployeeCreateModel) => () => {
const { employee, password, role } = create;
return employeeService.create(employee, password, role);
},
update: (update: EmployeeUpdateModel) => () => {
const { employee, id } = update;
return employeeService.update(employee, id);
},
delete: (id: string) => () => {
return employeeService.delete(id);
},
};
export const deleteEmployee = (employee: EmployeeModel, actions: Actions) => {
actions
.employee
.delete(employee.id)
.then(() => {
actions.toast.success(getToastMessage(`Employee '${employee.fullName}' successfully deleted`));
actions.employee.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast(`Error deleting employee '${employee.fullName}'`, error));
});
};
<file_sep>/src/state/view/projects-view.state.ts
export interface ProjectsViewState {
filterString: string;
}
export const defaultProjectsViewState: ProjectsViewState = {
filterString: '',
};
<file_sep>/src/actions/form/project-form.actions.ts
import { ActionsType } from 'hyperapp';
import { GenericFormActions, patch, setOpen, setSaving, updateValue } from './index';
import { ProjectFormState, initProjectForm } from '../../state/form/project-form.state';
import { Actions } from '../index';
import { ProjectModel } from '../../api/dto/project.model';
import { getToastMessage, getApiErrorToast } from '../../utils';
import { ProjectRequestModel } from '../../api/dto/project.request.model';
export const projectFormActions: ActionsType<ProjectFormState, GenericFormActions<ProjectFormState>> = {
setSaving: isSaving => state => setSaving(isSaving, state),
patch: newValues => state => patch(newValues, state),
updateValue: control => state => updateValue(control, state),
reset: () => (state) => {
return Object.assign({}, state, initProjectForm());
},
setOpen: isOpen => state => setOpen(isOpen, state),
};
export const showProjectCreateForm = (show: boolean, actions: Actions): void => {
actions.form.project.reset();
actions.form.project.setOpen(show);
};
export const showProjectEditForm = (project: ProjectModel, actions: Actions): void => {
actions.form.project.patch({
...project,
});
actions.form.project.setOpen(true);
};
export const createProject = (state: ProjectFormState, actions: Actions) => {
const { name, ftePercentage, startDate, endDate, projectManagerId } = state.controls;
try {
const request = new ProjectRequestModel({
name: name.value!,
ftePercentage: ftePercentage.value!,
startDate: startDate.value!,
endDate: endDate.value!,
projectManagerId: projectManagerId.value!,
});
actions
.project
.create(request)
.then((project: ProjectModel) => {
actions.toast.success(getToastMessage(`Successfully created project '${project.name}'`));
actions.form.project.reset();
// Refresh underlying view
actions.project.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error creating project', error));
});
} catch (error) {
actions.toast.error(getApiErrorToast('Error creating project', error));
}
};
export const updateProject = (state: ProjectFormState, actions: Actions): void => {
const { id, name, ftePercentage, startDate, endDate, projectManagerId } = state.controls;
try {
const request = new ProjectRequestModel({
name: name.value!,
ftePercentage: ftePercentage.value!,
startDate: startDate.value!,
endDate: endDate.value!,
projectManagerId: projectManagerId.value!,
});
if (id.value == null) {
throw Error(`'ID' is missing`);
}
actions
.project
.update({ project: request, id: id.value })
.then((project: ProjectModel) => {
actions.toast.success(getToastMessage(`Successfully updated project '${project.name}'`));
actions.form.project.reset();
// Refresh underlying view
actions.project.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error updateing project', error));
});
} catch (error) {
actions.toast.error(getApiErrorToast('Error updateing project', error));
}
};
<file_sep>/src/state/form/index.ts
import { EmployeeFormState, initEmployeeForm } from './employee-form.state';
import { AuthenticationFormState, initAuthenticationForm } from './authentication-form.state';
import { initProjectForm, ProjectFormState } from './project-form.state';
import { ContractFormState, initContractFormState } from './contract-form.state';
import { AllocationFormState, initAllocationForm } from './allocation-form.state';
export interface FormState {
authentication: AuthenticationFormState;
employee: EmployeeFormState;
project: ProjectFormState;
contract: ContractFormState;
allocation: AllocationFormState;
[key: string]: any;
}
export const defaultFormState: FormState = {
authentication: initAuthenticationForm(),
employee: initEmployeeForm(),
project: initProjectForm(),
contract: initContractFormState(),
allocation: initAllocationForm(),
};
<file_sep>/src/actions/index.ts
import { userActions, UserActions } from './user.actions';
import { ActionsType } from 'hyperapp';
import { location, LocationActions } from '@hyperapp/router';
import { State } from '../state';
import { employeeActions, EmployeeActions } from './employee.actions';
import { toastActions, ToastActions } from './toast.actions';
import { formActions, FormActions } from './form';
import { ProjectActions, projectActions } from './project.actions';
import { AllocationActions, allocationActions } from './allocation.actions';
import { contractActions, ContractActions } from './contract.actions';
import { viewActions, ViewActions } from './view';
export interface Actions {
location: LocationActions;
user: UserActions;
form: FormActions;
view: ViewActions;
employee: EmployeeActions;
project: ProjectActions;
allocation: AllocationActions;
contract: ContractActions;
toast: ToastActions;
}
export const actions: ActionsType<State, Actions> = {
location: location.actions,
user: userActions,
form: formActions,
view: viewActions,
employee: employeeActions,
project: projectActions,
allocation: allocationActions,
contract: contractActions,
toast: toastActions,
};
<file_sep>/src/state/view/index.ts
import { defaultEmployeesViewState, EmployeesViewState } from './employees-view.state';
import { defaultProjectsViewState, ProjectsViewState } from './projects-view.state';
import { defaultPlanningViewState, PlanningViewState } from './planning-view.state';
export interface ViewState {
employees: EmployeesViewState;
projects: ProjectsViewState;
planning: PlanningViewState;
}
export const defaultViewState: ViewState = {
employees: defaultEmployeesViewState,
projects: defaultProjectsViewState,
planning: defaultPlanningViewState,
};
<file_sep>/src/api/dto/employee.request.model.ts
import { Employee } from './employee';
import { EmployeeModel } from './employee.model';
import { EmployeeBaseModel } from './employee.base.model';
export class EmployeeRequestModel implements Employee {
public readonly active?: boolean | undefined;
public readonly firstName: string;
public readonly lastName: string;
public readonly emailAddress: string;
constructor(employee: EmployeeBaseModel | EmployeeModel) {
this.active = employee.active;
if (employee.firstName != null) {
this.firstName = employee.firstName;
} else {
throw new Error(`'First name' is missing`);
}
if (employee.lastName != null) {
this.lastName = employee.lastName;
} else {
throw new Error(`'Last name' is missing`);
}
if (employee.emailAddress != null) {
this.emailAddress = employee.emailAddress;
} else {
throw new Error(`'Email address' is missing`);
}
}
}
<file_sep>/src/services/api.service.ts
import { ApiError } from '../api/api-error';
import { ResponseStatusCode } from '../api/response-status-code.enum';
import { userService } from './user.service';
import { ServiceError } from './service-error';
enum RequestMethods {
GET = 'GET',
PUT = 'PUT',
POST = 'POST',
DELETE = 'DELETE',
}
interface ConfigurationParameters {
apiKey?: string | ((name: string) => string);
basePath?: string;
}
type URLParams = {[key: string]: string | number | undefined};
class Configuration {
/**
* parameter for apiKey security
* @param name security name
* @memberof Configuration
*/
apiKey?: string | ((name: string) => string);
/**
* override base path
*
* @type {string}
* @memberof Configuration
*/
basePath?: string;
constructor(param: ConfigurationParameters = {}) {
this.apiKey = param.apiKey;
this.basePath = param.basePath;
}
}
export class ApiService {
private static instance: ApiService;
protected constructor(private configuration: Configuration) {}
public post<T>(url: string, body: any, queryParams?: URLParams): Promise<T> {
return this.request(RequestMethods.POST, url, body, queryParams);
}
public put<T>(url: string, body: any, queryParams?: URLParams): Promise<T> {
return this.request(RequestMethods.PUT, url, body, queryParams);
}
public get<T>(url: string, queryParams?: URLParams): Promise<T> {
return this.request(RequestMethods.GET, url, undefined, queryParams);
}
public delete<T>(url: string): Promise<T> {
return this.request(RequestMethods.DELETE, url);
}
public request<T>(method: string, endpoint: string, body?: any, queryParams?: URLParams): Promise<T> {
const { basePath } = this.configuration;
const url = new URL(`${basePath}${endpoint}`);
const token = userService.getToken();
let authorizationHeaders;
if (token != null) {
authorizationHeaders = {
Authorization: `Bearer ${token}`,
};
}
if (queryParams != null) {
Object
.keys(queryParams)
.filter(key => queryParams[key] != null)
.map((key) => {
url.searchParams.append(key, `${queryParams[key]!}`);
});
}
return fetch(url.toString(), {
method,
body: JSON.stringify(body),
headers: {
...authorizationHeaders,
'Content-Type': 'application/json',
},
mode: 'cors',
credentials: 'same-origin',
})
.then((response: Response) => {
if (!response.ok) {
throw new ApiError(response.status, response.statusText);
}
if (response.status === ResponseStatusCode.NoContent) {
return Promise.resolve();
}
return response
.json()
.then(body => body as T);
})
.catch((error: Error) => {
if (error instanceof ApiError) {
throw error;
}
throw new ApiError(ResponseStatusCode.NetworkError, error.message);
});
}
public static getInstance(): ApiService {
if (!ApiService.instance) {
ApiService.instance = new ApiService({
basePath: process.env.BACKEND_URL,
});
}
return ApiService.instance;
}
public static checkDefaultResponseStatus(error: ApiError): void {
if (error.status === ResponseStatusCode.Unauthorized) {
throw new ServiceError('Unauthenticated or invalid token');
}
if (error.status === ResponseStatusCode.InternalServerError) {
throw new ServiceError('Internal server error');
}
if (error.status === ResponseStatusCode.NetworkError) {
throw new ServiceError('Error contacting server');
}
}
}
export const apiService = ApiService.getInstance();
export default apiService;
<file_sep>/src/actions/view/employees-view.actions.ts
import { EmployeesViewState } from '../../state/view/employees-view.state';
import { ActionResult, ActionsType } from 'hyperapp';
export interface EmployeesViewActions {
updateFilterString: (filterString: string) => (state: EmployeesViewState) => ActionResult<EmployeesViewState>;
}
export const employeesViewActions: ActionsType<EmployeesViewState, EmployeesViewActions> = {
updateFilterString: filterString => () => ({
filterString,
}),
};
<file_sep>/src/api/dto/contract.base.model.ts
import { Contract } from './contract';
import moment from 'moment';
export class ContractBaseModel implements Contract {
public readonly startDate: moment.Moment;
public readonly endDate: moment.Moment;
public readonly pensumPercentage: number;
public readonly employeeId: string;
constructor(contract: Contract) {
if (contract.startDate != null) {
this.startDate = moment(contract.startDate);
} else {
throw new Error(`The field 'startDate' is missing.`);
}
if (contract.endDate != null) {
this.endDate = moment(contract.endDate);
} else {
throw new Error(`The field 'endDate' is missing.`);
}
if (contract.pensumPercentage != null) {
this.pensumPercentage = +contract.pensumPercentage;
} else {
throw new Error(`The field 'pensumPercentage' is missing.`);
}
if (contract.employeeId != null) {
this.employeeId = contract.employeeId;
} else {
throw new Error(`The field 'employeeId' is missing.`);
}
}
}
<file_sep>/src/api/dto/project.request.model.ts
import { DATE_FORMAT_STRING } from '../../constants';
import { Project } from './project';
import { ProjectModel } from './project.model';
import { ProjectBaseModel } from './project.base.model';
export class ProjectRequestModel implements Project {
name: string;
ftePercentage: number;
startDate: string;
endDate: string;
projectManagerId: string;
constructor(project: ProjectBaseModel | ProjectModel) {
if (project.name) {
this.name = project.name;
} else {
throw new Error(`'Name' is missing`);
}
if (project.ftePercentage) {
this.ftePercentage = project.ftePercentage;
} else {
throw new Error(`'FTE' is missing`);
}
if (project.startDate) {
this.startDate = project.startDate.format(DATE_FORMAT_STRING);
} else {
throw new Error(`'Start date' is missing`);
}
if (project.endDate) {
this.endDate = project.endDate.format(DATE_FORMAT_STRING);
} else {
throw new Error(`'End date' is missing`);
}
if (project.projectManagerId) {
this.projectManagerId = project.projectManagerId;
} else {
throw new Error(`'Project Manager' is missing`);
}
}
}
<file_sep>/src/models/employee-extended.model.ts
import { EmployeeModel } from '../api/dto/employee.model';
import { Employee } from '../api/dto/employee';
import { ProjectExtendedModel } from './project-extended.model';
export class EmployeeExtendedModel extends EmployeeModel {
public readonly projects: ProjectExtendedModel[];
constructor(employee: Employee, projects: ProjectExtendedModel[]) {
super(employee);
this.projects = projects;
}
}
<file_sep>/src/services/employee.service.ts
import { apiService, ApiService } from './api.service';
import { Employee } from '../api/dto/employee';
import { EmployeeModel } from '../api/dto/employee.model';
import { EmployeeRequestModel } from '../api/dto/employee.request.model';
import { Role } from '../api/role';
import { Contract } from '../api/dto/contract';
import { ContractModel } from '../api/dto/contract.model';
import { ContractRequestModel } from '../api/dto/contract.request.model';
import { ServiceError } from './service-error';
import { ResponseStatusCode } from '../api/response-status-code.enum';
class EmployeeService {
private static instance: EmployeeService;
private constructor(private api: ApiService) {}
public create(employee: EmployeeRequestModel, password: string, role: Role): Promise<EmployeeModel> {
const params = {
password,
role,
};
return this.api.post<Employee>('/api/employee', employee, params)
.then((response: Employee) => new EmployeeModel(response))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for creating employee failed');
}
throw error;
});
}
public getAll(role?: Role): Promise<EmployeeModel[]> {
const params = {
role,
};
return this.api.get<Employee[]>('/api/employee', params)
.then((list: Employee[]) => list.map(e => new EmployeeModel(e)))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
throw error;
});
}
public get(id: string): Promise<EmployeeModel> {
return this.api.get<Employee>(`/api/employee/${id}`)
.then((response: Employee) => new EmployeeModel(response))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Employee not found');
}
throw error;
});
}
public update(employee: EmployeeRequestModel, id: string): Promise<EmployeeModel> {
return this.api.put<Employee>(`/api/employee/${id}`, employee)
.then((response: Employee) => new EmployeeModel(response))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to update employees');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Employee not found');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for updateing employee failed');
}
throw error;
});
}
public delete(id: string): Promise<void> {
return this.api.delete<void>(`/api/employee/${id}`)
.then(() => {})
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to delete employees');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Employee not found');
}
throw error;
});
}
public createContract(contract: ContractRequestModel): Promise<ContractModel> {
return this.api.post<Contract>('/api/contract', contract)
.then((response: Contract) => new ContractModel(response))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to create contracts');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Contract not found');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for creating contract failed');
}
throw error;
});
}
public updateContract(contract: ContractRequestModel, id: string): Promise<ContractModel> {
return this.api.put<Contract>(`/api/contract/${id}`, contract)
.then((response: Contract) => new ContractModel(response))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to update contracts');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Contract not found');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for updateing contract failed');
}
throw error;
});
}
public deleteContract(id: string): Promise<void> {
return this.api.delete<void>(`/api/contract/${id}`)
.then(() => {})
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to delete contracts');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Contract not found');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for deleting contract failed');
}
throw error;
});
}
public getAllContracts(fromDate?: string, toDate?: string): Promise<ContractModel[]> {
const params = {
fromDate,
toDate,
};
return this.api.get<ContractModel[]>('/api/contract', params)
.then((list: Contract[]) => list.map(e => new ContractModel(e)))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
throw error;
});
}
public getContract(id: string): Promise<ContractModel> {
return this.api.get<ContractModel>(`/api/contract/${id}`)
.then(e => new ContractModel(e))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to view contract');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Contract not found');
}
throw error;
});
}
public filterListByRole(employees: EmployeeModel[] | null, role: Role): EmployeeModel[] {
return (null === employees) ? [] : employees.filter(e => e.role === role);
}
public static getInstance(): EmployeeService {
if (!EmployeeService.instance) {
EmployeeService.instance = new EmployeeService(apiService);
}
return EmployeeService.instance;
}
}
export const employeeService = EmployeeService.getInstance();
export default employeeService;
<file_sep>/src/models/project-extended.model.ts
import { ProjectModel } from '../api/dto/project.model';
import { Project } from '../api/dto/project';
import { AllocationExtendedModel } from './allocation-extended.model';
import { Moment } from 'moment';
import { isBetweenDates } from '../utils';
export class ProjectExtendedModel extends ProjectModel {
public readonly allocations: AllocationExtendedModel[];
constructor(project: Project, allocations: AllocationExtendedModel[]) {
super(project);
this.allocations = allocations;
}
public getAllocationByDate(date: Moment): AllocationExtendedModel | undefined {
let i = 0;
const numberOfAllocations = this.allocations.length;
while (i < numberOfAllocations) {
const { startDate, endDate } = this.allocations[i];
if (isBetweenDates(startDate, endDate, date)) {
return this.allocations[i];
}
i = i + 1;
}
return;
}
}
<file_sep>/src/api/dto/credentials.ts
/**
* Represents the credentials of employee with an email address
* and a raw password (Based on these information a JWT token is then issued)
* @export
* @interface Credentials
*/
export interface Credentials {
/**
* Employee email address
* @type {string}
*/
emailAddress: string;
/**
* Raw employee password
* @type {string}
*/
rawPassword: string;
}
<file_sep>/src/api/dto/employee.base.model.ts
import { Employee } from './employee';
export class EmployeeBaseModel implements Employee {
public readonly active?: boolean | undefined;
public readonly firstName: string;
public readonly lastName: string;
public readonly emailAddress: string;
constructor(employee: Employee) {
this.active = employee.active;
if (employee.firstName != null) {
this.firstName = employee.firstName;
} else {
throw new Error(`The field 'firstName' is missing.`);
}
if (employee.lastName != null) {
this.lastName = employee.lastName;
} else {
throw new Error(`The field 'lastName' is missing.`);
}
if (employee.emailAddress != null) {
this.emailAddress = employee.emailAddress;
} else {
throw new Error(`The field 'emailAddress' is missing.`);
}
}
}
<file_sep>/src/actions/view/planning-view.actions.ts
import { ActionResult, ActionsType } from 'hyperapp';
import { PlanningViewState } from '../../state/view/planning-view.state';
import moment, { Moment } from 'moment';
import { EmployeesViewState } from '../../state/view/employees-view.state';
export interface PlanningViewActions {
changeStartDate: (startDate: Moment) => (state: PlanningViewState) => ActionResult<PlanningViewState>;
updateFilterString: (filterString: string) => (state: EmployeesViewState) => ActionResult<EmployeesViewState>;
}
export const planningViewActions: ActionsType<PlanningViewState, PlanningViewActions> = {
changeStartDate: startDate => state => ({
...state,
startDate: startDate.startOf('day'),
}),
updateFilterString: filterString => () => ({
filterString,
}),
};
export const showPrevious = (startDate: Moment, numberOfDays: number, actions: PlanningViewActions): void => {
actions.changeStartDate(
moment(startDate)
.subtract(numberOfDays, 'days'),
);
};
export const showNext = (startDate: Moment, numberOfDays: number, actions: PlanningViewActions): void => {
actions.changeStartDate(
moment(startDate)
.add(numberOfDays, 'days'),
);
};
<file_sep>/src/views/ViewProps.ts
import { State } from '../state';
import { Actions } from '../actions';
export interface ViewProps {
state: State;
actions: Actions;
}
<file_sep>/src/api/dto/allocation.ts
import { Moment } from 'moment';
/**
* Represents the work unit an employee is doing for a project
* @export
* @interface Allocation
*/
export interface Allocation {
/**
* Allocation ID
* @type {string}
* @memberof Allocation
*/
id?: string;
/**
* Allocation start date (YYYY-MM-DD)
* @type {string}
* @memberof Allocation
*/
startDate: string | Moment;
/**
* Allocation end date (YYYY-MM-DD)
* @type {string}
* @memberof Allocation
*/
endDate: string | Moment;
/**
* Full time equivalent for the contract as percentage value (0.5 FTE = 50)
* @type {number}
* @memberof Allocation
*/
pensumPercentage: number;
/**
* Contract ID of the allocation
* @type {string}
* @memberof Allocation
*/
contractId: string;
/**
* Project ID of the allocation
* @type {string}
* @memberof Allocation
*/
projectId: string;
}
<file_sep>/src/state/index.ts
import { location, LocationState } from '@hyperapp/router';
import { defaultFormState, FormState } from './form/index';
import { EmployeeModel } from '../api/dto/employee.model';
import { Toast } from '../actions/toast.actions';
import { ProjectModel } from '../api/dto/project.model';
import { AllocationModel } from '../api/dto/allocation.model';
import { ContractModel } from '../api/dto/contract.model';
import { defaultViewState, ViewState } from './view';
export interface ToastState {
list: Toast[];
}
export interface ContractState {
list: ContractModel[];
isLoading: boolean;
}
export interface EmployeeState {
list: EmployeeModel[];
isLoading: boolean;
}
export interface ProjectState {
list: ProjectModel[];
isLoading: boolean;
}
export interface AllocationState {
list: AllocationModel[];
isLoading: boolean;
}
export interface ContractState {
list: ContractModel[];
isLoading: boolean;
}
export interface UserState {
authenticated: boolean | null;
token: string | null;
employee: EmployeeModel | null;
}
export interface State {
location: LocationState;
user: UserState;
form: FormState;
employee: EmployeeState;
project: ProjectState;
allocation: AllocationState;
contract: ContractState;
toast: ToastState;
view: ViewState;
}
export const state: State = {
location: location.state,
user: {
token: null,
authenticated: null,
employee: null,
},
employee: {
list: [],
isLoading: false,
},
project: {
list: [],
isLoading: false,
},
allocation: {
list: [],
isLoading: false,
},
contract: {
list: [],
isLoading: false,
},
form: defaultFormState,
view: defaultViewState,
toast: {
list: [],
},
};
<file_sep>/src/actions/project.actions.ts
import { ProjectState } from '../state';
import { ActionResult, ActionsType } from 'hyperapp';
import { projectService } from '../services/project.service';
import { ProjectModel } from '../api/dto/project.model';
import { ProjectRequestModel } from '../api/dto/project.request.model';
import { Actions } from './index';
import { getApiErrorToast, getToastMessage } from '../utils';
export interface ProjectActions {
setLoading: (isLoading: boolean) => (state: ProjectState) => ActionResult<ProjectState>;
fetchAll: () => (state: ProjectState, actions: ProjectActions) => Promise<ProjectModel[]>;
setList: (projects: ProjectModel[]) => (state: ProjectState) => ActionResult<ProjectState>;
create: (project: ProjectRequestModel) => () => Promise<ProjectModel>;
update: (update: ProjectUpdateModel) => () => Promise<ProjectModel>;
delete: (id: string) => () => Promise<void>;
}
interface ProjectUpdateModel {
project: ProjectRequestModel;
id: string;
}
export const projectActions: ActionsType<ProjectState, ProjectActions> = {
setLoading: isLoading => state => (
Object.assign({}, state, {
isLoading,
})
),
setList: projects => state => (
Object.assign({}, state, {
list: [...projects],
})
),
fetchAll: () => (_, actions) => {
actions.setLoading(true);
projectService
.getAll()
.then((projects) => {
actions.setLoading(false);
actions.setList(projects);
return projects;
});
},
create: (project: ProjectRequestModel) => () => {
return projectService
.create(project)
.then((project: ProjectModel) => {
return project;
});
},
update: (update: ProjectUpdateModel) => () => {
const { project, id } = update;
return projectService
.update(project, id)
.then((project: ProjectModel) => {
return project;
});
},
delete: (id: string) => () => {
return projectService.delete(id);
},
};
export const deleteProject = (project: ProjectModel, actions: Actions): void => {
actions.project
.delete(project.id)
.then(() => {
actions.toast.success(getToastMessage(`Project '${project.name}' successfully deleted`));
actions.project.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast(`Error deleting project: '${project.name}'`, error));
});
};
<file_sep>/src/constants.ts
/**
* Shows a toast for 4 seconds
*/
export const TOAST_DURATION = 4000;
/**
* Default date format of API
*/
export const DATE_FORMAT_STRING = 'YYYY-MM-DD';
/**
* Key name in the local storage, where the token is saved.
*/
export const LOCAL_STORAGE_USER_TOKEN = 'user';
/**
* Maximum allowed input length for short strings
*/
export const INPUT_LENGTH_SHORT_MAX = 50;
/**
* Maximum allowed input length for long strings
*/
export const INPUT_LENGTH_LONG_MAX = 120;
/**
* Minimum allowed pensum for a contract
*/
export const CONTRACT_PENSUM_VALUE_MIN = 1;
/**
* Maximum allowed pensum for a contract
*/
export const CONTRACT_PENSUM_VALUE_MAX = 100;
/**
* Minimum allowed FTE for a project
*/
export const PROJECT_FTE_VALUE_MIN = 1;
/**
* Maximum allowed FTE for a project
*/
export const PROJECT_FTE_VALUE_MAX = 9223372036854775807;
<file_sep>/src/api/role.ts
/**
* Enumeration of the possible roles an employee can have.
* @export
* @enum {string}
*/
export enum Role {
ADMINISTRATOR = 'ADMINISTRATOR',
PROJECTMANAGER = 'PROJECTMANAGER',
DEVELOPER = 'DEVELOPER',
}
export const roleNameMap: {[key in Role]: string} = Object.freeze({
[Role.ADMINISTRATOR]: 'Administrator',
[Role.PROJECTMANAGER]: 'Project Manager',
[Role.DEVELOPER]: 'Developer',
});
export const roleList: ReadonlyArray<Role> = Object.freeze(
Object
.keys(roleNameMap)
.map(r => (r as Role)),
);
<file_sep>/src/state/form/project-form.state.ts
import { Moment } from 'moment';
import { BaseForm, FormControl } from './types';
import { selectValidator, textRequiredValidator, durationValidator } from './validators';
export interface ProjectFormState extends BaseForm {
controls: {
id: FormControl<string>;
name: FormControl<string>;
ftePercentage: FormControl<number>;
startDate: FormControl<Moment>;
endDate: FormControl<Moment>;
projectManagerId: FormControl<string>;
};
}
export const initProjectForm: () => ProjectFormState = () => ({
isOpen: false,
isSaving: false,
controls: {
id: {
name: 'id',
value: null,
},
name: {
name: 'name',
value: null,
validators: [
textRequiredValidator,
],
},
ftePercentage: {
name: 'ftePercentage',
value: null,
},
startDate: {
name: 'startDate',
value: null,
validators: [
durationValidator,
],
},
endDate: {
name: 'endDate',
value: null,
validators: [
durationValidator,
],
},
projectManagerId: {
name: 'projectManagerId',
value: null,
validators: [
selectValidator,
],
},
},
});
<file_sep>/src/actions/contract.actions.ts
import { ContractState } from '../state';
import { ActionResult, ActionsType } from 'hyperapp';
import { employeeService } from '../services/employee.service';
import { ContractModel } from '../api/dto/contract.model';
import { ContractRequestModel } from '../api/dto/contract.request.model';
export interface ContractActions {
setLoading: (isLoading: boolean) => (state: ContractState) => ActionResult<ContractState>;
fetchAll: () => (state: ContractState, actions: ContractActions) => Promise<ContractModel[]>;
setList: (employees: ContractModel[]) => (state: ContractState) => ActionResult<ContractState>;
create: (contract: ContractRequestModel) => () => Promise<ContractModel>;
update: (update: ContractUpdateModel) => () => Promise<ContractModel>;
delete: (id: string) => () => Promise<void>;
}
interface ContractUpdateModel {
contract: ContractRequestModel;
id: string;
}
export const contractActions: ActionsType<ContractState, ContractActions> = {
setLoading: isLoading => state => (
Object.assign({}, state, {
isLoading,
})
),
setList: contracts => state => (
Object.assign({}, state, {
list: [...contracts],
})
),
fetchAll: () => (_, actions) => {
actions.setLoading(true);
employeeService
.getAllContracts()
.then((contracts) => {
actions.setLoading(false);
actions.setList(contracts);
return contracts;
});
},
create: (contract: ContractRequestModel) => () => {
return employeeService
.createContract(contract)
.then((contract: ContractModel) => {
return contract;
});
},
update: (update: ContractUpdateModel) => () => {
const { contract, id } = update;
return employeeService
.updateContract(contract, id)
.then((contract: ContractModel) => {
return contract;
});
},
delete: (id: string) => () => {
return employeeService.deleteContract(id);
},
};
<file_sep>/src/api/api-error.ts
export class ApiError extends Error {
constructor(public status: number, public message: string) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
}
<file_sep>/src/state/form/allocation-form.state.ts
import { Moment } from 'moment';
import { BaseForm, FormControl } from './types';
import { durationValidator, selectValidator } from './validators';
export interface AllocationFormState extends BaseForm {
controls: {
id: FormControl<string>;
projectId: FormControl<string>;
employeeId: FormControl<string>;
contractId: FormControl<string>;
startDate: FormControl<Moment>;
endDate: FormControl<Moment>;
pensumPercentage: FormControl<number>;
};
}
export const initAllocationForm: () => AllocationFormState = () => ({
isOpen: false,
isSaving: false,
controls: {
id: {
name: 'id',
value: null,
},
projectId: {
name: 'projectId',
value: null,
validators: [
selectValidator,
],
},
employeeId: {
name: 'employeeId',
value: null,
validators: [
selectValidator,
],
},
contractId: {
name: 'contractId',
value: null,
validators: [
selectValidator,
],
},
startDate: {
name: 'startDate',
value: null,
validators: [
durationValidator,
],
},
endDate: {
name: 'endDate',
value: null,
validators: [
durationValidator,
],
},
pensumPercentage: {
name: 'pensumPercentage',
value: null,
},
},
});
<file_sep>/src/services/allocation.service.ts
import { apiService, ApiService } from './api.service';
import { AllocationModel } from '../api/dto/allocation.model';
import { Allocation } from '../api/dto/allocation';
import { AllocationRequestModel } from '../api/dto/allocation.request.model';
import { ServiceError } from './service-error';
import { ResponseStatusCode } from '../api/response-status-code.enum';
class AllocationService {
private static instance: AllocationService;
private constructor(private api: ApiService) {}
public create(allocation: AllocationRequestModel): Promise<AllocationModel> {
return this.api.post<Allocation>('/api/allocation', allocation)
.then(e => new AllocationModel(e))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to create allocation');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Employee or Project not found');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for creating allocation failed');
}
throw error;
});
}
public getAll(employeeId?: string, projectId?: string, fromDate?: string, toDate?: string): Promise<AllocationModel[]> {
const params = {
employeeId,
projectId,
fromDate,
toDate,
};
return this.api.get<Allocation[]>('/api/allocation', params)
.then((list: Allocation[]) => list.map(e => new AllocationModel(e)))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to view allocation');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Employee or Project not found');
}
throw error;
});
}
public get(id: string): Promise<AllocationModel> {
return this.api.get<Allocation>(`/api/allocation/${id}`)
.then(e => new AllocationModel(e))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to view allocation');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Allocation not found');
}
throw error;
});
}
public update(allocation: AllocationRequestModel, id: string): Promise<AllocationModel> {
return this.api.put<Allocation>(`/api/allocation/${id}`, allocation)
.then(e => new AllocationModel(e))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to update allocation');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Allocation, Employee or Project not found');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for updateing allocation failed');
}
throw error;
});
}
public delete(id: string): Promise<void> {
return this.api.delete<Allocation>(`/api/allocation/${id}`)
.then(() => {})
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to delete allocation');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Allocation not found');
}
throw error;
});
}
public filterByProject(allocations: AllocationModel[] | null, projectId: string): AllocationModel[] {
return (null === allocations) ? [] : allocations.filter(e => e.projectId === projectId);
}
public static getInstance(): AllocationService {
if (!AllocationService.instance) {
AllocationService.instance = new AllocationService(apiService);
}
return AllocationService.instance;
}
}
export const allocationService = AllocationService.getInstance();
export default AllocationService;
<file_sep>/src/actions/form/allocation-form.actions.ts
import { ActionsType } from 'hyperapp';
import { GenericFormActions, patch, setOpen, setSaving, updateValue } from './index';
import { AllocationFormState, initAllocationForm } from '../../state/form/allocation-form.state';
import { Actions } from '../index';
import { getToastMessage, getApiErrorToast } from '../../utils';
import { AllocationRequestModel } from '../../api/dto/allocation.request.model';
import { AllocationModel } from '../../api/dto/allocation.model';
import { ContractModel } from '../../api/dto/contract.model';
export const allocationFormActions: ActionsType<AllocationFormState, GenericFormActions<AllocationFormState>> = {
setSaving: isSaving => state => setSaving(isSaving, state),
patch: newValues => state => patch(newValues, state),
updateValue: control => state => updateValue(control, state),
reset: () => (state) => {
return Object.assign({}, state, initAllocationForm());
},
setOpen: isOpen => state => setOpen(isOpen, state),
};
export const showAllocationCreateForm = (show: boolean, actions: Actions): void => {
actions.form.allocation.reset();
actions.form.allocation.setOpen(show);
};
export const showManageAllocationModal = (allocation: AllocationModel, contracts: ContractModel[], actions: Actions) => {
const contract = contracts.find(c => c.id === allocation.contractId);
if (contract == null) {
throw new Error(`ContractModel for id '${allocation.contractId}' should be available`);
}
actions.form.allocation.patch({
...allocation,
employeeId: contract.employeeId,
});
actions.form.allocation.setOpen(true);
};
export const createAllocation = (state: AllocationFormState, actions: Actions): void => {
const { projectId, contractId, pensumPercentage, startDate, endDate } = state.controls;
actions.form.allocation.setSaving(true);
try {
const request = new AllocationRequestModel({
projectId: projectId.value!,
contractId: contractId.value!,
pensumPercentage: pensumPercentage.value!,
startDate: startDate.value!,
endDate: endDate.value!,
});
actions
.allocation
.create(request)
.then(() => {
actions.toast.success(getToastMessage(`Successfully created allocation`));
actions.form.allocation.reset();
// Refresh underlying view
actions.allocation.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error creating allocation', error));
actions.form.allocation.setSaving(false);
});
} catch (error) {
actions.toast.error(getApiErrorToast('Error creating allocation', error));
actions.form.allocation.setSaving(false);
}
};
export const updateAllocation = (state: AllocationFormState, actions: Actions): void => {
const { id, projectId, contractId, pensumPercentage, startDate, endDate } = state.controls;
actions.form.allocation.setSaving(true);
try {
const request = new AllocationRequestModel({
projectId: projectId.value!,
contractId: contractId.value!,
pensumPercentage: pensumPercentage.value!,
startDate: startDate.value!,
endDate: endDate.value!,
});
if (id.value == null) {
throw Error(`'ID' is missing`);
}
actions
.allocation
.update({ allocation: request, id: id.value })
.then(() => {
actions.toast.success(getToastMessage(`Successfully updated allocation`));
actions.form.allocation.reset();
// Refresh underlying view
actions.allocation.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error updating allocation', error));
actions.form.allocation.setSaving(false);
});
} catch (error) {
actions.toast.error(getApiErrorToast('Error updating allocation', error));
actions.form.allocation.setSaving(false);
}
};
export const removeAllocation = (id: string, actions: Actions): void => {
actions.form.allocation.setSaving(true);
actions
.allocation
.delete(id)
.then(() => {
actions.toast.success(getToastMessage(`Successfully deleted allocation`));
actions.form.allocation.reset();
// Refresh underlying view
actions.allocation.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error deleting allocation', error));
actions.form.allocation.setSaving(false);
});
};
<file_sep>/src/api/dto/project.model.ts
import { Project } from './project';
import { ProjectBaseModel } from './project.base.model';
import { AllocationModel } from './allocation.model';
import { getDaysOfDateRange } from '../../utils';
export class ProjectModel extends ProjectBaseModel {
public readonly id: string;
constructor(project: Project) {
super(project);
if (project.id) {
this.id = project.id;
} else {
throw new Error(`The field 'id' is missing.`);
}
}
public getAllocations(allocations: AllocationModel[]): AllocationModel[] {
return allocations.filter(a => a.projectId === this.id);
}
public getTotalAllocatedPercentage(allocations: AllocationModel[], ...ignoreAllocations: AllocationModel[]): number {
const projectAllocations = this.getAllocations(allocations)
.filter((allocation) => {
return !ignoreAllocations.find(ignoredAllocation => allocation.id === ignoredAllocation.id);
});
return projectAllocations.reduce(
(prev, allocation) => {
const days = getDaysOfDateRange(allocation.startDate, allocation.endDate, true);
return prev + (days * allocation.pensumPercentage);
},
0,
);
}
public static createMap(projects: ProjectModel[]): Map<string, ProjectModel> {
const projectMap: Map<string, ProjectModel> = new Map();
projects.forEach((project) => {
projectMap.set(project.id, project);
});
return projectMap;
}
}
<file_sep>/src/api/dto/allocation.base.model.ts
import { Allocation } from './allocation';
import moment from 'moment';
export class AllocationBaseModel implements Allocation {
public readonly startDate: moment.Moment;
public readonly endDate: moment.Moment;
public readonly pensumPercentage: number;
public readonly contractId: string;
public readonly projectId: string;
constructor(allocation: Allocation) {
if (allocation.startDate) {
this.startDate = moment(allocation.startDate);
} else {
throw new Error(`The field 'startDate' is missing.`);
}
if (allocation.endDate) {
this.endDate = moment(allocation.endDate);
} else {
throw new Error(`The field 'endDate' is missing.`);
}
if (allocation.pensumPercentage) {
this.pensumPercentage = allocation.pensumPercentage;
} else {
throw new Error(`The field 'pensumPercentage' is missing.`);
}
if (allocation.contractId) {
this.contractId = allocation.contractId;
} else {
throw new Error(`The field 'contractId' is missing.`);
}
if (allocation.projectId) {
this.projectId = allocation.projectId;
} else {
throw new Error(`The field 'projectId' is missing.`);
}
}
}
<file_sep>/src/api/dto/project.base.model.ts
import { Project } from './project';
import moment from 'moment';
export class ProjectBaseModel implements Project {
public readonly name: string;
public readonly ftePercentage: number;
public readonly startDate: moment.Moment;
public readonly endDate: moment.Moment;
public readonly projectManagerId: string;
public get durationInDays(): number {
return this.endDate.diff(this.startDate, 'days') + 1;
}
public get totalPercentage(): number {
return this.durationInDays * this.ftePercentage;
}
constructor(project: Project) {
if (project.name) {
this.name = project.name;
} else {
throw new Error(`The field 'name' is missing.`);
}
if (project.ftePercentage) {
this.ftePercentage = project.ftePercentage;
} else {
throw new Error(`The field 'ftePercentage' is missing.`);
}
if (project.startDate) {
this.startDate = moment(project.startDate);
} else {
throw new Error(`The field 'startDate' is missing.`);
}
if (project.endDate) {
this.endDate = moment(project.endDate);
} else {
throw new Error(`The field 'endDate' is missing.`);
}
if (project.projectManagerId) {
this.projectManagerId = project.projectManagerId;
} else {
throw new Error(`The field 'projectManagerId' is missing.`);
}
}
}
<file_sep>/src/services/user.service.ts
import jwtDecode from 'jwt-decode';
import { apiService, ApiService } from './api.service';
import { Credentials } from '../api/dto/credentials';
import { Token } from '../api/dto/token';
import { TokenPayload } from '../api/dto/token-payload';
import { ApiError } from '../api/api-error';
import { ResponseStatusCode } from '../api/response-status-code.enum';
import { ServiceError } from './service-error';
import { LOCAL_STORAGE_USER_TOKEN } from '../constants';
class UserService {
private static instance: UserService;
private constructor(private api: ApiService) {}
public static getInstance(): UserService {
if (!UserService.instance) {
UserService.instance = new UserService(apiService);
}
return UserService.instance;
}
public login(credentials: Credentials): Promise<string> {
return this.api.post<Token>('/api/token', credentials)
.then(response => response.token)
.catch((error: ApiError) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Employee not found or invalid password');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for the username/password failed');
}
throw error;
});
}
public refresh(): Promise<string> {
const token = this.getToken();
if (token == null) {
return Promise.reject(new ServiceError('No token available to refresh'));
}
const payload: Token = { token };
return this.api.put<Token>(`/api/token`, payload)
.then(response => response.token)
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Token not valid or user not found');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for the token failed');
}
throw error;
});
}
public decodeToken(token: string): TokenPayload {
const payload: TokenPayload = jwtDecode(token);
if (payload.employee == null) {
throw new Error(`Expected 'employee' in the token payload.`);
}
return payload;
}
public getToken(): string | null {
return window.localStorage.getItem(LOCAL_STORAGE_USER_TOKEN);
}
public setToken(token: string): void {
window.localStorage.setItem(LOCAL_STORAGE_USER_TOKEN, token);
}
public removeToken(): void {
window.localStorage.removeItem(LOCAL_STORAGE_USER_TOKEN);
}
}
export const userService = UserService.getInstance();
export default userService;
<file_sep>/src/models/allocation-extended.model.ts
import { AllocationModel } from '../api/dto/allocation.model';
import { ContractModel } from '../api/dto/contract.model';
import { Allocation } from '../api/dto/allocation';
import { Contract } from '../api/dto/contract';
export class AllocationExtendedModel extends AllocationModel {
public readonly contract: ContractModel;
constructor(allocation: Allocation, contract: Contract) {
super(allocation);
this.contract = new ContractModel(contract);
}
}
<file_sep>/src/api/dto/project.ts
import { Moment } from 'moment';
/**
* Represents a FHNW research project with a
* given full-time-equivalent (FTE) workload in
* percentages managed by a project manager employee
* @export
* @interface Project
*/
export interface Project {
/**
* Project ID
* @type {string}
* @memberof Project
*/
id?: string;
/**
* Project name
* @type {string}
* @memberof Project
*/
name: string;
/**
* Full time equivalent represented as
* a percentage value (1 FTE = 100% = 1 person working 1 day)
* @type {number}
* @memberof Project
*/
ftePercentage: number;
/**
* Project start date (YYYY-MM-DD)
* @type {string}
* @memberof Project
*/
startDate: string | Moment;
/**
* Project end date (YYYY-MM-DD)
* @type {string}
* @memberof Project
*/
endDate: string | Moment;
/**
* Project manager employee ID
* @type {string}
* @memberof Project
*/
projectManagerId: string;
}
<file_sep>/src/state/form/authentication-form.state.ts
import { FormControl, BaseForm } from './types';
export interface AuthenticationFormState extends BaseForm {
controls: {
emailAddress: FormControl<string>;
rawPassword: FormControl<string>;
};
}
export const initAuthenticationForm: () => AuthenticationFormState = () => ({
controls: {
emailAddress: {
name: 'emailAddress',
value: null,
},
rawPassword: {
name: '<PASSWORD>',
value: null,
},
},
isOpen: false,
isSaving: false,
});
<file_sep>/src/api/dto/allocation.model.ts
import { Allocation } from './allocation';
import { AllocationBaseModel } from './allocation.base.model';
export class AllocationModel extends AllocationBaseModel {
public readonly id?: string | undefined;
constructor(allocation: Allocation) {
super(allocation);
if (allocation.id) {
this.id = allocation.id;
} else {
throw new Error(`The field 'id' is missing.`);
}
}
public static createMapByContractId(allocations: AllocationModel[]): Map<string, Set<AllocationModel>> {
const map: Map<string, Set<AllocationModel>> = new Map();
allocations.forEach((allocation) => {
const { contractId } = allocation;
if (!map.has(contractId)) {
map.set(contractId, new Set());
}
const set = map.get(contractId);
set!.add(allocation);
});
return map;
}
}
<file_sep>/src/actions/view/projects-view.actions.ts
import { ActionResult, ActionsType } from 'hyperapp';
import { ProjectsViewState } from '../../state/view/projects-view.state';
export interface ProjectsViewActions {
updateFilterString: (filterString: string) => (state: ProjectsViewState) => ActionResult<ProjectsViewState>;
}
export const projectsViewActions: ActionsType<ProjectsViewState, ProjectsViewActions> = {
updateFilterString: filterString => () => ({
filterString,
}),
};
<file_sep>/src/services/service-error.ts
export class ServiceError extends Error {
constructor(public message: string) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
public toString(): string {
return this.message;
}
}
<file_sep>/src/state/view/employees-view.state.ts
export interface EmployeesViewState {
filterString: string;
}
export const defaultEmployeesViewState: EmployeesViewState = {
filterString: '',
};
<file_sep>/src/actions/form/employee-form.actions.ts
import { ActionsType } from 'hyperapp';
import { GenericFormActions, patch, setOpen, setSaving, updateValue } from './index';
import { EmployeeFormState, initEmployeeForm } from '../../state/form/employee-form.state';
import { Actions } from '../index';
import { EmployeeRequestModel } from '../../api/dto/employee.request.model';
import { EmployeeModel } from '../../api/dto/employee.model';
import { getToastMessage, getApiErrorToast } from '../../utils';
import { Role } from '../../api/role';
export const employeeFormActions: ActionsType<EmployeeFormState, GenericFormActions<EmployeeFormState>> = {
setSaving: isSaving => state => setSaving(isSaving, state),
patch: newValues => state => patch(newValues, state),
updateValue: control => state => updateValue(control, state),
reset: () => (state) => {
return Object.assign({}, state, initEmployeeForm());
},
setOpen: isOpen => state => setOpen(isOpen, state),
};
export const createEmployee = (state: EmployeeFormState, actions: Actions): void => {
const { emailAddress, firstName, lastName, password, role } = state.controls;
actions.form.employee.setSaving(true);
try {
const request = new EmployeeRequestModel({
emailAddress: emailAddress.value!,
firstName: firstName.value!,
lastName: lastName.value!,
active: true,
});
if (password.value == null) {
throw Error(`'Password' is missing`);
}
if (role.value == null) {
throw Error(`'Role' is missing`);
}
actions
.employee
.create({ employee: request, password: <PASSWORD>, role: role.value as Role })
.then((employee: EmployeeModel) => {
actions.toast.success(getToastMessage(`Successfully created employee '${employee.fullName}'`));
actions.form.employee.setSaving(false);
actions.form.employee.patch({
...employee,
});
// Refresh underlying view
actions.employee.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error creating employee', error));
actions.form.employee.setSaving(false);
});
} catch (error) {
actions.toast.error(getApiErrorToast('Error creating employee', error));
actions.form.employee.setSaving(false);
}
};
export const updateEmployee = (state: EmployeeFormState, actions: Actions) => {
const { id, emailAddress, firstName, lastName } = state.controls;
actions.form.employee.setSaving(true);
try {
const request = new EmployeeRequestModel({
emailAddress: emailAddress.value!,
firstName: firstName.value!,
lastName: lastName.value!,
active: true,
});
if (id.value == null) {
throw Error(`'ID' is missing`);
}
actions
.employee
.update({ employee: request, id: id.value })
.then((employee: EmployeeModel) => {
actions.toast.success(getToastMessage(`Successfully updated employee '${employee.fullName}'`));
actions.form.employee.setSaving(false);
// Refresh underlying view
actions.employee.fetchAll();
actions.form.employee.reset();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error updating employee', error));
actions.form.employee.setSaving(false);
});
} catch (error) {
actions.toast.error(getApiErrorToast('Error updating employee', error));
actions.form.employee.setSaving(false);
}
};
<file_sep>/src/actions/form/contract-form.actions.ts
import { ActionResult, ActionsType } from 'hyperapp';
import {
ContractForm,
ContractFormState,
initContractForm,
initContractFormState,
} from '../../state/form/contract-form.state';
import { FormControl } from '../../state/form/types';
import { patch, updateValue } from './index';
import { Contract } from '../../api/dto/contract';
import { Actions } from '../index';
import { ContractRequestModel } from '../../api/dto/contract.request.model';
import { ContractModel } from '../../api/dto/contract.model';
import { getToastMessage, getApiErrorToast } from '../../utils';
interface ListUpdateValue<T> {
index: number;
control: FormControl<T>;
}
interface ListSaving {
index: number;
isSaving: boolean;
}
interface ListPatch {
index: number;
values: {[key: string]: any};
}
export interface ContractFormActions {
addEmpty: (employeeId: string) => (state: ContractFormState) => ActionResult<ContractFormState>;
set: (form: ContractForm[]) => () => ActionResult<ContractFormState>;
remove: (index: number) => (state: ContractFormState) => ActionResult<ContractFormState>;
updateValue: (update: ListUpdateValue<any>) => (state: ContractFormState) => ActionResult<ContractFormState>;
patch: (listPatch: ListPatch) => (state: ContractFormState) => ActionResult<ContractFormState>;
patchAll: (contracts: Contract[]) => (state: ContractFormState) => ActionResult<ContractFormState>;
reset: () => () => ActionResult<ContractFormState>;
setSaving: (listSaving: ListSaving) => (state: ContractFormState) => ActionResult<ContractFormState>;
}
export const contractFormActions: ActionsType<ContractFormState, ContractFormActions> = {
addEmpty: employeeId => (state: ContractFormState) => {
const form = patch({ employeeId }, initContractForm());
return {
list: [...state.list, form],
};
},
set: forms => () => ({ list: [...forms] }),
remove: index => (state: ContractFormState) => ({
list: state.list.filter((_, listIndex) => listIndex !== index),
}),
updateValue: (update: ListUpdateValue<any>) => (state: ContractFormState) => ({
list: state.list.map((form, listIndex) => {
if (listIndex !== update.index) {
return form;
}
return updateValue(update.control, form);
}),
}),
patch: (listPatch: ListPatch) => (state: ContractFormState) => ({
list: state.list.map((form, listIndex) => {
if (listIndex !== listPatch.index) {
return form;
}
return patch(listPatch.values, form);
}),
}),
patchAll: (contracts: Contract[]) => (state: ContractFormState) => {
const list = contracts.map((contract) => {
const form = initContractForm();
return patch(contract, form);
});
return {
...state,
list,
};
},
reset: () => () => initContractFormState(),
setSaving: (listSaving: ListSaving) => (state: ContractFormState) => ({
list: state.list.map((form, listIndex) => {
if (listIndex !== listSaving.index) {
return form;
}
return {
...form,
isSaving: listSaving.isSaving,
};
}),
}),
};
export const updateContractFormValue = (index: number, actions: ContractFormActions) => (control: FormControl<any>) => {
actions.updateValue({
index,
control,
});
};
export const removeContractForm = (key: number, actions: Actions) => {
actions.form.contract.remove(key);
};
export const createContract = (state: ContractForm, index: number, actions: Actions) => {
const { startDate, endDate, pensumPercentage, employeeId } = state.controls;
try {
const request = new ContractRequestModel({
startDate: startDate.value!,
endDate: endDate.value!,
pensumPercentage: pensumPercentage.value!,
employeeId: employeeId.value!,
});
actions
.contract
.create(request)
.then((contract: ContractModel) => {
actions.toast.success(getToastMessage(`Contract successfully created`));
actions.contract.fetchAll();
actions.form.contract.patch({
index,
values: contract,
});
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error creating contract', error));
});
} catch (error) {
actions.toast.error(getApiErrorToast('Error creating contract', error));
}
};
// TODO RENAME STATE FORM
export const updateContract = (state: ContractForm, actions: Actions) => {
const { id, startDate, endDate, pensumPercentage, employeeId } = state.controls;
try {
const request = new ContractRequestModel({
startDate: startDate.value!,
endDate: endDate.value!,
pensumPercentage: pensumPercentage.value!,
employeeId: employeeId.value!,
});
if (id.value == null) {
throw Error(`'ID' is missing`);
}
actions
.contract
.update({ contract: request, id: id.value })
.then(() => {
actions.toast.success(getToastMessage(`Contract successfully updated`));
actions.contract.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error updating contract', error));
});
} catch (error) {
actions.toast.error(getApiErrorToast('Error updating contract', error));
}
};
export const deleteContract = (state: ContractForm, key: number, actions: Actions) => {
// TODO VALIDATE if id is available
actions
.contract
.delete(state.controls.id.value!)
.then(() => {
removeContractForm(key, actions);
actions.toast.success(getToastMessage('Contract successfully deleted'));
actions.contract.fetchAll();
})
.catch((error: Error) => {
actions.toast.error(getApiErrorToast('Error deleting contract', error));
});
};
<file_sep>/README.md
# WODSS Project Management Frontend: Group 2
[](https://travis-ci.com/kelvinlouis/fhnw-wodss-frontend)
This repository contains the source code of the frontend client of group 2.
The corresponding [backend](https://gitlab.fhnw.ch/christoph.christen/wodss-backend) is hosted on Gitlab.
You might need privileges to access the repository. Please contact _<NAME>_ if you need access.
The project is part of the [WODSS](https://www.fhnw.ch/de/studium/module/6008109) module
at the University of Applied Sciences and Arts Northwestern Switzerland (FHNW).
This documentation functions as a guide. It lists all prerequisites that are needed to start developing and building
the application for a production or similar environment.
## Prerequisites
In order to start developing or building the client, the following tools are required:
- **Node.js**: v10.x.x
- **Yarn**: v1.15.2 or
- **npm**: v6.x.x
We use _Yarn_ as our package manager. Using _npm_ instead should not be a problem.
## Getting started
### Installation
After all necessary tools are installed (see previous chapter), you can run the following commands to install the
client:
```
git clone https://github.com/kelvinlouis/fhnw-wodss-frontend.git
cd fhnw-wodss-frontend
yarn
```
It will clone/download the repository and install all the necessary dependencies.
### Development
Before starting developing, please ensure that you installed all prerequisites and configured the client correctly.
Please refer to the [configuration](#configuration).
```
# Starting the development server: http://localhost:1234/
yarn start
# Linting TypeScript
yarn lint
# Linting SCSS
yarn lint-scss
```
If you experience issues running any of the comments above, please refer to [Known Issues](#known-issues).
### Build
If you want to build a production build, ensure you configured the client correctly beforehand. Please refer to the [configuration](#configuration).
The first command `yarn build` will create all the necessary files to host the client on any server.
```
# Creates a production build in dist/
yarn build
# Testing the build
cd dist
python -m SimpleHTTPServer 8000
```
## Configuration
In order to run the development server or build for production, you have to prepare your environmental files.
They contain variables that the client will use during build and runtime.
You can copy the provided `.env.template`, rename and change it accordingly.
- For development (local) you will have to rename it to: `.env`
- In case of building for production you will have to rename it to: `.env.production`
### Options
The following options are required:
- `BACKEND_URL`: The url to the running backend server. Ensure that the port is set correctly and it does not contain a trailing slash!
Example: `BACKEND_URL=http://localhost:8080`
- `BACKEND_JWT_TOKEN_TTL`: Specifies how long the JWT token provided by the backend is valid.
It acts as a fallback, if the token does not contain the `exp` attribute.
Example: `BACKEND_JWT_TOKEN_TTL=3600` expects it to be valid for 1 hour (60 * 60seconds).
The following options are optional:
- `PARCEL_MAX_CONCURRENT_CALLS`: This option is used during build time (`yarn start` or `yarn build`) and limits the number of concurrent calls the parcel
bundler is allowed to do. We experienced issues on Windows and had to limit it. Example: `PARCEL_MAX_CONCURRENT_CALLS=3`
## Known Issues
- **After running `yarn start` the build gets stuck**: Check if your `.env` file has the following property set `PARCEL_MAX_CONCURRENT_CALLS=3`.
We experienced difficulties building on Windows.
- **The client does not connect to the backend server**: Ensure that you have set `BACKEND_URL` correctly and that the URL does not contain a trailing slash at the end.
## Change Log
### Version 1.0.0 (2019-04-28)
- First version of the application.
## Links
- [Backend](https://gitlab.fhnw.ch/christoph.christen/wodss-backend)
- [API](https://github.com/swaechter/fhnw-wodss-spec)
- [Hyperapp](https://github.com/jorgebucaran/hyperapp)
## Contributors
- <NAME>
- <NAME>
- <NAME>
- <NAME>
<file_sep>/src/state/form/validators.ts
import { Moment } from 'moment';
import { FormControl, FormErrors, BaseForm } from './types';
export const textRequiredValidator = (control: FormControl<string>): FormErrors => {
if (control.value != null && control.value.length === 0) {
return {
required: true,
};
}
return;
};
export const emailValidator = (control: FormControl<string>): FormErrors => {
const emailRegex = new RegExp([
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@/,
/((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
].map((r) => { return r.source; }).join(''));
if (control.value != null && control.value.length > 0 && !emailRegex.test(control.value.toLowerCase())) {
return {
email: true,
};
}
return;
};
export const durationValidator = (control: FormControl<Moment>, state: BaseForm): FormErrors => {
const { controls } = state;
if (control.value != null && control.name === 'startDate' && control.value.isSameOrAfter(controls['endDate'].value)) {
return {
negativeDuration: true,
};
}
if (control.value != null && control.name === 'endDate' && control.value.isSameOrBefore(controls['startDate'].value)) {
return {
negativeDuration: true,
};
}
return;
};
export const selectValidator = (control: FormControl<string>): FormErrors => {
if (control.value != null && control.value.length === 0) {
return {
required: true,
};
}
return;
};
<file_sep>/src/api/dto/allocation.request.model.ts
import { DATE_FORMAT_STRING } from '../../constants';
import { Allocation } from './allocation';
import { AllocationModel } from './allocation.model';
import { AllocationBaseModel } from './allocation.base.model';
export class AllocationRequestModel implements Allocation {
public readonly startDate: string;
public readonly endDate: string;
public readonly pensumPercentage: number;
public readonly contractId: string;
public readonly projectId: string;
constructor(allocation: AllocationBaseModel | AllocationModel) {
if (allocation.startDate) {
this.startDate = allocation.startDate.format(DATE_FORMAT_STRING);
} else {
throw new Error(`The field 'startDate' is missing.`);
}
if (allocation.endDate) {
this.endDate = allocation.endDate.format(DATE_FORMAT_STRING);
} else {
throw new Error(`The field 'endDate' is missing.`);
}
if (allocation.pensumPercentage) {
this.pensumPercentage = allocation.pensumPercentage;
} else {
throw new Error(`The field 'pensumPercentage' is missing.`);
}
if (allocation.contractId) {
this.contractId = allocation.contractId;
} else {
throw new Error(`The field 'contractId' is missing.`);
}
if (allocation.projectId) {
this.projectId = allocation.projectId;
} else {
throw new Error(`The field 'projectId' is missing.`);
}
}
}
<file_sep>/src/actions/user.actions.ts
import { ActionResult, ActionsType } from 'hyperapp';
import { UserState } from '../state';
import { EmployeeModel } from '../api/dto/employee.model';
import { Credentials } from '../api/dto/credentials';
import { userService } from '../services/user.service';
import moment from 'moment';
export interface UserActions {
login:
(credentials: Credentials) =>
(state: UserState, actions: UserActions) =>
Promise<EmployeeModel>;
refresh: () => (state: UserState, actions: UserActions) => Promise<EmployeeModel>;
scheduleRefresh: (expirationTimestamp?: number) => (state: UserState, actions: UserActions) => null;
restore: () => (state: UserState, actions: UserActions) => Promise<EmployeeModel>;
logout: () => (state: UserState) => ActionResult<UserState>;
patch: (values: Partial<UserState>) => (state: UserState) => ActionResult<UserState>;
}
/**
* Is executed if the server successfully returns a token.
* @param state
* @param actions
*/
const onSuccess = (state: UserState, actions: UserActions) => (token: string): EmployeeModel => {
const { employee, exp } = userService.decodeToken(token);
const employeeModel = new EmployeeModel(employee);
userService.setToken(token);
actions.patch({
token,
authenticated: true,
employee: employeeModel,
});
actions.scheduleRefresh(exp);
return employeeModel;
};
export const userActions: ActionsType<UserState, UserActions> = {
login: credentials => (state, actions) => {
return userService
.login(credentials)
.then(onSuccess(state, actions));
},
refresh: () => (state, actions) => {
return userService
.refresh()
.then(onSuccess(state, actions));
},
/**
* IMPORTANT: Timestamps and the TTL config value have to be in unix timestamp.
* @param expirationTimestamp - unix timestamp (in seconds)
*/
scheduleRefresh: expirationTimestamp => (_, actions) => {
const configTtl = process.env.BACKEND_JWT_TOKEN_TTL;
let scheduleIn = configTtl ? +configTtl : null;
const now = moment();
if (expirationTimestamp != null) {
const expirationDate = moment(expirationTimestamp, 'X');
if (expirationDate.diff(now) > 0) {
scheduleIn = Math.round(expirationDate.diff(now) / 1000);
}
}
if (scheduleIn != null) {
// Schedule 10 percent before expiration (milliseconds)
const scheduleBeforeExpiration = Math.round(scheduleIn - (scheduleIn * 0.1)) * 1000;
setTimeout(
() => {
actions.refresh();
},
scheduleBeforeExpiration,
);
}
},
restore: () => (_, actions) => {
return actions
.refresh()
.catch(() => {
actions.patch({
authenticated: false,
});
});
},
logout: () => (state) => {
if (!state.authenticated) {
throw new Error('User is not authenticated');
}
userService.removeToken();
return {
authenticated: false,
employee: null,
};
},
patch: newValues => state => ({
...state,
...newValues,
}),
};
<file_sep>/src/state/form/contract-form.state.ts
import { Moment } from 'moment';
import { BaseForm, FormControl, ListForm } from './types';
import { durationValidator } from './validators';
export interface ContractForm extends BaseForm {
controls: {
id: FormControl<string>;
employeeId: FormControl<string>;
startDate: FormControl<Moment>;
endDate: FormControl<Moment>;
pensumPercentage: FormControl<number>;
};
}
export type ContractFormState = ListForm<ContractForm>;
export const initContractFormState: () => ContractFormState = () => ({
list: [],
});
export const initContractForm: () => ContractForm = () => ({
isOpen: false,
isSaving: false,
controls: {
id: {
name: 'id',
value: null,
},
employeeId: {
name: 'employeeId',
value: null,
},
startDate: {
name: 'startDate',
value: null,
validators: [
durationValidator,
],
},
endDate: {
name: 'endDate',
value: null,
validators: [
durationValidator,
],
},
pensumPercentage: {
name: 'pensumPercentage',
value: null,
},
},
});
<file_sep>/src/api/response-status-code.enum.ts
export enum ResponseStatusCode {
NoContent = 204,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
PreconditionFailed = 412,
InternalServerError = 500,
NetworkError = 999,
}
<file_sep>/src/services/project.service.ts
import { apiService, ApiService } from './api.service';
import { Project } from '../api/dto/project';
import { ProjectModel } from '../api/dto/project.model';
import { ProjectRequestModel } from '../api/dto/project.request.model';
import { ServiceError } from './service-error';
import { ResponseStatusCode } from '../api/response-status-code.enum';
class ProjectService {
private static instance: ProjectService;
private constructor(private api: ApiService) {}
public create(project: ProjectRequestModel): Promise<ProjectModel> {
return this.api.post<Project>('/api/project', project)
.then(e => new ProjectModel(e))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to create project');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for creating project failed');
}
throw error;
});
}
public getAll(projectManagerId?: string, fromDate?: string, toDate?: string): Promise<ProjectModel[]> {
const params = {
projectManagerId,
fromDate,
toDate,
};
return this.api.get<Project[]>('/api/project', params)
.then((list: Project[]) => list.map(e => new ProjectModel(e)))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Project Manager not found');
}
throw error;
});
}
public get(id: string): Promise<ProjectModel> {
return this.api.get<Project>(`/api/project/${id}`)
.then(e => new ProjectModel(e))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to view project');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Project not found');
}
throw error;
});
}
public update(project: ProjectRequestModel, id: string): Promise<ProjectModel> {
return this.api.put<Project>(`/api/project/${id}`, project)
.then(e => new ProjectModel(e))
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to update project');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Project not found');
}
if (error.status === ResponseStatusCode.PreconditionFailed) {
throw new ServiceError('Precondition for updateing project failed');
}
throw error;
});
}
public delete(id: string): Promise<void> {
return this.api.delete<null>(`/api/project/${id}`)
.then(() => {})
.catch((error) => {
ApiService.checkDefaultResponseStatus(error);
if (error.status === ResponseStatusCode.Forbidden) {
throw new ServiceError('Not allowed to delete project');
}
if (error.status === ResponseStatusCode.NotFound) {
throw new ServiceError('Project not found');
}
throw error;
});
}
public static getInstance(): ProjectService {
if (!ProjectService.instance) {
ProjectService.instance = new ProjectService(apiService);
}
return ProjectService.instance;
}
}
export const projectService = ProjectService.getInstance();
export default projectService;
<file_sep>/src/state/form/types.ts
export enum FormErrorType {
required = 'required',
email = 'email',
negativeDuration = 'negativeDuration',
}
export type FormErrors = {[key in FormErrorType]?: boolean} | undefined;
export type ValidatorFunction<T> = (control: FormControl<T>, state: BaseForm) => FormErrors;
export interface FormControl<T> {
name: string;
value: T | null;
errors?: FormErrors;
validators?: ValidatorFunction<T>[];
}
export interface BaseForm {
isSaving: boolean;
isOpen: boolean;
controls: {[key: string]: any};
}
export interface ListForm<T extends BaseForm> {
list: T[];
}
| a7d66714d0ce121feba96055a63d9320a7265711 | [
"Markdown",
"TypeScript"
]
| 65 | TypeScript | NateMS/fhnw-wodss-frontend | e69bfd23a36941f5149e4665afea0dbbe2f0ec5d | 4d8d4d55f783d02b1158e06929d731df6d116ec6 |
refs/heads/master | <file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"golang.org/x/net/context"
)
// verifyIDToken verifies Google ID token, which heavily based on JWT.
// It returns user ID of the pricipal who granted an authorization.
func verifyIDToken(c context.Context, t string) (string, error) {
token, err := jwt.Parse(t, func(j *jwt.Token) (interface{}, error) {
kid, _ := j.Header["kid"].(string)
keys, err := idTokenCerts(c)
if err != nil {
return nil, err
}
cert, ok := keys[kid]
if !ok {
return nil, fmt.Errorf("verifyIDToken: keys[%q] = nil", kid)
}
return cert, nil
})
if err != nil {
return "", err
}
sub, ok := token.Claims["sub"].(string)
if !ok {
return "", errors.New("verifyIDToken: invalid 'sub' claim")
}
return sub, nil
}
// idTokenCerts returns public certificates used to encrypt ID tokens.
// It returns a cached copy, if available, or fetches from a known URL otherwise.
// The returnd map is keyed after the cert IDs.
func idTokenCerts(c context.Context) (map[string][]byte, error) {
certURL := config.Google.CertURL
// try cache first
keys, err := certsFromCache(c, certURL)
if err == nil {
return keys, nil
}
// fetch from public endpoint otherwise
var exp time.Duration
keys, exp, err = fetchPublicKeys(c, certURL)
if err != nil {
return nil, err
}
if exp <= 0 {
return keys, nil
}
// cache the result for duration exp
var data bytes.Buffer
if err := gob.NewEncoder(&data).Encode(keys); err != nil {
errorf(c, "idTokenCerts: %v", err)
} else if err := cache.set(c, certURL, data.Bytes(), exp); err != nil {
errorf(c, "idTokenCerts: cache.set(%q): %v", certURL, err)
}
// return the result anyway, even on cache errors
return keys, nil
}
// certsFromCache returns cached public keys.
// See idTokenCerts func.
func certsFromCache(c context.Context, k string) (map[string][]byte, error) {
data, err := cache.get(c, k)
if err != nil {
return nil, err
}
var keys map[string][]byte
return keys, gob.NewDecoder(bytes.NewReader(data)).Decode(&keys)
}
// certsFromCache fetches public keys from the network.
// See idTokenCerts func.
func fetchPublicKeys(c context.Context, url string) (map[string][]byte, time.Duration, error) {
res, err := httpClient(c).Get(url)
if err != nil {
return nil, 0, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, 0, fmt.Errorf("fetchPublicKeys: %s: %v", url, res.Status)
}
var body map[string]string
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
return nil, 0, err
}
keys := make(map[string][]byte)
for k, v := range body {
keys[k] = []byte(v)
}
return keys, resourceExpiry(res.Header), nil
}
// resourceExpiry returns the remaining life of a resource
// based on Cache-Control and Age headers.
func resourceExpiry(h http.Header) time.Duration {
var max int64
for _, c := range strings.Split(h.Get("cache-control"), ",") {
c = strings.ToLower(strings.TrimSpace(c))
if !strings.HasPrefix(c, "max-age=") {
continue
}
var err error
if max, err = strconv.ParseInt(c[8:], 10, 64); err != nil {
max = 0
}
break
}
age, err := strconv.ParseInt(h.Get("age"), 10, 64)
if err != nil {
age = 0
}
r := max - age
if r < 0 {
return 0
}
return time.Duration(r) * time.Second
}
| 037623a0bd2bac1d431820fa97a5a328b0b09c1b | [
"Go"
]
| 1 | Go | GoogleChrome/ioweb2015 | 9fbdda51cb9bb8c69912277144e3c6910e419893 | b09e0a97fea6ff3b77fc3e8dcc26000962a4a7b7 |
refs/heads/master | <repo_name>ronnyma/GeeksforGeeks<file_sep>/02Subsetsum.py
#!/usr/bin/env python
import random as rnd
import sys
def subset_sum(sum, set):
t = [[0 if x != 0 else 1 for x in range(sum + 1)] for y in range(len(set))]
for i in range(len(t[:])):
for j in range(len(t[i][:])):
num = set[i]
t[i][j] = t[i - 1][j] if t[i - 1][j] else t[i - 1][j - num]
return t[-1][-1]
if __name__ == "__main__":
num = int(sys.argv[1])
d = [x * rnd.randint(1, 1000) for x in range(1, num+1)]
s = sum(d)
print len(d), s / 2
if subset_sum(s / 2, d):
print "Exists!"
else:
print "Not possiblei."
<file_sep>/01Knapsack.py
#!/usr/bin/env python
import pprint as pp
import random as rnd
import sys
from datetime import datetime
def knapsack(capacity, items):
# Define table
t = [[0 for x in range(capacity + 1)] for y in range(len(items) + 1)]
k = [[0 for x in range(capacity)] for y in range(len(items))]
for i in range(1, len(t[:])):
for j in range(1, len(t[:][i])):
w = items[i - 1][0]
v = items[i - 1][1]
w_add = j - w
v_over = t[i - 1][j]
if w <= j and v + t[i - 1][w_add] > v_over:
t[i][j] = v + t[i - 1][w_add]
k[i - 1][j - 1] = 1
else:
t[i][j] = v_over
s = []
l = -1
for i in range(1, len(k) + 1):
it = len(k) - i
if k[-i][l] == 1:
s.append(items[it])
l -= items[it][0]
pp.pprint(s)
print "Optimal weight: %s\nOptimal value: %s\nOptimal # items: %s" % (sum(x[0] for x in s), sum(x[1] for x in s), len(s))
if __name__ == "__main__":
num_items = int(sys.argv[1])
rnd.seed(4096)
d = [(x*rnd.randint(1,150),y*rnd.randint(10,30)) for x in range(1, num_items) for y in range(1, num_items)]
cap = sum(x[0] for x in d)
print "Capacity: ", cap
print "Items count: ", len(d)
startTime = datetime.now()
knapsack(cap/3, d)
print "Run time: ", datetime.now() - startTime
<file_sep>/README.md
# GeeksforGeeks
01 - Knapsack
02 Subset sum
| 7c32effda8e8e50412994a00f247b57e5da33898 | [
"Markdown",
"Python"
]
| 3 | Python | ronnyma/GeeksforGeeks | 893623101f3f9b80e1a16d498e9120774f023199 | fc621ae06179e378730b69138058318799289efb |
refs/heads/main | <file_sep># calculator
Creating Calculator App using ReactJs library.
| 43e18186111ecc44a933815dad7e188d094a92ec | [
"Markdown"
]
| 1 | Markdown | Tanujabshelke/calculator | f9034ff80dd690fbdd520bb3ab0d1c51b83b249a | 84a3800ce8993c3e2a4a139628f0760cdb0dfba7 |
refs/heads/master | <repo_name>villepa/playground<file_sep>/blake/server.rb
require 'json'
require 'sinatra'
textFile = File.open("blake.txt", "r")
poems = textFile.read
get '/' do
File.read('views/index.html')
end
<file_sep>/templating/server.rb
require 'json'
require 'sinatra'
get '/' do
File.read('view/index.html')
#File.read('view/style1.css')
end | 4c0119dc0fbaf82dbebfb19e22a30889d8a58254 | [
"Ruby"
]
| 2 | Ruby | villepa/playground | abc7dcd52ad8b84426f8bcb74ddf052955e473df | aa0eba8ff59aea70748cd89f734576113d6bc67e |
refs/heads/master | <repo_name>synartisis/webo<file_sep>/lib/parsers/tools/cachebuster.js
import fs from 'node:fs/promises'
import crypto from 'node:crypto'
import path from 'node:path'
import { parse } from '../parser.js'
import { getFile } from '../files.js'
import { parsable } from '../../utils/utils.js'
/** @type {(filename: string, config: Webo.Config, options: { type?: Webo.FileTypes, referrer: string, ignoreIfMissing?: boolean }) => Promise<string | null>} */
export async function cachebust(filename, config, { type = undefined, referrer, ignoreIfMissing = false }) {
if (!parsable(filename)) {
try {
return await calcFileHash(filename)
} catch (error) {
if (!ignoreIfMissing) {
throw new Error(`cannot find ${path.relative('.', filename)} referred by ${path.relative('.', referrer)}`, { cause: error })
}
return null
}
}
const file = getFile(filename)
if (file.hash) return file.hash
const { content } = await parse(filename, config, { type, cacheContent: config.command === 'build' })
if (!content) throw new Error(`cannot find ${path.relative('.', filename)} referred by ${path.relative('.', referrer)}`)
const hash = await calcContentHash(content)
return hash
}
/** @type {(content: string, length?: number) => Promise<string>} */
export async function calcContentHash(content, length = 6) {
if (!content) throw new Error('calcContentHash: empty content')
return crypto.createHash('md5').update(content).digest('hex').substring(0, length)
}
/** @type {(filename: string, length?: number) => Promise<string>} */
async function calcFileHash(filename, length = 6) {
const content = await fs.readFile(filename)
return crypto.createHash('md5').update(content).digest('hex').substring(0, length)
}
<file_sep>/lib/commands/deploy.js
import { spawn } from "node:child_process"
/** @type {(config: Webo.Config) => Promise<Webo.CommandResult>} */
export default async function deploy(config) {
if (!config.output) return { exitCode: 1, message: 'output is not defined' }
if (!config.deployTo) return { exitCode: 1, message: 'deploy-to is not defined' }
const deployTo = parsePath(config.deployTo)
const serviceCommands = config.service ? `&& systemctl restart ${config.service} && systemctl status ${config.service}` : ''
const remoteCommands = `cd ${deployTo.dirpath} && npm i --omit=dev` + serviceCommands
try {
const spawnRSync = await spawnAsync(`rsync -avzu --delete --exclude node_modules/ ${config.output} ./package.json ./package-lock.json ${deployTo.fullpath}`)
} catch (/** @type {any} */error) {
return error
}
try {
const spawnRemoteCommands = await spawnAsync(remoteCommands, deployTo.origin)
if (spawnRemoteCommands.exitCode != 0) return spawnRemoteCommands
} catch (/** @type {any} */error) {
return error
}
log(`_GREEN_deploy completed successfully`)
return { exitCode: 0, message: `deploy successfully` }
}
/** @type {(fullpath: string) => { origin: string | undefined, dirpath: string, fullpath: string }} */
function parsePath(fullpath) {
const [p1, p2] = fullpath?.split(':')
let origin
let dirpath
if (!p2) {
dirpath = p1
} else {
origin = p1
dirpath = p2
}
return { origin, dirpath, fullpath }
}
/** @type {(command: string, origin?: string) => Promise<{ exitCode: number, message: string }>} */
async function spawnAsync(command, origin) {
const finalCommand = origin
? `ssh ${origin} ${command}`
: `${command}`
const [ cmd, ...rest ] = finalCommand.split(' ')
const sp = spawn(cmd, rest)
return new Promise((resolve, reject) => {
sp.stdout.on('data', (/** @type {Buffer} */data) => data.toString().split('\n').forEach(line => line ? log(`_GRAY_${line}`) : ''))
sp.stderr.on('data', (/** @type {Buffer} */data) => data.toString().split('\n').forEach(line => line ? log(`_RED_${line}`) : ''))
sp.on('close', code => { code === 0 ? resolve({ exitCode: 0, message: 'done' }) : reject({ exitCode: code, message: 'deploy failed' }) })
})
}
<file_sep>/lib/utils/utils.js
import path from 'node:path'
import fs from 'node:fs/promises'
import fss from 'node:fs'
const COLORS = {
GREEN: '\x1b[32m', RED: '\x1b[31m', YELLOW: '\x1b[33m', DIM: '\x1b[2m', CYAN: '\x1b[36m', GRAY: '\x1b[90m', LIGHTRED: '\x1b[91m', RESET: '\x1b[0m'
}
const extensionsSupported = ['html', 'css', 'js', 'mjs', 'vue']
/** @type {(verbose: boolean) => void} */
export function setGlobals(verbose) {
global.log = log
global.logv = verbose ? global.log : () => null
}
/** @type {(path: string) => boolean} */
export function parsable(path) {
if (typeof path !== 'string') return false
const filename = path.replace(/\\/g, '/').split('/').pop() ?? ''
const ext = filename.split('.').pop()
return !!ext && extensionsSupported.includes(ext)
}
/** @type {(filename: string) => string} */
export function relativePath(filename) {
return path.relative(path.resolve('.'), filename)
}
/** @type {(dir: string, type: 'file' | 'dir') => Promise<string[]>} */
export async function readdirp(dir, type) {
if (!type) throw new Error(`readdirp: type argument is required`)
if (!dir.endsWith(path.sep)) dir += path.sep
const entries = await fs.readdir(dir, { withFileTypes: true })
let files = []
if (type === 'dir') files.push(dir)
for await (const entry of entries) {
if (entry.isSymbolicLink()) continue
let entryPath = path.resolve(dir, entry.name)
if (entry.isDirectory()) {
files.push(... await readdirp(entryPath, type))
} else {
if (type === 'file') files.push(entryPath)
}
}
return files
}
/** @type {string[]} */
const _watchingDirs = []
/** @type {(dirnames: string[], listener: Function) => void} */
export function watchDirs(dirnames, listener) {
if (!dirnames) return
for (const dirname of dirnames) {
if (_watchingDirs.includes(dirname)) continue
_watchingDirs.push(dirname)
let lastrun = Date.now()
fss.watch(dirname, (eventType, filename) => {
const now = Date.now()
if (now < lastrun + 300) return
lastrun = now
const filepath = dirname + filename
setTimeout(() =>
fss.stat(filepath, (err, stat) => {
// check if modified in the last 3 seconds
if (err) {
if (err.code === 'ENOENT') {
return listener('remove', filepath)
} else {
throw err
}
}
if (stat.mtimeMs < now - 3 * 1000) return
if (stat.isFile()) {
return listener('change', filepath)
} else {
const dirpath = filepath.endsWith(path.sep) ? filepath : filepath + path.sep
// console.debug('DIR', {filepath, dirpath, eventType, filename})
watchDirs([ dirpath ], listener)
}
})
, 100)
})
}
}
/** @type {(message?: any, ...optionalParams: any[]) => void} */
function log(...args) {
const colorKeys = Object.keys(COLORS)
args.forEach(arg => {
const time = new Date().toISOString().split('T').pop()?.substring(3)
if (typeof arg === 'object') {
console.dir(arg)
} else {
let ret = arg.startsWith('\r') ? '\r' : ''
// @ts-ignore
colorKeys.forEach(clr => arg = arg.replace(new RegExp(`_${clr}_`, 'g'), COLORS[clr]).replace(/\r/g, ''))
process.stdout.write(`${ret}${COLORS.YELLOW}${time}${COLORS.RESET} : ${arg}${COLORS.RESET} `)
}
if (typeof args[args.length - 1] !== 'object') process.stdout.write('\n')
})
}
<file_sep>/lib/servers/webo-server.js
import path from 'node:path'
import { createHttpServer } from './webo-http-server.js'
import { createWebSocketServer } from './webo-websocket-server.js'
export const port = calcUniquePort()
export let webSockets = new Set
export function createWeboServer() {
const server = createHttpServer(port)
const { webSockets: sockets } = createWebSocketServer(server)
webSockets = sockets
}
function calcUniquePort() {
// define unique webo server port per project in a deterministic way
const localPath = path.resolve('.')
return 36000 + localPath.split('').map(o => o.charCodeAt(0)).reduce((sum,o) => sum += o, 0) % 1000
}
<file_sep>/lib/commands/init.js
import { spawn } from "node:child_process"
import * as fs from 'node:fs/promises'
const __dirname = new URL('.', import.meta.url).pathname
/** @type {(config: Webo.Config) => Promise<Webo.CommandResult>} */
export default async function init(config) {
const dirContent = await fs.readdir('.')
if (dirContent.filter(o => o !== '.git').length > 0) return { exitCode: 1, message: `cannot initialized: current directory is not empty` }
if (!config.template) return { exitCode: 1, message: 'template is not defined' }
const templates = await fs.readdir(__dirname + 'templates/')
if (!templates.includes(config.template)) return { exitCode: 1, message: `unknown template "${config.template}". Available templates: ${templates.join(', ')}` }
log(`initializing template "${config.template}"`)
try {
await spawnAsync(`rsync -a ${__dirname}templates/${config.template}/ .`)
} catch (/** @type {any} */error) {
return error
}
log(`_GREEN_init completed successfully`)
return { exitCode: 0, message: `init completed successfully` }
}
/** @type {(command: string, origin?: string) => Promise<{ exitCode: number, message: string }>} */
async function spawnAsync(command, origin) {
const finalCommand = origin
? `ssh ${origin} ${command}`
: `${command}`
const [ cmd, ...rest ] = finalCommand.split(' ')
const sp = spawn(cmd, rest)
return new Promise((resolve, reject) => {
sp.stdout.on('data', (/** @type {Buffer} */data) => data.toString().split('\n').forEach(line => line ? log(`_GRAY_${line}`) : ''))
sp.stderr.on('data', (/** @type {Buffer} */data) => data.toString().split('\n').forEach(line => line ? log(`_RED_${line}`) : ''))
sp.on('close', code => { code === 0 ? resolve({ exitCode: 0, message: 'done' }) : reject({ exitCode: code, message: 'deploy failed' }) })
})
}
<file_sep>/lib/commands/templates/esma/src/server/server.js
import esma from 'esma'
const server = esma.createServer()
const port = process.env.NODE_PORT || 3000
const __dirname = new URL('.', import.meta.url).pathname
server.use(esma.static(__dirname + '../client', { extensions: ['html'] }))
server.listen(port, () => console.log('listening', port))<file_sep>/webo.d.ts
export async function webo(config: Webo.Config, nodeArgs: any): Promise<void>
declare global {
namespace Webo {
type Command = 'dev' | 'build' | 'config' | 'deploy' | 'init'
type ProjectTypes = 'static' | 'user'
type FileTypes = 'html' | 'css' | 'js-module' | 'js-script' | 'js-legacy' | 'vue' | 'raw' | 'dev-dep'
interface Config {
version: string
command: Command,
userEntry: string,
serverRoots: string[],
clientRoots: string[],
watchServer: boolean,
watchClient: boolean,
bundle: boolean,
transpile: boolean,
minify: boolean,
legacy: boolean,
cachebust: boolean,
output: string,
deployTo: string,
service: string,
template: string
verbose: boolean,
projectType?: ProjectTypes,
showConfig?: boolean,
debug?: boolean,
}
interface CommandResult {
exitCode: number,
message: string,
}
interface File {
type: FileTypes | null,
content?: string,
deps: FileDeps,
hash?: string,
parseCount: number,
}
interface FileDeps {
[filename: string]: { type: FileTypes }
}
}
function log(message?: any, ...optionalParams: any[]): void
function logv(message?: any, ...optionalParams: any[]): void
}<file_sep>/lib/processes/userProcess/static-server.js
import http from 'node:http'
import path from 'node:path'
import fs from 'node:fs'
import { stat, readdir } from 'node:fs/promises'
import mime from 'mime'
export function createStaticServer() {
return http.createServer(staticRequestHandler).listen(3000, () => console.log('listening 3000'))
}
/** @type {http.RequestListener} */
async function staticRequestHandler(req, res) {
// console.debug(req.url)
const relpath = req.url?.split('?')[0]
let filepath = path.resolve('.' + relpath)
let stats = await tryStat(filepath)
if (stats?.isDirectory()) {
stats = await tryStat(path.join(filepath, 'index.html'))
if (stats) {
filepath = path.join(filepath, 'index.html')
} else {
const dirContent = await dirListing(filepath)
res.setHeader('Content-Type', 'text/html')
res.end(dirContent)
return
}
}
if (!stats) {
res.statusCode = 404
res.end()
return
}
let ext = filepath.split('.').pop()
const mimeType = mime.getType(ext ?? '')
if (mimeType) res.setHeader('Content-Type', mimeType)
const stream = fs.createReadStream(filepath)
stream.pipe(res)
}
/** @type {(filename: string) => Promise<any>} */
async function tryStat(filename) {
try {
return await stat(filename)
} catch (error) {
return null
}
}
/** @type {(dirpath: string) => Promise<string>} */
async function dirListing(dirpath) {
let dirs = ''
let files = ''
const entries = await readdir(dirpath, { withFileTypes: true })
for (const entry of entries) {
if (entry.isDirectory()) {
dirs += /*html*/`<div><a href="/${entry.name}/">${entry.name}/<a></div>`
} else {
files += /*html*/`<div><a href="/${entry.name}">${entry.name}<a></div>`
}
}
return /*html*/`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>webo index</title>
<style>
section > div { padding: .1rem 1rem; border-bottom: solid 1px #ddd; }
</style>
</head>
<body>
<h1>index of ${dirpath}</h1>
<section class="dirs">
${dirs}
</section>
<section class="files">
${files}
</section>
</body>
</html>
`
}<file_sep>/lib/commands/dev.js
import path from 'node:path'
import { createUserProcess } from '../processes/process-manager.js'
import { watchServer, watchClient } from '../utils/watchers.js'
import { createWeboServer } from '../servers/webo-server.js'
/** @type {(config: Webo.Config, nodeArgs: string) => Promise<Webo.CommandResult>} */
export default async function dev(config, nodeArgs) {
const userEntryPath = path.resolve(config.userEntry)
const userEntryUrl = new URL(`file:///${userEntryPath}`).href
const userProcess = createUserProcess(userEntryUrl, nodeArgs, config)
if (config.watchClient) {
createWeboServer()
watchClient(config.clientRoots, config.cachebust)
}
if (config.watchServer) watchServer(config.serverRoots)
return new Promise(resolve => {
process.on('SIGINT', () => {
log('\r_GREEN_webo ended by user');
userProcess.kill();
resolve({ exitCode: 0, message: '' })
})
})
}
<file_sep>/lib/parsers/types/html.js
import path from 'node:path'
import fs from 'node:fs/promises'
import * as html from 'syn-html-parser'
import { cachebust } from '../tools/cachebuster.js'
import { port } from '../../servers/webo-server.js'
/** @type {(source: string, filename: string, config: Webo.Config) => Promise<{ content: string, deps: Webo.FileDeps }>} */
export async function parse(source, filename, config) {
let content = source
if (config.watchClient) {
content = source.replace('</body>', /*html*/`
<script>
var weboSocketScript = document.createElement('script');
weboSocketScript.src = location.origin.replace(location.port, '${port}') + '/webo-socket.js';
document.body.appendChild(weboSocketScript)
</script>
</body>`)
}
// include bracket imports [[ ../_partial.html ]]
const { contentWithPartials, partials } = await includeBracketPartials(content, filename)
if (Object.keys(partials).length) {
content = contentWithPartials
}
const doc = content.includes('<!DOCTYPE html>') ? html.parseHtml(content) : html.parseFragment(content)
await weboAttributes(doc, config.command === 'build' ? 'production' : 'development')
if (config.legacy) {
const scripts = await createLegacyScripts(doc)
if (scripts.length > 0) {
const weboEnvScript = html.createElement('script', { src: '/webo-env.min.js', nomodule: '' })
html.insertBefore(weboEnvScript, scripts[0])
}
}
const refs = await detectRefs(doc, path.dirname(filename))
if (config.cachebust) {
await cacheBusting(doc, filename, config, refs)
}
return { content: html.serialize(doc), deps: { ...partials, ...refs } }
}
/** @type {(source: string, filename: string) => Promise<{contentWithPartials: string, partials: any}>} */
async function includeBracketPartials(source, filename) {
let contentWithPartials = source
let match
/** @type {any} */
const partials = {}
const re = /\[\[\s*import\s*(?<path>.*)\s*\]\]/g
while (match = re.exec(contentWithPartials)) {
const relPartialPath = match.groups?.path.trim() ?? ''
const partialPath = path.join(path.dirname(filename), relPartialPath)
partials[partialPath] = { type: 'dev-dep' }
let partialContent = await fs.readFile(partialPath, 'utf-8')
const partialDoc = html.parseFragment(partialContent)
const partialDir = path.dirname(relPartialPath)
partialContent = await rewritePartials(partialDoc, partialDir)
const [ before, after ] = contentWithPartials.split(match[0])
contentWithPartials = [ before, partialContent, after ].join('')
// console.debug(match.groups.path, path.join(path.dirname(filename), match.groups.path))
}
return { contentWithPartials, partials }
}
/** @type {(doc: html.ParentNode, dir: string) => Promise<Webo.FileDeps>} */
async function detectRefs(doc, dir) {
/** @type {any} */
const refs = {}
html.qsa(doc, el => {
if (el.tagName === 'script') {
const attribs = html.getAttributes(el)
if (!attribs['src'] || attribs['src'].includes('//')) return false
const src = attribs['src'].trim().split('?')[0]
let type = 'js-script'
if (attribs['nomodule']) type = 'js-legacy'
if (attribs['type'] === 'module') type = 'js-module'
if (src.includes('.min.')) type = 'raw'
refs[path.join(dir, src)] = { type }
}
if (el.tagName === 'link') {
const attribs = html.getAttributes(el)
if (attribs['rel'] !== 'stylesheet' || !attribs['href'] || attribs['href'].includes('//')) return false
refs[path.join(dir, attribs['href'].trim().split('?')[0])] = { type: 'css' }
}
return false
})
return refs
}
/** @type {(doc: html.ParentNode, currentEnv: 'production' | 'development') => Promise<void>} */
async function weboAttributes(doc, currentEnv) {
const els = html.qsa(doc, el => !!html.getAttributes(el)['webo-env'])
await Promise.all(
els.map(el => {
const attribs = html.getAttributes(el)
if (attribs['webo-env'] !== currentEnv) {
html.detachNode(el)
} else {
delete attribs['webo-env']
}
})
)
}
/** @param {html.ParentNode} doc */
async function createLegacyScripts(doc) {
const scriptElements = html.qsa(doc, el => {
const attribs = html.getAttributes(el)
return el.tagName === 'script' && attribs['type'] === 'module' && 'src' in attribs && !attribs['src']?.includes('.min.') && !attribs['src']?.includes('//')
})
scriptElements.map(el => {
const attribs = html.getAttributes(el)
const src = attribs['src']
if (!src) return
const legacyScript = html.createElement('script', { src: src.replace(/\.(m?js)$/, '.legacy.$1'), nomodule: '', defer: '' })
html.insertBefore(legacyScript, el)
})
return scriptElements
}
/** @type {(doc: html.ParentNode, filename: string, config: Webo.Config, htmlRefs: Webo.FileDeps) => Promise<void>} */
async function cacheBusting(doc, filename, config, htmlRefs) {
const dir = path.dirname(filename)
const refs = html.qsa(doc, el => [ 'script', 'link', 'img' ].includes(el.tagName))
await Promise.all(
refs.map(async el => {
const attribs = html.getAttributes(el)
if (el.tagName === 'script' && !attribs['src']) return
if (el.tagName === 'link' && attribs['rel'] !== 'stylesheet' && !attribs['rel']?.includes('icon')) return
if (el.tagName === 'img' && !attribs['src']) return
const attr = 'src' in attribs ? 'src' : 'href'
const uri = attribs[attr]
if (!uri) throw new Error(`cacheBusting error`)
const ref = uri.split('?')[0]
if (ref.startsWith('http://') || ref.startsWith('https://') || ref.startsWith('//')) return
const refPath = path.join(dir, ref)
const { type } = htmlRefs[refPath] || {}
if (ref.includes('//')) return
const ext = ref.split('.').pop()
if (!ext) return
const hash = await cachebust(path.join(dir, ref), config, { type, referrer: filename })
let newRef = [ref.substring(0, ref.length - ext.length - 1), hash, ext].filter(Boolean).join('.')
const refAttr = el.attrs.find(o => o.name === attr)
if (refAttr) {
refAttr.value = newRef
}
})
)
}
/** @type {(doc: html.ParentNode, relPath: string) => Promise<string>} */
async function rewritePartials(doc, relPath) {
const partialRefs = html.qsa(doc, el => [ 'script', 'link', 'img' ].includes(el.tagName))
await Promise.all(
partialRefs.map(async el => {
const attribs = html.getAttributes(el)
if (el.tagName === 'script' && !attribs['src']) return
if (el.tagName === 'link' && attribs['rel'] !== 'stylesheet' && !attribs['rel']?.includes('icon')) return
if (el.tagName === 'img' && !attribs['src']) return
const attr = 'src' in attribs ? 'src' : 'href'
const uri = attribs[attr]
if (!uri) throw new Error(`rewritePartials error`)
const ref = uri.split('?')[0]
if (ref.startsWith('http://') || ref.startsWith('https://') || ref.startsWith('//')) return
const refNew = path.join(relPath, ref)
const refAttr = el.attrs.find(o => o.name === attr)
if (refAttr) {
refAttr.value = refNew
}
// console.log(el.name, ref, attr, path.join(partialDir, ref))
})
)
return html.serialize(doc)
}<file_sep>/lib/parsers/types/css.js
import path from 'node:path'
import { cachebust } from '../tools/cachebuster.js'
/** @type {(source: string, filename: string, config: Webo.Config) => Promise<{ content: string }>} */
export async function parse(source, filename, config) {
let content = source
if (config.cachebust) {
content = await cacheBusting(content, filename, config)
}
return { content }
}
const reStripComments = /(?!<\")\/\*[^\*]+\*\/(?!\")/g
const reRefs = /url\((?<ref>.+?)\)/g
/** @type {(content: string, filename: string, config: Webo.Config) => Promise<string>} */
async function cacheBusting(content, filename, config) {
const dir = path.dirname(filename)
const contentWithoutComments = content.replaceAll(reStripComments, '')
const matches = contentWithoutComments.matchAll(reRefs)
for await (const match of matches) {
const ref = match.groups?.ref.trim().replaceAll("'", '').replaceAll('"', '').split('?')[0].split('#')[0]
if (!ref) continue
if (ref.startsWith('http://') || ref.startsWith('https://') || ref.startsWith('/') || ref.startsWith('data:')) continue
const ext = ref.split('.').pop()
if (!ext) continue
const hash = await cachebust(path.join(dir, ref), config, { referrer: filename, ignoreIfMissing: ignoreIfMissing(ext) })
const refFinal = [ref.substring(0, ref.length - ext.length - 1), hash, ext].filter(Boolean).join('.')
content = content.replaceAll(ref, refFinal)
}
return content
}
/** @type {(ext: string) => boolean} */
function ignoreIfMissing(ext) {
return ['eot', 'woff', 'ttf', 'svg'].includes(ext)
}
<file_sep>/lib/parsers/tools/_parse5.js
/**
* @typedef {Object} Node
* @property {string} type
* @property {string} name
* @property {{[key: string]: string}} attribs
* @property {Node[]} children
* @property {'http://www.w3.org/1999/xhtml'} namespace
* @property {'http://www.w3.org/1999/xhtml'} [x-attribsNamespace]
* @property {'http://www.w3.org/1999/xhtml'} [x-attribsPrefix]
* @property {Node?} parent
* @property {Node?} prev
* @property {Node?} next
*/
import * as parse5 from 'parse5'
import * as htmlparser2Adapter from 'parse5-htmlparser2-tree-adapter'
/** @type {(html: string) => Node})} */
export function parseHtml(html) {
return parse5.parse(html, { treeAdapter: htmlparser2Adapter })
}
/** @type {(html: string) => Node})} */
export function parseFragment(html) {
return parse5.parseFragment(html, { treeAdapter: htmlparser2Adapter })
}
/** @type {(document: Node) => string})} */
export function serialize(document) {
return parse5.serialize(document, { treeAdapter: htmlparser2Adapter })
}
/** @type {(node: Node, predicate: (el: Node) => boolean) => Node | undefined})} */
export function qs(node, predicate) {
let result
if (predicate(node)) {
result = node
} else {
if (node.children) {
for (let child of node.children) {
result = qs(child, predicate)
if (result) break
}
}
}
return result
}
/** @type {(node: Node, predicate: (el: Node) => boolean, res?: Node[]) => Node[]})} */
export function qsa(node, predicate, res = []) {
if (predicate(node)) res.push(node)
if (node.children) node.children.forEach(child => qsa(child, predicate, res))
return res
}
/** @type {(node: Node, fn: (el: Node) => void) => void})} */
export function walk(node, fn) {
fn(node)
if (node.children) node.children.forEach(child => walk(child, fn))
}
/** @type {(type: string, attributes: any) => Node} */
export function createElement(type, attributes = {}) {
return {
type,
name: type,
namespace: 'http://www.w3.org/1999/xhtml',
attribs: Object.create(null, Object.getOwnPropertyDescriptors(attributes)),
['x-attribsNamespace']: Object.create(null, { src: {}, type: {} }),
['x-attribsPrefix']: Object.create(null, { src: {}, type: {} }),
children: [],
parent: null,
prev: null,
next: null
}
}
/** @type {(newChild: Node, refChild: Node) => void} */
export function insertBefore(newChild, refChild) {
if (!newChild || !refChild) throw new Error('missing parameter')
newChild.parent = refChild.parent
refChild.parent?.children.splice(refChild.parent.children.indexOf(refChild), 0, newChild)
const oldSibbling = refChild.next
refChild.next = newChild
newChild.prev = refChild
newChild.next = oldSibbling
}
/** @type {(el: Node) => void} */
export function remove(el) {
if (!el) throw new Error('missing parameter')
el.parent?.children.splice(el.parent.children.indexOf(el), 1)
if (el.prev) el.prev.next = el.next
if (el.next) el.next.prev = el.prev
}<file_sep>/lib/parsers/tools/bundler.js
import fs from 'node:fs/promises'
import { rollup } from 'rollup'
import { parse as parseVue } from '../types/vue.js'
import { calcContentHash } from './cachebuster.js'
/** @type {(filename: string, config: Webo.Config, options: { format?: 'esm' | 'iife' }) => Promise<{ content: string, deps: Webo.FileDeps }>} */
export async function bundle(filename, config, options = { format: undefined }) {
const outputOptions = { format: options.format, name: '' }
if (options.format === 'iife') outputOptions.name = '__BUNDLE_NAME__'
const plugins = [ vuePlugin(config) ]
let rollupBundle
try {
rollupBundle = await rollup({
input: filename,
plugins,
onwarn: warning => console.log('ROLLUP', filename, warning),
})
} catch (error) {
log(`_RED_Bundler parse error`)
// @ts-ignore
log(`_RED_${error.loc.file} _GRAY_(col:${error.loc.column}, line:${error.loc.line})`)
// @ts-ignore
error.frame.split('\n').map(l => log(`_GRAY_${l}`))
if (config.command === 'build') throw new Error('PARSE ERROR')
return { content: '', deps: {} }
}
const { output } = await rollupBundle.generate({ format: options.format })
const { code, modules } = output[0]
const bundleName = 'webo_' + await calcContentHash(code)
const deps = Object.keys(modules).filter(m => m !== filename)
.reduce((/**@type {any}}*/flat, m) => { flat[m] = { type: 'dev-dep' }; return flat }, {})
return { content: code.replace(/__BUNDLE_NAME__/g, bundleName), deps }
}
/** @type {(filename: string) => Promise<any>} */
export async function getResolvedIds(filename) {
try {
const rollupBundle = await rollup({
input: filename,
onwarn: warning => console.log('ROLLUP', filename, warning),
})
return rollupBundle.cache?.modules?.find(o => o.id === filename)?.resolvedIds ?? {}
} catch (error) {
log(`_LIGHTRED_${error}`)
return {}
}
}
/** @type {(config: Webo.Config) => any} */
function vuePlugin(config) {
return {
name: 'vue-plugin',
/** @type {(id: string) => Promise<string | undefined>} */
async load(id) {
if (!(id.endsWith('.vue'))) return undefined
const source = await fs.readFile(id, 'utf8')
let { content } = await parseVue(source, id, config)
return content
}
}
}
<file_sep>/lib/parsers/types/vue.js
import * as html from 'syn-html-parser'
import { transpile } from '../tools/transpiler.js'
import { minify } from '../tools/minifier.js'
/** @type {(source: string, filename: string, config: Webo.Config) => Promise<{ content: string }>} */
export async function parse(source, filename, config) {
let result = { content: source }
const document = html.parseFragment(`${source.replace(/<template/g, '<vue-template').replace(/<\/template>/g, '<\/vue-template>')}`)
const templateEl = html.qs(document, el => el.tagName === 'vue-template')
const template = templateEl ? html.serialize(templateEl) : ''
const scriptEl = html.qs(document, el => el.tagName === 'script')
const script = scriptEl ? html.serialize(scriptEl) : 'export default {}'
result.content = script.replace('export default {', `export default {\n template: \`${template}\`,\n `)
if (config.transpile) {
const transpileResult = await transpile(result.content, { presetName: 'transpileModern' })
Object.assign(result, transpileResult)
}
if (config.minify) {
const minifyResult = await minify(result.content)
Object.assign(result, minifyResult)
}
return result
}
<file_sep>/lib/servers/webo-http-server.js
import fs from 'node:fs'
import http from 'node:http'
const __dirname = new URL('.', import.meta.url).pathname
/** @type {string} */
let weboSocketClient
/** @type {(port: number) => http.Server} */
export function createHttpServer(port) {
weboSocketClient = fs.readFileSync(__dirname + '/webo-socket.js', 'utf8').replace('[WS_PORT]', String(port))
return http.createServer(requestHandler).listen(port, '127.0.0.1')
}
/** @type {http.RequestListener} */
function requestHandler(req, res) {
if (req.url === '/webo-socket.js') {
res.setHeader('Content-Type', 'application/javascript')
res.end(weboSocketClient)
return
}
res.statusCode = 404
res.end()
}
<file_sep>/lib/parsers/files.js
import * as staticFiles from './static/static.js'
/** @type {{[filename: string]: Webo.File}} */
export const files = {}
/** @type {(filename: string) => Webo.File} */
export function getFile(filename) {
let file = files[filename]
if (!file) {
file = files[filename] = createFile()
}
if (file.content) return file
const staticContent = staticFiles.getFile(filename.replace(/\\/g, '/').split('/').pop() ?? '')
if (staticContent) {
Object.assign(file, { content: staticContent, type: 'raw' })
}
return file
}
/** @type {(deps: Webo.FileDeps) => void} */
export function attachFiles(deps) {
for (const [filename, file] of Object.entries(deps)) {
if (!files[filename]) {
files[filename] = { ...createFile(), ...file }
} else {
if (file.type !== 'dev-dep' && files[filename].type !== file.type) {
files[filename] = { ...createFile(), ...file }
}
}
}
}
/** @type {(filename: string, source: string) => Webo.FileTypes} */
export function detectType(filename, source) {
if (/\.legacy\.m?js/.test(filename)) return 'js-legacy'
if (filename.includes('.min.')) return 'raw'
const ext = filename.split('.').pop() ?? ''
if (ext === 'html' || ext === 'css' || ext === 'vue') return ext
if (ext === 'mjs') return 'js-module'
if (ext === 'js') return detectJsType(source)
return 'raw'
}
export function createFile() {
return {
type: null,
content: undefined,
deps: {},
hash: undefined,
parseCount: 0,
}
}
/** @type {(source: string) => 'js-module' | 'js-script'} */
function detectJsType(source) {
if (/(^|\n)\s*\bexport\b/.test(source)) return 'js-module'
return 'js-script'
}
<file_sep>/lib/parsers/types/js-legacy.js
import { bundle } from '../tools/bundler.js'
import { transpile } from '../tools/transpiler.js'
import { minify } from '../tools/minifier.js'
/** @type {(source: string, filename: string, config: Webo.Config) => Promise<{ content: string }>} */
export async function parse(source, filename, config) {
const sourceFilename = filename.replace('.legacy.', '.')
let result = { content: source }
const bundleResult = await bundle(sourceFilename, config, { format: 'iife' })
Object.assign(result, bundleResult)
const transpileResult = await transpile(result.content, { presetName: 'transpileLegacy' })
Object.assign(result, transpileResult)
if (config.minify) {
const minifyResult = await minify(result.content)
Object.assign(result, minifyResult)
}
return result
}<file_sep>/backlog.md
# to do
syn-html-parser
img: add width and height
# for thought
inline scripts process?
<file_sep>/lib/utils/autodetect.js
import path from 'node:path'
import fs from 'node:fs'
import fsp from 'node:fs/promises'
/** @type {(config: Webo.Config) => Promise<Webo.ProjectTypes>} */
export async function detectProjectType(config) {
if (!config.userEntry) return 'user'
const userEntryPath = path.resolve(config.userEntry)
const isStatic = (await fsp.stat(userEntryPath)).isDirectory()
return isStatic ? 'static' : 'user'
}
export async function detectRoots() {
const serverRoots = []
const clientRoots = []
process.stdout.write('Auto detecting roots...')
if (fs.existsSync(path.resolve('src/server')) && fs.existsSync(path.resolve('src/client'))) {
serverRoots.push(path.resolve('src/server/'))
clientRoots.push(path.resolve('src/client/'))
}
console.log(serverRoots.length ? `${serverRoots.length + clientRoots.length} found` : 'not found')
return { serverRoots, clientRoots }
}
<file_sep>/readme.md
webo is a development server and a build tool for the web.
## installation
install webo as dev dependency
```console
$ npm i -D webo
```
## features
* live reloading when a resource is changed (saved)
* autopatching css styles without reloading when changing a css file
* building with optionally bundling, transpiling, minifying and cache busting
## usage
### development
if you have the following file structure:
```
src
client
index.html
styles.css
...
server
server.js
```
you can run (or put it in a package.json script wihtout npx)
```console
$ npx webo dev src/server/server.js -s src/server -c src/client
```
-s flag marks the directory as server-side content
-c flag marks the directory as client-side content
### build
to build your project :
```console
$ npx webo build --cachebust -s src/server -c src/client
```
the above will put the outputs in a ```dist/``` directory.
You can check all the command-line options in ```webo-config.js```
<file_sep>/lib/parsers/tools/minifier.js
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
/** @type {any} */
let terser
/** @type {(content: string) => Promise<{ content: string }>} */
export async function minify(content) {
if (!terser) terser = require(require.resolve('terser', { paths: [ process.cwd() ] }))
const { code, error } = await terser.minify(content)
if (error) log(error)
return { content: code }
}<file_sep>/lib/parsers/static/static.js
import fs from 'node:fs'
const __dirname = new URL('.', import.meta.url).pathname
/** @type {{[filename: string]: string}} */
let staticFiles = {}
/** @type {(filename: string) => string} */
export function getFile(filename) {
if (!staticFiles) load()
return staticFiles[filename]
}
function load() {
let babelPolyfill = ''
try {
babelPolyfill = fs.readFileSync(require.resolve('@babel/polyfill/dist/polyfill.min.js', { paths: [ process.cwd() ] }), 'utf8')
} catch (error) {}
const weboEnv = fs.readFileSync(__dirname + '/webo-env.min.js', 'utf8')
staticFiles = {
'webo-env.min.js': [ babelPolyfill, weboEnv ].join('\n\n')
}
}<file_sep>/lib/utils/watchers.js
import { readdirp, watchDirs, relativePath } from './utils.js'
import { restartUserProcess } from '../processes/process-manager.js'
import { webSockets } from '../servers/webo-server.js'
let cachebust = false
/** @type {(serverRoots: string[]) => Promise<void>} */
export async function watchServer(serverRoots) {
const serverDirs = (await Promise.all(serverRoots.map(root => readdirp(root, 'dir')))).flat()
watchDirs(serverDirs, serverWatcher)
}
/** @type {(clientRoots: string[], usingCachebust: boolean) => Promise<void>} */
export async function watchClient(clientRoots, usingCachebust) {
cachebust = usingCachebust
const clientDirs = (await Promise.all(clientRoots.map(root => readdirp(root, 'dir')))).flat()
watchDirs(clientDirs, clientWatcher)
}
/** @type {(event: any, filename: string) => Promise<void>} */
async function serverWatcher(event, filename) {
if (filename.replace(/\\/g, '/').split('/').pop()?.startsWith('.')) return
log(`_GREEN_${relativePath(filename)}`)
restartUserProcess()
}
/** @type {(event: any, filename: string) => Promise<void>} */
async function clientWatcher(event, filename) {
const filenameBare = filename.replace(/\\/g, '/').split('/').pop()
if (!filenameBare || filenameBare.startsWith('.')) return
log(`_GREEN_${relativePath(filename)}`)
;[... webSockets].filter(o => o.readyState === 1).forEach(socket => socket.send(cachebust ? 'reload' : 'changed ' + filenameBare))
}
<file_sep>/lib/processes/userProcess/userHost.js
import './patch-fs.js'
import { createStaticServer } from './static-server.js'
const [ userEntry, type ] = process.argv.splice(2)
// @ts-ignore
process.on('unhandledRejection', (reason, p) => process.send({ error: reason?.stack ?? reason }))
async function run() {
if (type === 'user') {
return await import(userEntry)
}
if (type === 'static') {
return createStaticServer()
}
throw new Error(`Unkown project type ${type}`)
}
run()
<file_sep>/lib/processes/process-manager.js
import * as cp from 'node:child_process'
import { parse } from '../parsers/parser.js'
const __dirname = new URL('.', import.meta.url).pathname
/** @type {cp.ChildProcess} */
let userProc
/** @type {[userEntry: string, nodeArgs: string, config: Webo.Config]} */
let userProcArgs
/** @type {(userEntry: string, nodeArgs: string, config: Webo.Config) => cp.ChildProcess} */
export function createUserProcess(userEntry, nodeArgs, config) {
userProcArgs = [ userEntry, nodeArgs, config ]
userProc = cp.fork(
__dirname + 'userProcess/userHost.js',
[ userEntry, config.projectType ?? '' ],
{ execArgv: nodeArgs ? nodeArgs.split(' ') : undefined, env: {} }
)
logv(`_CYAN_[ user process ${userProc.pid} ${userEntry} ]_RESET_`)
// @ts-ignore
userProc.on('message', async ({ id, path, error }) => {
if (error) return onProcessError(error)
const { content } = await parse(path, config)
userProc.send({ id, path, content })
})
process.on('exit', onProcessExit)
return userProc
}
export function restartUserProcess() {
onProcessExit()
userProc = createUserProcess(...userProcArgs)
}
function onProcessExit() {
process.removeListener('exit', onProcessExit)
userProc.kill()
}
/** @type {(message: string) => void} */
function onProcessError(message) {
log(`_RED_${message}`)
}<file_sep>/lib/parsers/tools/transpiler.js
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
/** @type {any} */
let babel
/** @type {any} */
let babelPresets
/** @type {(content: string, options: { presetName: 'transpileModern' | 'transpileLegacy' }) => Promise<{ content: string }>} */
export async function transpile(content, { presetName }) {
if (!babel) babel = require(require.resolve('@babel/core', { paths: [ process.cwd() ] }))
if (!babelPresets) babelPresets = {
transpileLegacy: [[ require.resolve('@babel/preset-env', { paths: [ process.cwd() ] }), { modules: false }]],
transpileModern: [[ require.resolve('@babel/preset-env', { paths: [ process.cwd() ] }), { modules: false, targets: { chrome: 61, safari: '10.1', edge: 16 } }]],
}
const options = { presets: babelPresets[presetName] }
const { code } = await babel.transform(content, options)
return { content: code }
}<file_sep>/lib/config.js
import fs from 'node:fs/promises'
import { createRequire } from 'node:module'
import path from 'node:path'
import { parseArgs } from 'node:util'
const require = createRequire(import.meta.url)
const version = await getVersion()
/** @type {() => { config: Webo.Config, nodeArgs: string }} */
export function createConfig() {
const { values, command, userEntry, nodeArgs } = getUserOptions()
const overrides = configOverrides[command]
renameProperty(values, 'server-root', 'serverRoots')
renameProperty(values, 'client-root', 'clientRoots')
renameProperty(values, 'watch-server', 'watchServer')
renameProperty(values, 'watch-client', 'watchClient')
renameProperty(values, 'show-config', 'showConfig')
renameProperty(values, 'deploy-to', 'deployTo')
/** @type { Webo.Config } */
const config = { ...baseConfig, command, userEntry, ...overrides, ...values }
config.serverRoots = config.serverRoots.map(o => path.resolve(o))
config.clientRoots = config.clientRoots.map(o => path.resolve(o))
if (values['preset-build']) config.bundle = config.transpile = config.minify = config.cachebust = config.legacy = true
config.version = version
return { config, nodeArgs }
}
const baseConfig = {
command: '',
userEntry: '',
serverRoots: [],
clientRoots: [],
watchServer: false,
watchClient: false,
bundle: false,
transpile: false,
minify: false,
legacy: false,
cachebust: false,
output: '',
deployTo: '',
service: '',
verbose: false,
}
const configOverrides = {
dev: {
watchServer: true,
watchClient: true,
},
build: {
output: 'dist/'
},
deploy: {
output: 'dist/'
},
init: {
},
config: {
},
}
/** @type {() => { values: any, command: Webo.Command, userEntry: string, nodeArgs: string }} */
function getUserOptions() {
const options = {
'version': { type: 'boolean', short: 'v' },
'server-root': { type: 'string', short: 's', multiple: true },
'client-root': { type: 'string', short: 'c', multiple: true },
'watch-server': { type: 'boolean' },
'watch-client': { type: 'boolean' },
'watch': { type: 'boolean' },
'bundle': { type: 'boolean' },
'transpile': { type: 'boolean' },
'minify': { type: 'boolean' },
'cachebust': { type: 'boolean' },
'legacy': { type: 'boolean' },
'output': { type: 'string' },
'deploy-to': { type: 'string' },
'service': { type: 'string' },
'template': { type: 'string' },
'verbose': { type: 'boolean' },
'debug': { type: 'boolean' },
'show-config': { type: 'boolean' },
'preset-dev': { type: 'boolean' },
'preset-build': { type: 'boolean' },
}
const { values, positionals } = parseArgs({ options, allowPositionals: true })
const [ command, userEntry, ...restArgs ] = positionals
const nodeArgs = restArgs.join(' ').split('--').pop()?.trim() ?? ''
if (values.version) return logAndExit(`webo v${version}`, 0)
if (!command) return logAndExit(`Usage: webo command [entry] [flags]\n Commands: dev, build, deploy, init, config\n Flags : ${Object.keys(options)}`, 1)
if (command !== 'dev' && command !== 'build' && command !== 'deploy' && command !== 'init' && command !== 'config') return logAndExit(`Unknown command '${command}'\nCommands allowed : dev, build, deploy, init, config`, 1)
if (command === 'dev' && !userEntry) return logAndExit(`Entry is required for 'dev' command.\nwebo dev [entry]`, 1)
let missingDeps = ''
if (values.transpile || values.legacy) {
missingDeps += checkForMissingDeps('@babel/core', '--transpile or --legacy')
missingDeps += checkForMissingDeps('@babel/preset-env', '--transpile or --legacy')
missingDeps += checkForMissingDeps('@babel/polyfill', '--transpile or --legacy')
}
if (values.minify) missingDeps += checkForMissingDeps('terser', '--minify')
if (missingDeps) return logAndExit(missingDeps, 1)
return { values, command, userEntry, nodeArgs }
}
/** @type {(obj: {[key: string]: any}, oldName: string, newName: string) => void} */
function renameProperty(obj, oldName, newName) {
if (!Object.hasOwn(obj, oldName)) return
obj[newName] = obj[oldName]
delete obj[oldName]
}
/** @type {(errorMessage: string, statusCode: number) => any} */
function logAndExit(errorMessage, statusCode) {
console.log(errorMessage)
process.exit(statusCode)
}
/** @type {(moduleName: string, switchName: string) => string} */
function checkForMissingDeps(moduleName, switchName) {
try {
require.resolve(moduleName, { paths: [ process.cwd() ] })
return ''
} catch (error) {
return `To use ${switchName} switch you must install ${moduleName}. Run 'npm i -D ${moduleName}'\n`
}
}
async function getVersion() {
const __dirname = new URL('.', import.meta.url).pathname
const pkg = await fs.readFile(__dirname + '../package.json', 'utf8')
const json = JSON.parse(pkg)
return json.version
}
<file_sep>/lib/commands/build.js
import path from 'node:path'
import { promises as fs} from'node:fs'
import { readdirp } from'../utils/utils.js'
import { relativePath } from'../utils/utils.js'
import { parse } from'../parsers/parser.js'
import { files } from'../parsers/files.js'
import { parsable } from'../utils/utils.js'
/** @type {string[]} */
const destFilenames = []
/** @type {string[]} */
const serverFiles = []
/** @type {(config: Webo.Config) => Promise<Webo.CommandResult>} */
export default async function build(config) {
if (!config.output) return { exitCode: 1, message: 'output is not defined' }
if (!config.serverRoots.length) return { exitCode: 1, message: 'serverRoots not defined' }
if (!config.clientRoots.length) return { exitCode: 1, message: 'clientRoots not defined' }
const buildStarted = Date.now()
const dest = path.resolve(config.output)
await fs.mkdir(dest, { recursive: true })
const srcRoots = [ ...config.serverRoots, ...config.clientRoots ]
const destFilenamesOrig = await readdirp(dest, 'file')
/** @type {string[]} */
const srcFiles = []
// client files
await Promise.all(
config.clientRoots.map(async srcRoot => srcFiles.push(... await readdirp(srcRoot, 'file')))
)
// parse html files
await Promise.all(
srcFiles.filter(o => o.endsWith('.html')).map(srcFile => parse(srcFile, config, { cacheContent: true }))
)
logv(`_GRAY_${srcFiles.filter(o => o.endsWith('.html')).length} html files parsed`)
// parse module entries
await Promise.all(
Object.keys(files).filter(k => files[k].type === 'js-module').map(k => parse(k, config, { cacheContent: true }))
)
// parse rest parsable files
await Promise.all(
srcFiles.filter(o => parsable(o) && !files[o]?.content).map(srcFile => parse(srcFile, config, { cacheContent: true }))
)
// parse virtual files
await Promise.all(
Object.keys(files).filter(k => parsable(k) && !files[k].content).map(k => parse(k, config, { cacheContent: true }))
)
logv(`_GRAY_copying files...`)
// copy parsable files
await Promise.all(
Object.entries(files).map(async ([k ,v]) => {
if (v?.type === 'dev-dep') return
const destFilename = resolveDestPath(k, srcRoots, dest)
return copy(k, destFilename, v.content)
})
)
logv(`_GRAY_ parsable files copied`)
// add server files
await Promise.all(
config.serverRoots.map(async srcRoot => {
const filesUnderRoot = await readdirp(srcRoot, 'file')
serverFiles.push(... filesUnderRoot)
srcFiles.push(... filesUnderRoot)
})
)
logv(`_GRAY_ server files copied`)
// copy non parsable files
await Promise.all(
srcFiles.filter(k => serverFiles.includes(k) || !(k in files)).map(async k => {
if (excludeFile(k)) return
const destFilename = resolveDestPath(k, srcRoots, dest)
return copy(k, destFilename)
})
)
logv(`_GRAY_ non parsable files copied`)
// npm files
await copy(path.resolve('package.json'), path.join(dest, 'package.json'))
await copy(path.resolve('package-lock.json'), path.join(dest, 'package-lock.json'))
logv(`_GRAY_ npm files copied`)
// remove extraneous
await Promise.all(
destFilenamesOrig.map(async f => {
if (!destFilenames.includes(f) && !serverFiles.includes(f)) {
log(`_GRAY_remove extraneous ${relativePath(f)}`)
await fs.unlink(f)
try {
const dir = path.dirname(f)
if ((await readdirp(dir, 'file')).length === 0) {
await fs.rmdir(dir)
log(`_GRAY_remove empty dir ${relativePath(dir)}`)
}
} catch (error) {}
}
})
)
if (config.debug) {
log('_YELLOW_\nDEBUG: _RESET_ "filename type parseCount"\n_GRAY_' +
Object.keys(files).map(k => `${k.split('/').pop()} ${files[k].type} _RESET_${files[k].parseCount}_GRAY_`).join('\n')
)
}
const buildResult = `build to '${config.output}' succeeded at ${Math.round(10 * (Date.now() - buildStarted) / 1000) / 10}s`
log(`_GREEN_${buildResult}`)
return { exitCode: 0, message: buildResult }
// return `build to '${config.output}' succeeded at ${Math.round(10 * (Date.now() - buildStarted) / 1000) / 10}s`
}
/** @type {(srcPath: string, destPath: string, content?: string) => Promise<void>} */
async function copy(srcPath, destPath, content) {
destFilenames.push(destPath)
let srcBuffer, destBuffer
if (content) {
srcBuffer = Buffer.from(content)
} else {
try {
srcBuffer = await fs.readFile(srcPath)
} catch (error) { srcBuffer = Buffer.from('*EMPTY_SRC*') }
}
try {
destBuffer = await fs.readFile(destPath)
} catch (error) { destBuffer = Buffer.from('*EMPTY_DEST*') }
if (!srcBuffer.equals(destBuffer)) {
await fs.mkdir(path.dirname(destPath), { recursive: true })
if (srcBuffer.equals(Buffer.from('*EMPTY_SRC*'))) {
await fs.copyFile(srcPath, destPath)
} else {
await fs.writeFile(destPath, srcBuffer)
}
log(`_GRAY_${relativePath(destPath)}`)
}
}
/** @type {(srcPath: string, srcRoots: string[], destRoot: string) => string} */
function resolveDestPath(srcPath, srcRoots, destRoot) {
const srcRoot = srcRoots.find(r => srcPath.startsWith(r))
if (!srcRoot) { log(`_RED_${srcPath} not found`); return '' }
const relPath = path.relative(srcRoot, srcPath)
const dirname = srcRoot.replace(/\\/g, '/').split('/').pop() ?? ''
return path.join(destRoot, dirname, relPath)
}
/** @type {(filename: string) => boolean} */
function excludeFile(filename) {
if (['tsconfig.json', 'jsconfig.json'].includes(path.basename(filename))) return true
return false
} | 7fed3dc1fdf67c048ce5d7f4692af0a1c59e6352 | [
"JavaScript",
"TypeScript",
"Markdown"
]
| 28 | JavaScript | synartisis/webo | c0161ba898925f69636effa0b5a349522f54095d | 999ab9a475c7ffb6f410a3822fe45372ad4a5a8c |
refs/heads/master | <file_sep># Frosty Backup Utility
A lightweight command line backup utility that stores back ups as archives in Amazon Glacier or S3.
Frosty will run one or more user configurable jobs to execute a backup and then push the resulting backup to Amazon Glacier or S3. This aim is that frost can be easily configured to run various scripts as backups and can then be forgotten about except for receive email reports of the backups success/failure.
A "job" is a single command line command to execute resulting in one or more files that can be sent to Amazon Glacie or S3. Frosty takes care of setting environment variables and tidying up after itself to help ensure that no backups are left taking up disk space. The command that is run should produce one or more artifacts that will be zipped and sent to Amazon Glacier or S3.
Please note that Amazon Glacier and S3 are not equal. Please choose the service that is right for you ([this FAQ might help](https://aws.amazon.com/glacier/faqs/)). Notably, within Frosty, retention periods for backups are supported for S3 via lifecycles but with Glacier backups will remain indefinitely and must be archived externally for Frosty.
Binaries can be obtained from the [releases](https://github.com/mleonard87/frosty/releases) page.
## Other Features
- You do not have to create artifacts for upload to S3 or Glacier. Frosty will happily run any command that does not produce any artifacts and send the email report.
- Easily extensible - Once you have frosty configured and running adding new scripts or commands to run is as easy as adding a new 3-line entry to the config file.
# Usage
You need to create one or more backup scripts to be executed and then a configuration file detailing when to execute and where the resulting data should be stored Please see the following sections on how to do this.
## Commandline
```
Usage of frosty
frosty <path-to-frosty-config-file> [flags...]
Flags:
--validate
Validates that the specified config file is valid.
--version
Prints the version information about the Frosty backup utility.
```
## Creating Backup Scripts
Frosty only accepts a single command with no arguments for each job. As such, it is recommended that you create shell scripts that Frosty will execute to run your backups. Any resulting artifacts from your script will be zipped up and pushed to the configured backup service.
In order to have backups pushed up to Amazon Glacier or S3 you must put any files you want backed up into the jobs `artifacts` directory. The location of this is available within your scripts from the environment variable `FROSTY_JOB_ARTIFACTS_DIR`. Please see the [examples](examples) directory for examples of how this is done.
**Note:** Make sure that your scripts have the correct permissions to run!
## Environment Variables
Frosty sets environment variables when running jobs for use within scripts called in the `command` property of a frosty job. The following environment variables are set by default:
- **FROSTY_JOB_DIR**: The absolute path to the working directory of the current job. This is of the form `~/.frosty/jobs/<job-name>` (or whatever path you have set in the "workDirectory" config property).
- **FROSTY_JOB_ARTIFACTS_DIR**: The absolute path to the folder that should contain any files that you want copied to Amazon Glacier or S3. This is of the form `~/.frosty/jobs/artefacts/<job-name>` (or whatever path you have set in the "workDirectory" config property).
## Configuration Files
The commands to execute to carry out a frosty backup are configured in a JSON file. By convention this should end with `.frosty.config` (e.g. `internal_server_backup.frosty.config`). A full example can be found in the [examples](examples) directory.
```javascript
// Main Config
{
"workDirectory": "", // String (optional): Specify a directory location as the working directory for backups. Default is `~/.frosty`.
"reporting": {
"email": {
"smtp": {
"host": "", // String (required): The SMTP host name to connect to to send email reports.
"port": "", // String (required): The SMTP port number to connect to to send email reports.
"username": "", // String (optional): The username for the SMTP account to connect to. If this is not provided not auth will be used.
"password": "" // String (optional): Must be supplied with username as the password for the SMTP account.
},
"sender": "", // String (required): What sender address do you want on the email reports.
"recipients": [ // String[] (required): A list of recipient email addresses that will get the reports.
""
]
}
},
"backup": {
// One of "s3" or "glacier" configuration. See below for more details.
},
"jobs": [ // Job[] (required): A list of configurations for jobs to be run.
{
"name": "", // String (required): The name of the job to be run. This is how the job will be identified in the report.
"command": "", // String (required): The shell command to run. This must not contain any arguments.
"schedule": "" // String (required): Cron syntax for when the job should be scheduled.
},
...
]
}
// s3 Config -- this should go in the "backup" property above if using S3.
"s3": {
"accessKeyId": "", // String (required): The AWS Access Key of the account you wish to use to store data to S3.
"secretAccessKey": "", // String (required): The AWS Secret Key of the account you wish to use to store data to S3.
"bucketName": "", // String (required): The AWS s3 bucket in which you want to put your backups.
"region": "", // String (required): The AWS region you wish for your bucket to be created in.
"accountId": "", // String (required): The AWS account ID you are using to store data in S3.
"retentionDays": // Int (optional): The number of days you wish to retain backups for. After this they will be automatically deleted.
"endpoint": "" // String (optional): The S3 endpoint to use, you can override the default to use services such as [minio](https://github.com/minio/minio).
"pathStyleAccess": // Bool (optional): Use path access style on S3 URLs like http://s3.amazonaws.com/BUCKET/KEY rather than virtual host of http://BUCKET.s3.amazonaws.com/KEY. The default is virtual host.
}
// glacier Config -- this should go in the "backup" property above if using S3.
"glacier": {
"accessKeyId": "", // String (required): The AWS Access Key of the account you wish to use to store data to S3.
"secretAccessKey": "", // String (required): The AWS Secret Key of the account you wish to use to store data to S3.
"region": "", // String (required): The AWS region you wish for your bucket to be created in.
"accountId": "" // String (required): The AWS account ID you are using to store data in S3.
}
```
# Reporting
## Emails
As detailed above in the "Configuration" section, frosty is able to send out glorious html email reports following each backup. Backups are grouped so that any jobs scheduled with the same time be batched together and result in a single report. That is, if all jobs have a cron of "0 1 * * *" all jobs will run at 1am and you will receive a single email shortly after this. If yoiu have two jobs with "0 1 * * *" and one job with "30 1 * * *" you will receive one email after the 1am jobs complete and 1 email after the 1:30am jobs complete.
If a job fails, it's standard out and standard error is added to the email so you can identify exactly what went wrong. The emails subject line will start with "[SUCCESS]" or "[FAILURE]" so you should be able to filter out success emails in your inbox if you are only interested in failures.
A sample email report can be seen here:

<file_sep>package reporting
import (
"log"
"os"
"text/template"
"time"
"github.com/mleonard87/frosty/backup"
"github.com/mleonard87/frosty/config"
"github.com/mleonard87/frosty/job"
"github.com/mleonard87/frosty/tmpl"
)
type EmailSummaryTemplateData struct {
BackupService string
StartTime time.Time
EndTime time.Time
ElapsedTime time.Duration
Hostname string
BackupLocation string
Jobs []job.JobStatus
Status int
}
func (estd EmailSummaryTemplateData) IsSuccessful() bool {
return estd.Status == job.STATUS_SUCCESS
}
func SendEmailSummary(jobStatuses []job.JobStatus, emailConfig *config.EmailReportingConfig) {
templateData := emailSummaryTemplateData(jobStatuses)
data, err := tmpl.Asset("tmpl/email_summary.html")
if err != nil {
log.Printf("Error obtaining \"tmpl/email_summary.html\" email template:\n")
log.Println(err)
}
t := template.New("frosty-report")
t, err2 := t.Parse(string(data))
if err2 != nil {
log.Printf("Error parsing \"tmpl/email_summary.html\" email template:\n")
log.Println(err)
}
mail := Mail{
Host: emailConfig.SMTP.Host,
Port: emailConfig.SMTP.Port,
Username: emailConfig.SMTP.Username,
Password: emailConfig.SMTP.Password,
Sender: emailConfig.Sender,
}
for _, recipient := range emailConfig.Recipients {
mail.AddRecipient(recipient)
}
mail.SendFromTemplate(t, templateData)
}
func emailSummaryTemplateData(jobStatuses []job.JobStatus) EmailSummaryTemplateData {
hostname, err := os.Hostname()
if err != nil {
log.Fatal("Could not determine hostname.", err)
}
var startTime, endTime time.Time
status := job.STATUS_SUCCESS
for _, j := range jobStatuses {
if startTime.IsZero() || j.StartTime.Before(startTime) {
startTime = j.StartTime
}
if endTime.IsZero() || j.EndTime.After(endTime) {
endTime = j.EndTime
}
if j.Status == job.STATUS_FAILURE {
status = job.STATUS_FAILURE
}
}
bs := *backupservice.CurrentBackupService()
return EmailSummaryTemplateData{
BackupService: bs.Name(),
StartTime: startTime,
EndTime: endTime,
ElapsedTime: endTime.Sub(startTime),
Hostname: hostname,
BackupLocation: bs.BackupLocation(),
Jobs: jobStatuses,
Status: status,
}
}
<file_sep>package reporting
import (
"bytes"
"fmt"
"log"
"net/smtp"
"strings"
"text/template"
)
type Mail struct {
Host string
Port string
Username string
Password string
Sender string
Recipients []string
}
func (m *Mail) AddRecipient(recipient string) {
m.Recipients = append(m.Recipients, recipient)
}
func (m *Mail) getSMTPHostAndPort() string {
return m.Host + ":" + m.Port
}
func (m *Mail) recipientHeader() string {
var recipients string
for _, recipient := range m.Recipients {
recipients += recipient + ","
}
return strings.TrimRight(recipients, ",")
}
func (m *Mail) useAuthentication() bool {
return m.Username != ""
}
func (m *Mail) SendFromTemplate(tmpl *template.Template, templateData EmailSummaryTemplateData) {
var subject string
if templateData.IsSuccessful() {
subject = "[SUCCESS] Frosty Backup Report"
} else {
subject = "[FAILURE] Frosty Backup Report"
}
var wc bytes.Buffer
headers := make(map[string]string)
headers["From"] = m.Sender
headers["To"] = m.recipientHeader()
headers["Subject"] = subject
headers["Content-Type"] = "text/html; charset=utf-8"
for k, v := range headers {
h := fmt.Sprintf("%s: %s\r\n", k, v)
wc.Write([]byte(h))
}
wc.Write([]byte("\r\n"))
tmpl.Execute(&wc, templateData)
if m.useAuthentication() {
a := smtp.PlainAuth("", m.Username, m.Password, m.Host)
err := smtp.SendMail(m.getSMTPHostAndPort(), a, m.Sender, m.Recipients, wc.Bytes())
if err != nil {
log.Printf("Error sending email with auth: %s\n", err)
}
} else {
// Connect to the remote SMTP server.
c, err := smtp.Dial(m.getSMTPHostAndPort())
if err != nil {
log.Printf("Error sending email: %s\n", err)
}
defer c.Close()
// Set the sender and recipient.
c.Mail(m.Sender)
c.Rcpt(m.Recipients[0])
// Send the email body.
cwc, err := c.Data()
if err != nil {
log.Fatal(err)
}
defer cwc.Close()
cwc.Write(wc.Bytes())
}
}
<file_sep>package backupservice
import (
"bytes"
"fmt"
"os"
"io/ioutil"
"log"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/glacier"
"github.com/mleonard87/frosty/config"
)
const ()
type AmazonGlacierBackupService struct {
AccessKeyId string
SecretAccessKey string
Region string
AccountId string
VaultName string
GlacierService *glacier.Glacier
}
// Return the backup service type this must match the string as used as the JSON property in the frosty backup config.
func (agss *AmazonGlacierBackupService) Name() string {
return config.BACKUP_SERVICE_AMAZON_GLACIER
}
// Initialise any variable needed for backups.
func (agss *AmazonGlacierBackupService) SetConfig(backupConfig *config.BackupConfig) {
agss.AccessKeyId = backupConfig.BackupConfig["accessKeyId"].(string)
agss.SecretAccessKey = backupConfig.BackupConfig["secretAccessKey"].(string)
agss.Region = backupConfig.BackupConfig["region"].(string)
agss.AccountId = backupConfig.BackupConfig["accountId"].(string)
agss.VaultName = agss.getVaultName()
}
// Initialise anything in the backup service that needs to be created prior to uploading files. In this instance we need
// to create a vault for the backup to hold any archives.
func (agss *AmazonGlacierBackupService) Init() error {
agss.setEnvvars()
agss.GlacierService = glacier.New(session.New(), &aws.Config{})
err := agss.createVault(agss.VaultName)
if err != nil {
return err
}
return nil
}
// Store the file in pathToFile in Amazon Glacier.
func (agss *AmazonGlacierBackupService) StoreFile(pathToFile string) error {
fileContents, err := ioutil.ReadFile(pathToFile)
if err != nil {
return err
}
params := &glacier.UploadArchiveInput{
AccountId: aws.String(agss.AccountId),
VaultName: aws.String(agss.VaultName),
Body: bytes.NewReader(fileContents),
}
_, err = agss.GlacierService.UploadArchive(params)
if err != nil {
return err
}
return nil
}
// Get the name to be used for the .zip archive without the .zip extension.
func (agss *AmazonGlacierBackupService) ArtifactFilename(jobName string) string {
return jobName
}
// Get a friendly name for the email template of where this backup was stored. In this case, the name of the Glacier
// vault.
func (agss *AmazonGlacierBackupService) BackupLocation() string {
return fmt.Sprintf("Glacier Vault: %s", agss.getVaultName())
}
// Create the Glacier Vault.
func (agss *AmazonGlacierBackupService) createVault(vaultName string) error {
agss.setEnvvars()
params := &glacier.CreateVaultInput{
AccountId: aws.String(agss.AccountId),
VaultName: aws.String(agss.VaultName),
}
_, err := agss.GlacierService.CreateVault(params)
if err != nil {
return err
}
return nil
}
// Set the required AWS environment variables.
func (agss *AmazonGlacierBackupService) setEnvvars() {
os.Setenv(ENVVAR_AWS_ACCESS_KEY_ID, agss.AccessKeyId)
os.Setenv(ENVVAR_AWS_SECRET_ACCESS_KEY, agss.SecretAccessKey)
os.Setenv(ENVVAR_AWS_REGION, agss.Region)
}
// Get the name to use for for the Glacier Vault.
func (agss *AmazonGlacierBackupService) getVaultName() string {
if agss.VaultName == "" {
hostname, err := os.Hostname()
if err != nil {
log.Fatal("Could not determine hostname.", err)
}
agss.VaultName = BACKUP_NAME_PREFIX + time.Now().Format("20060102") + "_" + hostname
}
return agss.VaultName
}
<file_sep>package config
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"os"
"strings"
)
const (
BACKUP_SERVICE_AMAZON_GLACIER = "glacier"
BACKUP_SERVICE_AMAZON_S3 = "s3"
)
var frostyConfig FrostyConfig
type FrostyConfig struct {
WorkDir string `json:"workDirectory"`
ReportingConfig ReportingConfig `json:"reporting"`
RawBackupConfig map[string]interface{} `json:"backup"`
BackupConfig BackupConfig
Jobs []JobConfig `json:"jobs"`
}
type ReportingConfig struct {
Email EmailReportingConfig `json:"email"`
}
type EmailReportingConfig struct {
SMTP struct {
Host string `json:"host"`
Port string `json:"port"`
Username string `json:"username"`
Password string `json:"<PASSWORD>"`
} `json:"smtp"`
Sender string `json:"sender"`
Recipients []string `json:"recipients"`
}
type JobConfig struct {
Name string `json:"name"`
Command string `json:"command"`
Schedule string `json:"schedule"`
}
type BackupConfig struct {
BackupService string
BackupConfig map[string]interface{}
}
func (fc *FrostyConfig) validateJobNames() bool {
ok := true
for _, j := range fc.Jobs {
jobNameCount := 0
for _, oj := range fc.Jobs {
if j.Name == oj.Name {
jobNameCount++
}
}
if jobNameCount > 1 {
ok = false
log.Printf("Job names must be unique - duplicate found for %q.\n", j.Name)
}
}
return ok
}
func (fc *FrostyConfig) validateJobs() bool {
ok := true
for i, j := range fc.Jobs {
if strings.TrimSpace(j.Name) == "" {
log.Printf("All jobs must have names and it must not be empty - job in position %d has no name.", i)
ok = false
}
if strings.TrimSpace(j.Command) == "" {
log.Printf("All jobs must have a command and it must not be empty - %q has no command.", j.Name)
ok = false
}
}
return ok
}
func (fc *FrostyConfig) validate() bool {
validationPassed := true
validationPassed = fc.validateJobNames()
validationPassed = fc.validateJobs()
// TODO: Validate that if the email section is supplied then all the details are provided.
// TODO: Validate that the email addresses in the email section are actually email addresses.
// TODO: Validate that the schedules passed in are valid cron syntax.
return validationPassed
}
func (fc *FrostyConfig) ScheduledJobs() map[string][]JobConfig {
sj := make(map[string][]JobConfig)
for _, v := range fc.Jobs {
val, ok := sj[v.Schedule]
if !ok {
val = []JobConfig{}
}
val = append(val, v)
sj[v.Schedule] = val
}
return sj
}
func LoadConfig(configPath string) (FrostyConfig, error) {
f, err := ioutil.ReadFile(configPath)
if err != nil {
log.Fatalf("Cannot find frosty config file: %s\n", err)
os.Exit(1)
}
var fc FrostyConfig
err = json.Unmarshal(f, &fc)
if err != nil {
log.Fatalf("Cannot parse frosty config file: %v: %v Are you sure the JSON is valid?\n", configPath, err)
os.Exit(1)
}
var backupConfig BackupConfig
if config, ok := fc.RawBackupConfig[BACKUP_SERVICE_AMAZON_GLACIER]; ok {
backupConfig.BackupService = BACKUP_SERVICE_AMAZON_GLACIER
backupConfig.BackupConfig = config.(map[string]interface{})
}
if config, ok := fc.RawBackupConfig[BACKUP_SERVICE_AMAZON_S3]; ok {
backupConfig.BackupService = BACKUP_SERVICE_AMAZON_S3
backupConfig.BackupConfig = config.(map[string]interface{})
}
fc.BackupConfig = backupConfig
if !fc.validate() {
return fc, errors.New("Failed to validate config file: " + configPath)
}
frostyConfig = fc
return fc, nil
}
func GetFrostConfig() FrostyConfig {
fc := frostyConfig
return fc
}
<file_sep>package job
import (
"strconv"
"strings"
"time"
"os/exec"
"os"
"fmt"
"github.com/mleonard87/frosty/artifact"
"github.com/mleonard87/frosty/config"
)
const (
STATUS_SUCCESS = iota
STATUS_FAILURE = iota
BYTES_PER_SI = 1000
)
var BINARY_SI_UNITS = [...]string{"B", " kB", " MB", " GB", " TB", " PB", " EB", " ZB"}
type JobStatus struct {
Status int
StdOut string
StdErr string
Error string
StartTime time.Time
EndTime time.Time
JobConfig config.JobConfig
ArchiveCreated bool
ArchiveSize int64
TransferStartTime time.Time
TransferEndTime time.Time
TransferError string
}
func (js JobStatus) ElapsedTime() time.Duration {
return js.EndTime.Sub(js.StartTime)
}
func (js JobStatus) ElapsedTransferTime() time.Duration {
return js.TransferEndTime.Sub(js.TransferStartTime)
}
func (js JobStatus) IsSuccessful() bool {
return js.Status == STATUS_SUCCESS
}
func (js JobStatus) GetArchiveNameDisplay() string {
return GetArtifactArchiveFileName(js.JobConfig.Name)
}
func (js JobStatus) GetArchiveSizeDisplay() string {
size := js.ArchiveSize
for _, unit := range BINARY_SI_UNITS {
if size < 1024 {
return strconv.FormatInt(size, 10) + unit
} else {
size = size / BYTES_PER_SI
}
}
return strconv.FormatInt(js.ArchiveSize, 10) + BINARY_SI_UNITS[0]
}
func Start(jobConfig config.JobConfig, runId string) JobStatus {
js := JobStatus{}
js.JobConfig = jobConfig
js.Status = STATUS_SUCCESS
js.StartTime = time.Now()
jobDir, artifactDir, err := MakeJobDirectories(jobConfig.Name, runId)
if err != nil {
js.Status = STATUS_FAILURE
js.Error = err.Error()
js.EndTime = time.Now()
return js
}
env := os.Environ()
env = append(env, fmt.Sprintf("FROSTY_JOB_DIR=%s", jobDir))
env = append(env, fmt.Sprintf("FROSTY_JOB_ARTIFACTS_DIR=%s", artifactDir))
cmd := exec.Command(jobConfig.Command)
cmd.Env = env
out, err := cmd.Output()
if err != nil {
js.Status = STATUS_FAILURE
if ee, ok := err.(*exec.ExitError); ok {
// Capture and trim any errors logged to stderr.
js.StdErr = strings.TrimSpace(string(ee.Stderr))
}
js.Error = err.Error()
js.EndTime = time.Now()
js.StdOut = strings.TrimSpace(string(out[:]))
return js
}
js.EndTime = time.Now()
js.StdOut = strings.TrimSpace(string(out[:]))
archiveTarget := GetArtifactArchiveTargetName(jobConfig.Name, runId)
js.ArchiveCreated, err = artifact.MakeArtifactArchive(artifactDir, archiveTarget)
if err != nil {
js.Status = STATUS_FAILURE
js.Error = err.Error()
return js
}
if js.ArchiveCreated {
fileInfo, err := os.Stat(archiveTarget)
if err != nil {
js.Status = STATUS_FAILURE
js.Error = err.Error()
return js
}
js.ArchiveSize = fileInfo.Size()
}
return js
}
<file_sep>package artifact
import (
"archive/zip"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
func MakeArtifactArchive(artifactDir string, target string) (bool, error) {
artifactFiles, err := listArtifactFiles(artifactDir, target)
if err != nil {
return false, err
}
if len(artifactFiles) == 0 {
return false, nil
}
err = makeZipFromFiles(target, artifactFiles, artifactDir)
if err != nil {
return false, err
}
return true, nil
}
func listArtifactFiles(artifactDir string, target string) ([]string, error) {
var artifactFiles []string
err := filepath.Walk(artifactDir, func(path string, f os.FileInfo, err error) error {
id, err := isDirectory(path)
if err != nil {
return err
}
if path != artifactDir && !id && path != target {
artifactFiles = append(artifactFiles, path)
}
return nil
})
if err != nil {
return artifactFiles, err
}
return artifactFiles, nil
}
func isDirectory(path string) (bool, error) {
fileInfo, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
} else {
em := fmt.Sprintf("Error determining if \"%s\" is a directory:\n%s\n", path, err)
return false, errors.New(em)
}
}
return fileInfo.IsDir(), nil
}
func makeZipFromFiles(target string, sourceFileList []string, basePath string) error {
zipfile, err := os.Create(target)
if err != nil {
return err
}
defer zipfile.Close()
// Create a new zip archive.
w := zip.NewWriter(zipfile)
defer w.Close()
for _, file := range sourceFileList {
relativeFileName, err := filepath.Rel(basePath, file)
if err != nil {
return err
}
f, err := w.Create(relativeFileName)
if err != nil {
return err
}
fileContents, err := ioutil.ReadFile(file)
if err != nil {
return err
}
_, err = f.Write(fileContents)
if err != nil {
return err
}
}
return nil
}
<file_sep>#!/bin/sh
echo "Starting backup"
echo "Here is some text to backup" >> $FROSTY_JOB_ARTIFACTS_DIR/backup.txt
echo "One" >> $FROSTY_JOB_ARTIFACTS_DIR/file1.txt
echo "Two" >> $FROSTY_JOB_ARTIFACTS_DIR/file2.txt
mkdir $FROSTY_JOB_ARTIFACTS_DIR/nested
echo "Three" >> $FROSTY_JOB_ARTIFACTS_DIR/nested/file3.txt
echo "Backup complete"<file_sep>package cli
import (
"fmt"
"log"
"os"
"sync"
"time"
flag "github.com/ogier/pflag"
"github.com/mleonard87/frosty/backup"
"github.com/mleonard87/frosty/config"
"github.com/mleonard87/frosty/job"
"github.com/mleonard87/frosty/reporting"
"gopkg.in/robfig/cron.v2"
)
var frostyVersion string
const (
COMMAND_BACKUP = "backup"
COMMAND_HELP = "help"
COMMAND_VALIDATE = "validate"
COMMAND_VERSION = "version"
)
func Execute() {
flag.Usage = printHelp
doValidate := flag.Bool("validate", false, "Validates that the specified config file is valid.")
doVersion := flag.Bool("version", false, "Prints the version information about the Frosty backup utility.")
flag.Parse()
switch {
case *doValidate:
validate(os.Args[1])
case *doVersion:
printVersion()
default:
backup(os.Args[1])
}
}
// Print usage information about the frosty backup tool.
func printHelp() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
fmt.Fprintf(os.Stderr, "\n\tfrosty <path-to-frosty-config-file> [flags...]\n\n")
fmt.Fprintf(os.Stderr, "Flags:\n")
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "\n%s\n", frostyVersion)
}
// Prints version information about frosty.
func printVersion() {
fmt.Fprintf(os.Stderr, "Frosty backup utility, version %s\n", frostyVersion)
}
// Validate a given config file.
func validate(configPath string) {
_, err := config.LoadConfig(configPath)
if err != nil {
log.Fatalf("Frosty config file: %v - FAILED\n", configPath)
os.Exit(1)
}
fmt.Printf("Frosty config file: %v - OK\n", configPath)
}
// The main function for beginning backups. This is the default way in which frosty will run. It loads a config file
// and then execute all the backups.
func backup(configPath string) {
fc, err := config.LoadConfig(configPath)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
bs := backupservice.NewBackupService(&fc.BackupConfig)
sj := fc.ScheduledJobs()
scheduleJobs(sj, bs, fc)
select {}
}
// For the given map of cron schedule times against the list of jobs due to run at this time raise a gocron job
// to execute each of these jobs in go routines at the given time.
func scheduleJobs(js map[string][]config.JobConfig, bs backupservice.BackupService, fc config.FrostyConfig) {
c := cron.New()
for k, v := range js {
// Assign v to jobs to use in the closure below.
jobs := v
// The function defined below acts as a closure using the assigned "jobs" variable above.
// If we do not re-assign v to jobs as above and constantly used "v" in the function then
// we would find that only the last set of jobs would ever be run as the value of "v" is
// updated in each iteration of the loop. However, jobs is scoped within the body of the
// loop and the closure below can take advantage of this.
_, err := c.AddFunc(k, func() {
// Get a timestamp as an ID for this run of jobs. This will be used in the directory name to ensure that
// if jobs overlap we don't get any conflicts.
t := time.Now()
runId := t.Format("20060102150405")
js := beginJobs(jobs, runId)
initBackupService(bs, js)
beginBackups(bs, js, runId)
if &fc.ReportingConfig.Email != nil {
reporting.SendEmailSummary(js, &fc.ReportingConfig.Email)
}
})
if err != nil {
log.Fatalf("Error scheduling jobs: %s", err.Error())
}
}
c.Start()
}
// Starts running all jobs by executing the commands and letting each command create its artifacts. This function
// returns when all jobs have finished. Each job is run in a separate go routine.
func beginJobs(jobs []config.JobConfig, runId string) []job.JobStatus {
ch := make(chan job.JobStatus)
var wg sync.WaitGroup
for _, j := range jobs {
wg.Add(1)
go beginJob(j, runId, ch, &wg)
}
go func() {
wg.Wait()
close(ch)
}()
var jobStatuses []job.JobStatus
for js := range ch {
jobStatuses = append(jobStatuses, js)
}
return jobStatuses
}
// Run an individual job.
func beginJob(jobConfig config.JobConfig, runId string, ch chan job.JobStatus, wg *sync.WaitGroup) {
log.Printf("Running Job: %s\n", jobConfig.Name)
defer wg.Done()
js := job.Start(jobConfig, runId)
ch <- js
}
// Initialise the backup service (e.g. S3 or Glacier) if there was a problem doing this mark all jobs as failed and
// write the error message to each job.
func initBackupService(backupService backupservice.BackupService, jobStatuses []job.JobStatus) error {
err := backupService.Init()
if err != nil {
for i := range jobStatuses {
// If we couldn't init the backup service then just log the same error caused by that against
// each job. This saves needing to create a generic section in the email reporting that covers
// over-arching backup service errors.
jobStatuses[i].Status = job.STATUS_FAILURE
jobStatuses[i].TransferError = err.Error()
continue
}
return err
}
return nil
}
// Begin the transfer of artifacts to the backup service.
func beginBackups(backupService backupservice.BackupService, jobStatuses []job.JobStatus, runId string) {
for i, js := range jobStatuses {
archivePath := job.GetArtifactArchiveTargetName(js.JobConfig.Name, runId)
// Only run the backup if the archive exists.
_, err := os.Stat(archivePath)
if err != nil {
if !os.IsNotExist(err) {
em := fmt.Sprintf("Error locating artifacts at \"%s\":\n%s\n", archivePath, err)
jobStatuses[i].Status = job.STATUS_FAILURE
jobStatuses[i].TransferError = em
continue
} else {
continue
}
}
jobStatuses[i].TransferStartTime = time.Now()
err = backupService.StoreFile(archivePath)
if err != nil {
jobStatuses[i].Status = job.STATUS_FAILURE
jobStatuses[i].TransferError = err.Error()
continue
}
jobStatuses[i].TransferEndTime = time.Now()
// Remove the directory created for this job.
err = job.RemoveJobDirectory(js.JobConfig.Name, runId)
if err != nil {
em := fmt.Sprintf("Unable to remove working directory for %s job following successful transfer:\n%s\n", js.JobConfig.Name, err)
js.Status = job.STATUS_FAILURE
js.Error = em
js.EndTime = time.Now()
continue
}
}
// Finally remove the run directory (this should be empty by this point).
err := job.RemoveRunDirectory(runId)
if err != nil {
log.Printf("Error removing run directory \"%s\":\n%s\n", runId, err)
}
}
<file_sep>package backupservice
import (
"log"
"os"
"fmt"
"path/filepath"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/mleonard87/frosty/config"
)
const (
ERROR_CODE_INVALID_BUCKET_NAME string = "InvalidBucketName"
ERROR_CODE_BUCKET_ALREADY_OWNED_BY_YOU string = "BucketAlreadyOwnedByYou"
LIFECYCLE_ID string = "frosty-backup-retention-policy"
)
type AmazonS3BackupService struct {
AccessKeyId string
SecretAccessKey string
Region string
AccountId string
RetentionDays int64
BucketName string
Endpoint string
UsePathStyleAccess bool
S3Service *s3.S3
}
// Return the backup service type this must match the string as used as the JSON property in the frosty backup config.
func (agss *AmazonS3BackupService) Name() string {
return config.BACKUP_SERVICE_AMAZON_S3
}
// Initialise any variable needed for backups.
func (asbs *AmazonS3BackupService) SetConfig(backupConfig *config.BackupConfig) {
asbs.AccessKeyId = backupConfig.BackupConfig["accessKeyId"].(string)
asbs.SecretAccessKey = backupConfig.BackupConfig["secretAccessKey"].(string)
asbs.Region = backupConfig.BackupConfig["region"].(string)
asbs.AccountId = backupConfig.BackupConfig["accountId"].(string)
// Attempt to get the retentionDays config property. If this can't be found then default to 0.
// 0 will not set a life cycle policy and any existing policy will remain.
rd, ok := backupConfig.BackupConfig["retentionDays"]
if ok {
asbs.RetentionDays = int64(rd.(float64))
} else {
asbs.RetentionDays = 0
}
asbs.BucketName = backupConfig.BackupConfig["bucketName"].(string)
// Endpoint is optional
e, ok := backupConfig.BackupConfig["endpoint"]
if ok {
asbs.Endpoint = e.(string)
} else {
asbs.Endpoint = ""
}
// pathStyleAccess is optional
psa, ok := backupConfig.BackupConfig["pathStyleAccess"]
if ok {
asbs.UsePathStyleAccess = psa.(bool)
} else {
asbs.UsePathStyleAccess = false
}
}
// Initialise anything in the backup service that needs to be created prior to uploading files. In this instance we need
// to create a bucket to store the backups if one does not already exist. This always uses a bucket
// called "frosty.backups".
func (asbs *AmazonS3BackupService) Init() error {
asbs.setEnvvars()
ac := &aws.Config{}
ac.S3ForcePathStyle = &asbs.UsePathStyleAccess
if asbs.Endpoint != "" {
ac.Endpoint = &asbs.Endpoint
} else {
ac = &aws.Config{}
}
asbs.S3Service = s3.New(session.New(), ac)
err := asbs.createBucket(asbs.BucketName)
if err != nil {
log.Println("Error creating bucket")
log.Println(err)
return err
}
err = asbs.putBucketLifecycleConfiguration()
if err != nil {
log.Println("Error creating bucket lifecycle")
log.Println(err)
return err
}
return nil
}
// Store the file in pathToFile in the bucket in S3.
func (asbs *AmazonS3BackupService) StoreFile(pathToFile string) error {
_, fileName := filepath.Split(pathToFile)
key := getObjectKey(fileName)
f, err := os.Open(pathToFile)
if err != nil {
log.Printf("Failed to open file to store: %s", pathToFile)
log.Println(err)
return err
}
params := &s3.PutObjectInput{
Body: f,
Bucket: &asbs.BucketName,
Key: &key,
}
_, err = asbs.S3Service.PutObject(params)
if err != nil {
log.Printf("Failed to put object %s into bucket %s with a key of %s\n", pathToFile, asbs.BucketName, fileName)
log.Println(err)
return err
}
return nil
}
// Get the name to be used for the .zip archive without the .zip extension.
func (asbs *AmazonS3BackupService) ArtifactFilename(jobName string) string {
return jobName
}
// Get a friendly name for the email template of where this backup was stored. In this case, the name of the S3 bucket.
func (asbs *AmazonS3BackupService) BackupLocation() string {
return fmt.Sprintf("S3 Bucket: %s", asbs.BucketName)
}
// Create the S3 bucket.
func (asbs *AmazonS3BackupService) createBucket(bucketName string) error {
asbs.setEnvvars()
params := &s3.CreateBucketInput{
Bucket: aws.String(bucketName),
}
_, err := asbs.S3Service.CreateBucket(params)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() == ERROR_CODE_INVALID_BUCKET_NAME {
log.Printf("The specified bucket is not valid. Bucket name: %s\n", bucketName)
log.Println(err)
return err
}
// If the BucketAlreadyOwnedByYou error is raised then this bucket already exists.
if aerr.Code() == ERROR_CODE_BUCKET_ALREADY_OWNED_BY_YOU {
return nil
}
}
return err
}
if err = asbs.S3Service.WaitUntilBucketExists(&s3.HeadBucketInput{Bucket: &bucketName}); err != nil {
log.Printf("Failed to wait for bucket to exist %s, %s\n", bucketName, err)
return err
}
return nil
}
func (asbs *AmazonS3BackupService) putBucketLifecycleConfiguration() error {
// If the retention period is not 0 days then submit a new life cycle policy.
if asbs.RetentionDays != 0 {
params := &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(asbs.BucketName),
LifecycleConfiguration: &s3.BucketLifecycleConfiguration{
Rules: []*s3.LifecycleRule{
{
Prefix: aws.String(""),
Status: aws.String("Enabled"),
ID: aws.String(LIFECYCLE_ID),
Expiration: &s3.LifecycleExpiration{
Days: &asbs.RetentionDays,
},
},
},
},
}
_, err := asbs.S3Service.PutBucketLifecycleConfiguration(params)
if err != nil {
log.Printf("Failed to create bucket lifecycle configuration, %s.\n", err)
return err
}
}
return nil
}
// Set the required AWS environment variables.
func (asbs *AmazonS3BackupService) setEnvvars() {
os.Setenv(ENVVAR_AWS_ACCESS_KEY_ID, asbs.AccessKeyId)
os.Setenv(ENVVAR_AWS_SECRET_ACCESS_KEY, asbs.SecretAccessKey)
os.Setenv(ENVVAR_AWS_REGION, asbs.Region)
}
// Get the name to use for the file being stored in S3.
func getObjectKey(fileName string) string {
hostname, err := os.Hostname()
if err != nil {
log.Fatal("Could not determine hostname.", err)
return ""
}
return fmt.Sprintf("%s/%s/%s_%s", hostname, time.Now().Format("20060102"), time.Now().Format("15:04:05"), fileName)
}
<file_sep>package main
import "github.com/mleonard87/frosty/cli"
func main() {
cli.Execute()
}
<file_sep>#!/bin/sh
echoerr() { echo "$@" 1>&2; }
echo "Frosty Job Dir: $FROSTY_JOB_DIR"
echo "Frosty Artifacts Dir: $FROSTY_JOB_ARTIFACTS_DIR"
>&2 echo "Uh-Oh! Its all gone wrong!"
echoerr hello world
exit 1<file_sep>generate-bindata-debug:
go-bindata -debug -o tmpl/bindata.go -pkg tmpl tmpl
clean:
rm -f build/*
build: clean
go-bindata -o tmpl/bindata.go -pkg tmpl tmpl
env GOOS=darwin GOARCH=amd64 go build -ldflags "-X github.com/mleonard87/frosty/cli.frostyVersion=0.3.0" -o "build/darwin_amd64" frosty.go
env GOOS=linux GOARCH=386 go build -ldflags "-X github.com/mleonard87/frosty/cli.frostyVersion=0.3.0" -o "build/linux_386" frosty.go
env GOOS=linux GOARCH=amd64 go build -ldflags "-X github.com/mleonard87/frosty/cli.frostyVersion=0.3.0" -o "build/linux_amd64" frosty.go
env GOOS=linux GOARCH=arm go build -ldflags "-X github.com/mleonard87/frosty/cli.frostyVersion=0.3.0" -o "build/linux_arm" frosty.go
env GOOS=windows GOARCH=amd64 go build -ldflags "-X github.com/mleonard87/frosty/cli.frostyVersion=0.3.0" -o "build/windows_amd64.exe" frosty.go
env GOOS=windows GOARCH=386 go build -ldflags "-X github.com/mleonard87/frosty/cli.frostyVersion=0.3.0" -o "build/windows_386.exe" frosty.go<file_sep>package job
import (
"log"
"os"
"os/user"
"path/filepath"
"fmt"
"github.com/mleonard87/frosty/backup"
"github.com/mleonard87/frosty/config"
)
const (
FROSTY_DIR_NAME = ".frosty"
JOBS_DIR_NAME = "jobs"
JOB_ARTIFACTS_DIR_NAME = "artifacts"
ARTIFACT_ARCHIVE_FILENAME_EXTENSION = "zip"
)
func getUserHomeDirectory() string {
usr, err := user.Current()
if err != nil {
log.Fatalf("Unable to obtain current user: %s", err)
os.Exit(1)
}
return usr.HomeDir
}
func getRunDirectoryPath(runId string) string {
fc := config.GetFrostConfig()
if fc.WorkDir == "" {
userHome := getUserHomeDirectory()
return filepath.Join(userHome, FROSTY_DIR_NAME, JOBS_DIR_NAME, runId)
} else {
return filepath.Join(fc.WorkDir, JOBS_DIR_NAME, runId)
}
}
func getJobDirectoryPath(jobName string, runId string) string {
return filepath.Join(getRunDirectoryPath(runId), jobName)
}
func getJobArtifactDirectoryPath(jobName string, runId string) string {
return filepath.Join(getJobDirectoryPath(jobName, runId), JOB_ARTIFACTS_DIR_NAME)
}
func MakeJobDirectories(jobName string, runId string) (string, string, error) {
jobDir := getJobDirectoryPath(jobName, runId)
artifactDir := getJobArtifactDirectoryPath(jobName, runId)
err := os.MkdirAll(jobDir, 0755)
if err != nil {
return "", "", err
}
err2 := os.MkdirAll(artifactDir, 0755)
if err2 != nil {
return "", "", err
}
return jobDir, artifactDir, nil
}
func RemoveJobDirectory(jobName string, runId string) error {
jobDir := getJobDirectoryPath(jobName, runId)
return os.RemoveAll(jobDir)
}
func RemoveRunDirectory(runId string) error {
runDir := getRunDirectoryPath(runId)
return os.RemoveAll(runDir)
}
func GetArtifactArchiveFileName(jobName string) string {
bs := *backupservice.CurrentBackupService()
return fmt.Sprintf("%s.%s", bs.ArtifactFilename(jobName), ARTIFACT_ARCHIVE_FILENAME_EXTENSION)
}
func GetArtifactArchiveTargetName(jobName string, runId string) string {
artifactDir := getJobArtifactDirectoryPath(jobName, runId)
return filepath.Join(artifactDir, GetArtifactArchiveFileName(jobName))
}
<file_sep>package backupservice
import (
"log"
"github.com/mleonard87/frosty/config"
)
const (
BACKUP_NAME_PREFIX = "frosty_"
ENVVAR_AWS_ACCESS_KEY_ID = "AWS_ACCESS_KEY_ID"
ENVVAR_AWS_SECRET_ACCESS_KEY = "AWS_SECRET_ACCESS_KEY"
ENVVAR_AWS_REGION = "AWS_REGION"
)
type BackupService interface {
Name() string
SetConfig(backupConfig *config.BackupConfig)
Init() error
StoreFile(pathToFile string) error
ArtifactFilename(jobName string) string
BackupLocation() string
}
var currentBackupService BackupService
func NewBackupService(backupConfig *config.BackupConfig) BackupService {
var bs BackupService
switch backupConfig.BackupService {
case config.BACKUP_SERVICE_AMAZON_GLACIER:
bs = &AmazonGlacierBackupService{}
case config.BACKUP_SERVICE_AMAZON_S3:
bs = &AmazonS3BackupService{}
default:
log.Fatal("Only Amazon Glacier and Amazon S3 are supported as a backup services.")
return nil
}
bs.SetConfig(backupConfig)
currentBackupService = bs
return bs
}
func CurrentBackupService() *BackupService {
if currentBackupService == nil {
log.Fatal("You must create a backup service before calling CurrentbackupService().")
}
return ¤tBackupService
}
| fae6212500b1e8460b1b68aae23d266528986520 | [
"Markdown",
"Go",
"Makefile",
"Shell"
]
| 15 | Markdown | mleonard87/frosty | 9de3450cc2865a0c510facd33da0e2c5b260d5f5 | d900f8af955614e5ed0d968a7dd3a9c0cc1293bd |
refs/heads/main | <file_sep>//
// SendToDB.swift
// ChatApp
//
// Created by ヘパリン類似物質 on 2021/05/18.
//
import Foundation
import FirebaseStorage
//新規登録後、画面遷移を行うかどうかの判断をするデリゲートメソッドを委任するためのプロトコル
protocol SendProfileOKDelegete {
func sendProfileOKDelegete(url: String)
}
//プロフィールイメージデータを、storageに保存する
class SendToDBModel {
var sendProfileOKDelegete:SendProfileOKDelegete?
init() {
}
func sendProfileImageData(data:Data){
//Data型で、引数を受け取り、それをUIImage型に変換
let image = UIImage(data: data)
//データを圧縮
let profileImageData = image?.jpegData(compressionQuality: 0.1)
//ここで、firestorage側にどう保存するかの設定を行なっている?、パスを設定している。
let imageRef = Storage.storage().reference().child("profileImage").child("\(UUID().uuidString + String(Date().timeIntervalSince1970)).jpg")
//ここで、FireStorageにデータを送信
imageRef.putData(profileImageData!, metadata: nil) { metadata, error in
if error != nil{
print(error.debugDescription)
return
}
//上で送った画像データのありかを示す画像URLをダウンロード。それが、url変数に代入される。
imageRef.downloadURL { url, error in
if error != nil{
print(error.debugDescription)
return
}
//ダウンロードした画像URLを、文字列にしてアプリ内に保存(チャット送信時に、画像データも使用するため。)
UserDefaults.standard.set(url?.absoluteString, forKey: "userImage")
//このタイミングでデリゲードメソッドをRegisterControllerで発動させ、画像がしっかりと保存されているかをかくにんする。
self.sendProfileOKDelegete?.sendProfileOKDelegete(url: url!.absoluteString )
}
}
}
}
<file_sep>//
// RegisterViewController.swift
// ChatApp
//
// Created by ヘパリン類似物質 on 2021/05/18.
//
import UIKit
import Firebase
import FirebaseAuth
class RegisterViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate,SendProfileOKDelegete,UITextFieldDelegate {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var profileImageView: UIImageView!
let sendToDBModel = SendToDBModel()
var urlSting = String()
override func viewDidLoad() {
//カメラもしくはアルバムの使用許可
let checkModel = CheckPermission()
checkModel.showCheckPermission()
sendToDBModel.sendProfileOKDelegete = self
super.viewDidLoad()
if Auth.auth().currentUser?.email != nil{
print("ログインなう")
} else {
print("ログアウトできました!")
}
// Do any additional setup after loading the view.
}
@IBAction func touroku(_ sender: Any) {
//メールアドレスとパスワードとプロフィール写真が空でないかを確認
if emailTextField.text?.isEmpty != true && passwordTextField.text?.isEmpty != nil, let image = profileImageView.image{
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) { result, error in
if error != nil {
print(error.debugDescription)
return
}
//UIimageを、Data型に変換
let data = image.jpegData(compressionQuality: 1.0)
//関数を呼び出し、プロフィール写真をstorageの保存、アプリ内に画像URLを保存
self.sendToDBModel.sendProfileImageData(data: data!)
}
}
}
//新規登録を押した後に呼ばれるデリゲートメソッド。
func sendProfileOKDelegete(url: String) {
urlSting = url
if urlSting.isEmpty != true {
performSegue(withIdentifier: "chat", sender: nil)
}
}
@IBAction func tapImageView(_ sender: Any) {
//カメラもしくはアルバムから、選択をする
//アラートを出す。
showAlert()
}
//カメラ立ち上げメソッド
func doCamera(){
let sourceType:UIImagePickerController.SourceType = .camera
//カメラ利用可能かチェック
if UIImagePickerController.isSourceTypeAvailable(.camera){
let cameraPicker = UIImagePickerController()
cameraPicker.allowsEditing = true
cameraPicker.sourceType = sourceType
cameraPicker.delegate = self
self.present(cameraPicker, animated: true, completion: nil)
}
}
//アルバム立ち上げメソッド
func doAlbum(){
let sourceType:UIImagePickerController.SourceType = .photoLibrary
//カメラ利用可能かチェック
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
let cameraPicker = UIImagePickerController()
cameraPicker.allowsEditing = true
cameraPicker.sourceType = sourceType
cameraPicker.delegate = self
self.present(cameraPicker, animated: true, completion: nil)
}
}
//アルバム等から選んだ写真をどうするかを記述?
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if info[.originalImage] as? UIImage != nil{
let selectedImage = info[.originalImage] as! UIImage
profileImageView.image = selectedImage
picker.dismiss(animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
//アラート
func showAlert(){
let alertController = UIAlertController(title: "選択", message: "どちらを使用しますか?", preferredStyle: .actionSheet)
let action1 = UIAlertAction(title: "カメラ", style: .default) { (alert) in
self.doCamera()
}
let action2 = UIAlertAction(title: "アルバム", style: .default) { (alert) in
self.doAlbum()
}
let action3 = UIAlertAction(title: "キャンセル", style: .cancel)
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
}
<file_sep>//
// NextViewController.swift
// struct
//
// Created by ヘパリン類似物質 on 2021/05/13.
//
import UIKit
//1、プロトコルを作成
protocol SetOKDelegate{
func setOK(check:Person)
}
class NextViewController: UIViewController {
//準備した構造体をpersonで、インスタンス化する。
var person = Person()
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var shumiTextField: UITextField!
@IBOutlet weak var movieTextField: UITextField!
//2、プロトコルを記述できるように変数に代入
var setOKDelegate:SetOKDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func done(_ sender: Any) {
person.name = nameTextField.text!
person.shumi = shumiTextField.text!
person.movie = movieTextField.text!
//3、ここで、ViewControllerのsetOKを呼び出して,personArrayにデータを入れている。->viewcontrollerにデータが渡る(personに入っているデータを、checkとして渡している。)
setOKDelegate!.setOK(check: person)
//モーダルを使用した際の、前の画面に戻る記述
dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// ViewController.swift
// Bokete-practice
//
// Created by ヘパリン類似物質 on 2021/05/15.
//
import UIKit
import Alamofire //httpリクエストを送るため等
import SwiftyJSON //JSON型のデータを扱えるようにする。
import SDWebImage //web上にある画像データを、扱えるようにする。
import Photos
class ViewController: UIViewController {
var count = 0
@IBOutlet weak var odaiImageView: UIImageView!
@IBOutlet weak var commentTextView: UITextView!
@IBOutlet weak var searchTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
commentTextView.layer.cornerRadius = 20.0
PHPhotoLibrary.requestAuthorization{(states) in
switch(states){
case .authorized: print("authorized");break
case .notDetermined: print("notdetermined");break
case .restricted: print("restricted");break
case .denied: print("denied");break
case .limited: print("limited");break
@unknown default: print("break");break
}
}
getImages(keyword: "funny")
}
@IBAction func nextOdai(_ sender: Any) {
count = count + 1
if searchTextField.text == ""{
getImages(keyword: "funny")
}else{
getImages(keyword: searchTextField.text!)
}
}
@IBAction func searchAction(_ sender: Any) {
count = 0
if searchTextField.text == ""{
getImages(keyword: "funny")
}else{
getImages(keyword: searchTextField.text!)
}
}
@IBAction func next(_ sender: Any) {
performSegue(withIdentifier: "share", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "share" {
let shareVC = segue.destination as! ShareViewController
shareVC.commentString = commentTextView.text
shareVC.resultImage = odaiImageView.image!
}
}
//検索キーワードの値をもとに、画像を持ってくる
//pixabay.com
func getImages(keyword:String) {
//API KEY = 21627028-4410cfec5802ee561c2e73b69
let url = "https://pixabay.com/api/?key=21627028-4410cfec5802ee561c2e73b69&q=\(keyword)"
//Alamofireを用いて、httpリクエストをする
AF.request(url).responseJSON{(responce) in
//responceの中に、httpリクエストをして帰ってきたJSON形式のデータが入っていると考える。
switch responce.result{
case .success:
//json変数に、受け取ったデータをJSON型で取得
let json:JSON = JSON(responce.data as Any)
//受け取ったJSONデータ内のWebFormatURLの文字列を取得する。
var imageString = json["hits"][self.count]["webformatURL"].string
//もし、JSONファイルの中にデータがなくなったら(3個しかない検索ワードの時に、4個目を取得し用途した場合)
if imageString == nil {
self.count = 0
imageString = json["hits"][self.count]["webformatURL"].string
}
//SDwebImageの仕組みを使って、imageViewに画像URl(webformatURL)を反映させる
self.odaiImageView.sd_setImage(with: URL(string: imageString!), completed: nil)
case .failure(let error):
print(error)
}
}
}
}
<file_sep>//
// SelectViewController.swift
// tiktok
//
// Created by ヘパリン類似物質 on 2021/05/24.
//
import UIKit
import SDWebImage
import AVFoundation
import SwiftVideoGenerator //音声と動画を合成する役割
class SelectMusicViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,MusicProtocol {
@IBOutlet weak var searchTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
var musicModel = MusicModel()
var player = AVAudioPlayer()
//音楽と動画を合成した動画URLを受け取る変数
var videoPath = String()
//前画面から、動画URLを受け取る
var passedURL:URL?
//遷移元から処理を受け取るクロージャのプロパティを用意
var resultHandler:((String,String,String) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
searchTextField.delegate = self
}
//音楽を検索する際に利用
@IBAction func searchButton(_ sender: Any) {
refleshData()
}
func refleshData() {
if searchTextField.text?.isEmpty != true {
//ItunesAPIへアクセスするために使用
let urlString = "https://itunes.apple.com/search?term=\(String(describing:searchTextField.text!))&entity=song&country=jp"
//パソコンが読める文字列に変換している。API公式サイトに、URLをエンコードした文字列を渡してね、と書いてあるためこのようにしている。
let encodeUrlString:String = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
musicModel.MusicDelegate = self //この委任、もしviewdidload内で書いたらどうなるかを確認する
//モデルメソッドを使用して、検索に該当するデータを取得し、配列を準備する。
musicModel.setData(resultCount: 50, encodeUrlString: encodeUrlString)
//キーボードを閉じる
searchTextField.resignFirstResponder()
}
}
//MusicModelのデリゲートメソッド(JSON解析によるデータを全て配列に準備できた際に、呼ばれるメソッド)
func catchData(count: Int) {
if count == 1 {
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return musicModel.artistNameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
//cell内の要素をタグで管理
let artWorkImageView = cell.viewWithTag(1) as! UIImageView
let musicNameLabel = cell.viewWithTag(2) as! UILabel
let artistNameLabel = cell.viewWithTag(3) as! UILabel
//JSON解析で得たデータを、cell要素に反映
artWorkImageView.sd_setImage(with: URL(string: musicModel.artWorkUrl100Array[indexPath.row]), completed:nil)
musicNameLabel.text = musicModel.trackCensoredNameArray[indexPath.row]
artistNameLabel.text = musicModel.artistNameArray[indexPath.row]
//favボタンを、プログラムで作成(選択した音楽と、動画を合成して、EditViewControllerに返す。)
let favButton = UIButton(frame: CGRect(x: 293, y: 33, width: 53, height: 53))
favButton.setImage(UIImage(named: "fav"), for: .normal) //ここのnormal、変えるとどうなるかをあとで確認
favButton.addTarget(self, action: #selector(favButtonTap(_:)), for: .touchUpInside)
favButton.tag = indexPath.row
cell.contentView.addSubview(favButton)
//プレビューボタン(音楽再生)をプログラムで作成
let playButton = UIButton(frame: CGRect(x: 16, y: 10, width: 100, height: 100))
playButton.setImage(UIImage(named: "play"), for: .normal)
playButton.addTarget(self, action: #selector(playButtonTap(_:)), for: .touchUpInside)
playButton.tag = indexPath.row
// playButton.layer.zPosition = 1.0
cell.contentView.addSubview(playButton)
return cell
}
//キーボードのreturnが押されたときの処理
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
refleshData()
searchTextField.resignFirstResponder()
return true
}
@objc func favButtonTap(_ sender:UIButton) {
//音声が流れていたら、止める
if player.isPlaying == true {
player.stop()
}
//動画と音声を合成する。合成中は、一定時間がかかるため、その間はロード画面を表示させる。
//ロード画面を表示する
LoadingView.lockView()
//動画と音声を合成する
VideoGenerator.fileName = "newAudioMovie"
VideoGenerator.current.mergeVideoWithAudio(videoUrl: passedURL!, audioUrl: URL(string: musicModel.preViewURLArray[sender.tag])!) { result in
//合成が終了したら、ロード画面を終了する
LoadingView.unlockView()
//合成が成功したかどうかでswitch文を使用する。
switch result{
case .success(let url): //ここのurlに、合成した音楽付きURLが入る
self.videoPath = url.absoluteString
if let handler = self.resultHandler{
handler(self.videoPath, self.musicModel.artistNameArray[sender.tag], self.musicModel.trackCensoredNameArray[sender.tag] )
}
self.dismiss(animated: true, completion: nil)
case .failure(let error):
print(error)
}
}
}
//プレビューボタンをタップした際に行う処理を記述する
//senderを用いることで、押されたボタン(UIButton)の情報がsenderに渡る。
//このことによって、別のスコープで定義したモノ(今回はtag番号)を使用して、処理に利用することができる。
@objc func playButtonTap(_ sender:UIButton) {
if player.isPlaying == true {
player.stop()
}
//タップしたセルのindexpath.rowを、senderを使用してこっちでも使用している。
let url = URL(string:musicModel.preViewURLArray[sender.tag])
print("kai")
print(sender.tag)
print("kai")
print(musicModel.preViewURLArray[sender.tag])
print("kai")
downLoadMusicURL(url: url!)
}
//引数の音楽を再生する関数
//途中でどんな処理を行なっているのか等、確認する。
func downLoadMusicURL(url:URL) {
var downLoadTask:URLSessionDownloadTask
downLoadTask = URLSession.shared.downloadTask(with: url, completionHandler: { url, response, error in
print(url!)
self.play(url: url!)
})
//タスクを再開するために記述。必要はないかも??
downLoadTask.resume()
}
//音楽を再生する関数
func play(url:URL){
do {
player = try AVAudioPlayer(contentsOf: url)
player.prepareToPlay()
player.volume = 1.0
print("kai")
print(url)
print("kai")
player.play()
} catch let error as NSError {
print(error.debugDescription)
}
}
//
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// MapViewController.swift
// GooGleMaps-Practice
//
// Created by ヘパリン類似物質 on 2021/06/02.
//
import UIKit
import MapKit
import GoogleMaps
class MapViewController: UIViewController, GetCoordinate {
var address = String()
var latitude = Double()
var longitude = Double()
var geocodeModel = GeocodeModel()
override func viewDidLoad() {
super.viewDidLoad()
geocodeModel.getCoordinate = self
geocodeModel.geocode(address: address)
}
//デリゲートメソッドを用いて、住所が座標に返還された後に、GoogleMapに反映させるように処理をおこなう。
func getCoordinateData(latitude: Double, longitude: Double) {
print(latitude)
print(longitude)
print("")
GMSServices.provideAPIKey("<KEY>")
let camera = GMSCameraPosition.camera(withLatitude: latitude, longitude: longitude, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: view.frame, camera: camera)
view.addSubview(mapView)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
marker.title = address
marker.map = mapView
}
//住所を井戸、経度に変換する関数
// func geocode(address:String) {
//
// CLGeocoder().geocodeAddressString(address) { placemarks, error in
//
// //緯度を変数に保存
// if let lat = placemarks?.first?.location?.coordinate.latitude {
// self.latitude = lat
// print("緯度 : \(lat)")
// }
//
// //経度を変数に保存
// if let lng = placemarks?.first?.location?.coordinate.longitude {
// self.longitude = lng
// print("経度 : \(lng)")
// print("")
// }
//
// }
//
// }
}
//緯度 : 35.1226382
//経度 : 136.9750189
<file_sep>//
// ViewController.swift
// SwiftBasicApp1
//
// Created by ヘパリン類似物質 on 2021/05/11.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var blurView: UIVisualEffectView!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var tapLabel: UILabel!
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func tap(_ sender: Any) {
count = count + 1
countLabel.text = String(count)
if count % 2 == 0 {
imageView.image = UIImage(named: "back2")
tapLabel.text = "2で割り切れる数値です。"
} else if count > 5 {
imageView.image = UIImage(named: "back3")
} else {
tapLabel.text = "奇数です。"
}
// switch count {
// case 5:
// tapLabel.text = "数値は5です。"
// break
// case 7:
// tapLabel.text = "数値は7です。"
// break
// default:
// tapLabel.text = "何でもない数値です。"
// }
}
}
<file_sep>//
// EditViewController.swift
// tiktok
//
// Created by ヘパリン類似物質 on 2021/05/24.
//
import UIKit
import AVKit //これを用いて、バックに動画のプレビューを再生する。
class EditViewController: UIViewController {
//撮影もしくは選択した動画URlが入ってきてる。
var url:URL?
//ライブラリのAVkitがあると使用可能。動画再生用にインスタンス化
var playerController:AVPlayerViewController?
var player:AVPlayer?
//selectVCで選択した楽曲名とアーティスト名を保持するため
var captionString = String()
//selectVCで作成した動画データを、受け取るため
var passedURL = String()
override func viewDidLoad() {
super.viewDidLoad()
setUPvideoPlayer(url: url!)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.isNavigationBarHidden = true
}
override func viewDidAppear(_ animated: Bool) {
setUPvideoPlayer(url: url!)
}
//引数の動画URLを再生できるように、AVPlayerViewControllerを定義し、動画を再生する関数
func setUPvideoPlayer(url:URL){
//前回までの残っていた設定を全て初期化する?
//初期化しなかったらどうなるのか、確認すること。
playerController?.removeFromParent()
player = nil
player = AVPlayer(url: url)
player?.volume = 1.0
view.backgroundColor = .black
//すでに宣言はしているが、メモリを確保するために再度宣言を行う???
playerController = AVPlayerViewController()
//ビデオをどのようなサイズ感で行うかを設定
playerController?.videoGravity = .resizeAspectFill
//動画再生の位置、大きさをここで指定する
playerController?.view.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height - 100)
//再生のシークバー的なやつだと思われる。あとでtrueにして確認
playerController?.showsPlaybackControls = false
//plawerControllerが持つobjectであるplayerの設定をしている。
playerController?.player = player
//UIviewControllerに対して、plawerControllerという子を追加する
self.addChild(playerController!)
//UIviewControllerのviewに、playerControllerのviewを追加する。
self.view.addSubview((playerController?.view)!)
//動画のリピート機能を作成する
//あるタイミングで使用したいメソッドがある場合は、NotificationCenterを使用すると良い。
//selecter = 行うメソッド name = どうゆうタイミングか object:対象は何なのか を、指定する。
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
//キャンセルボタンを、プログラムで作成する
//UIButtonのインスタンス化と、位置、大きさを作成する。
let cancelButton = UIButton(frame: CGRect(x: 10.0, y: 10.0, width: 30.0, height: 30.0))
//作成したUIButtonに、imageをセットする
cancelButton.setImage(UIImage(named: "cancel"), for: UIControl.State())
//ボタンをタップした際のアクションを決める
cancelButton.addTarget(self, action: #selector(cancel), for: .touchUpInside)
//Viewに貼る
view.addSubview(cancelButton)
//動画を再生する
player?.play()
}
//キャンセルボタンを押したときに呼ばれるメソッド
@objc func cancel() {
//画面を戻る
self.navigationController?.popViewController(animated: true)
}
//動画の再生時間が終わったときに、呼ばれるメソッド
@objc func playerItemDidReachEnd(_ notification:Notification) {
if self.player != nil {
self.player?.seek(to: CMTime.zero)
self.player?.volume = 1
self.player?.play()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "selectVC" {
let selectVC = segue.destination as! SelectMusicViewController
selectVC.passedURL = url
//Dispatchを使用することによって、画面遷移が行わレた後も、ここの判定が継続して行われるようになる
//あとで、dispatchを消しても同じような処理が行われるかどうかを確認する
DispatchQueue.global().async {
//クロージャを用いることによって、selectVC側でresultHundlerの値が入るまではここの処理が呼ばれない
selectVC.resultHandler = {
url,text1,text2 in
//入ってきた動画URLを使用し、作成された動画を流す。
self.setUPvideoPlayer(url: URL(string: url)!)
self.captionString = text1 + "\n" + text2
self.passedURL = url
}
}
}
//shareVCに遷移する場合は、合成済み動画データと音楽情報を遷移先にわたす。
if segue.identifier == "shareVC"{
let shareVC = segue.destination as! ShareViewController
shareVC.captionString = self.captionString
shareVC.passedURL = passedURL
}
}
@IBAction func next(_ sender: Any) {
//音楽合成済みの動画データがない場合は、遷移ができない。
if captionString.isEmpty != true {
performSegue(withIdentifier: "shareVC", sender: nil)
}else{
print("楽曲を選択してください")
}
}
@IBAction func showSelectVC(_ sender: Any) {
performSegue(withIdentifier: "selectVC", sender: nil)
}
}
<file_sep>//
// Car.swift
// CalcApp
//
// Created by ヘパリン類似物質 on 2021/05/11.
//
import Foundation
class Car{
var frontWheel = 0
var rearWheel = 0
//rubyでいう、initialize,初期化を表す。
init(){
frontWheel = 2
rearWheel = 2
}
//func は、 機能を表す。
func drive(){
print ("運転開始")
print("前輪: \(frontWheel)")
print("後輪: \(rearWheel)")
}
//引数を与える、メソッドの記述方法 rubyとは違い、データ型を指定する必要がある。
func move(toBack:String, human:String, count:Int){
print("\(toBack),\(human),\(count) ")
}
func plusAndMinus(num1:Int, num2:Int) -> Int{
return num1 + num2
}
}
<file_sep>//
// CheckViewController.swift
// OdaiApp
//
// Created by ヘパリン類似物質 on 2021/05/19.
//
import UIKit
import Firebase
import FirebaseFirestore
class CheckViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var idString = String()
var odaiString = String()
var dataSets:[AnswersModel] = []
let db = Firestore.firestore()
@IBOutlet weak var odaiLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
odaiLabel.text = odaiString
tableView.delegate = self
tableView.dataSource = self
// tableView.reloadData()
//カスタムセルを使用する際の記述
tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "Cell")
if UserDefaults.standard.object(forKey: "documentID") != nil {
idString = UserDefaults.standard.object(forKey: "documentID") as! String
}
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.isNavigationBarHidden = false
loadData()
}
//fireStoreから、answerデータを取ってくる関数
func loadData() {
//DB上のAnswersを、取ってくる
db.collection("Answers").order(by: "postDate").addSnapshotListener { snapShot, error in
self.dataSets = []
if error != nil {
print(error.debugDescription)
return
}
//snapShotDocに入っているものは、まだドキュメントの集合体
if let snapShotDoc = snapShot?.documents {
//ここで、集合体を一つずつ確認していく
for doc in snapShotDoc {
//ドキュメントのデータにアクセスできる形にして、dataに代入
let data = doc.data()
//いいね追加の際の記述↓
if let answer = data["answer"] as? String, let userName = data["userName"] as? String, let likeCount = data["like"] as? Int, let likeFlagDic = data["likeFlagDic"] as? Dictionary<String,Bool>{
//ここで判断しているのは、fireStoreからとってきたlikeFlagDicの値の中に、ドキュメントのidがしっかり保存されているかを確認している
if likeFlagDic["\(doc.documentID)"] != nil{
let answerModel = AnswersModel(answers: answer, userName: userName, docID: doc.documentID, likeCount: likeCount, likeFlagDic: likeFlagDic)
self.dataSets.append(answerModel)
}
}
//いいね追加の際の記述↑
//もし、各値が存在していたら(doc.documentIDで、ドキュメントIDを取得している。(後々、この値を用いてどのデータかを識別するため。))
// if let answer = data["answer"] as? String, let userName = data["userName"] as? String, let docID = doc.documentID as? String {
//
// print(answer)
// print("aoyama")
// //answersModel型(構造体)のデータを作成
// let answerModel = AnswersModel(answers: answer, userName: userName, docID: docID)
//
// //作成したデータを、配列に加える。
// self.dataSets.append(answerModel)
// }
}
// self.dataSets.reverse()
//for文でデータを配列に入れ終わったら、tableViewをリロードして、反映させる。
self.tableView.reloadData()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSets.count
}
func numberOfSections(in tableView: UITableView) -> Int {
1
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
tableView.estimatedRowHeight = 100
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//使用するセルを特定
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
//ラベルの文字の多さによって、大きさが自動で変わるセルを作成する
tableView.rowHeight = 150 //各セルのデフォルトの高さを指定。
//いいね機能実装の際の記述 ↓
cell.answerLabel.numberOfLines = 0
cell.answerLabel.text = "\(self.dataSets[indexPath.row].userName)君の回答\n\(self.dataSets[indexPath.row].answers)"
//ここで、cellごとにタグ番号を割り振ることで、いいねをする際にどのセルのいいねをするかを判別できるようにする。
cell.likeButton.tag = indexPath.row
cell.countLabel.text = String(self.dataSets[indexPath.row].likeCount) + "いいね"
//プログラム によるボタンをタップした後のアクションはどこを参照するのかを設定しておく
cell.likeButton.addTarget(self, action: #selector(like(_:)), for: .touchUpInside)
//もし自分のidがlikeFragdicの中のデータに含まれていたら
if (self.dataSets[indexPath.row].likeFlagDic[idString] != nil) == true {
let flag = dataSets[indexPath.row].likeFlagDic[idString]
//もし、いいねが押されていたら == 値がtrueだったら、cellのlikeButtonのイメージを、セットする。(bUIButtonのため、setImageを用いる。)
if flag! as! Bool == true{
cell.likeButton.setImage(UIImage(named: "like"), for: .normal)
} else {
cell.likeButton.setImage(UIImage(named: "notlike"), for: .normal)
}
}
//いいね機能実装の際の記述 ↑
// //ここで、セル内のどの要素を指定するかを、タグ番号を用いて指定している。
// let answerLabel = cell.contentView.viewWithTag(1) as! UILabel
// answerLabel.numberOfLines = 0 //UIlabelなので、このプロパティを指定できる。
// //Firebaseからとってきたデータを利用して、Labelにはる。
// answerLabel.text = "\(self.dataSets[indexPath.row].userName)君の回答\n\(self.dataSets[indexPath.row].answers)"
// print(answerLabel.text)
return cell
}
//いいねボタンを押した際の動き
@objc func like(_ sender:UIButton) {
var count = Int()
//ここでのsenderは、tableviewでのlikeButtonのことを指す。だから、tagのプロパティを使用することができる。
//かつ、現在の
let flag = self.dataSets[sender.tag].likeFlagDic[idString]
//もし、
if flag == nil {
count = self.dataSets[sender.tag].likeCount + 1
db.collection("Answers").document(dataSets[sender.tag].docID).setData(["likeFlagDic":[idString:true]], merge: true)
} else {
if flag as! Bool == true {
count = self.dataSets[sender.tag].likeCount - 1
db.collection("Answers").document(dataSets[sender.tag].docID).setData(["likeFlagDic":[idString:false]], merge: true)
}else{
count = self.dataSets[sender.tag].likeCount + 1
db.collection("Answers").document(dataSets[sender.tag].docID).setData(["likeFlagDic":[idString:true]], merge: true)
}
}
//count情報を送信
db.collection("Answers").document(dataSets[sender.tag].docID).updateData(["like" : count], completion: nil)
tableView.reloadData()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//画面遷移
let commentVC = self.storyboard?.instantiateViewController(identifier: "commentVC") as! CommentViewController
commentVC.idString = dataSets[indexPath.row].docID
commentVC.kaitouString = "\(dataSets[indexPath.row].userName)君の回答\n\(dataSets[indexPath.row].answers)"
self.navigationController?.pushViewController(commentVC, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// TableViewController.swift
// Qiita-HashTag
//
// Created by ヘパリン類似物質 on 2021/06/04.
//
import UIKit
import FirebaseFirestore
import ActiveLabel
class TableViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
//取得したデータが入る配列
var textArray = [String]()
//StoryBoard上のtableViewと紐づけています。
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//プロトコルの委任
tableView.delegate = self
tableView.dataSource = self
//データの取得、およびtableViewを読み込むメソッドを使用
loadData()
}
//tableのセルの数は、取得するデータ数に設定
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
textArray.count
}
//取得してきたデータを、セル内のラベル(textLabelに反映
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//storyBoard上のセルと、紐付けを行なっています。
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let textLabel = cell.contentView.viewWithTag(1) as! ActiveLabel // ActiveLabelに変更する
//取得してきた文字列をセルに反映しています。
textLabel.text = textArray[indexPath.row]
//ハッシュタグをタップしたらどうなるかの処理を追加記述 ==============================
textLabel.handleHashtagTap { hashTag in
//storyBoard上のhashTagViewControllerをインスタンス化
let hashVC = self.storyboard?.instantiateViewController(identifier: "hashVC") as! HashTagViewController
//hashVCへ、タップしたハッシュタグの情報を渡す
hashVC.hashTag = hashTag
//画面遷移
self.navigationController?.pushViewController(hashVC, animated: true)
}
//ハッシュタグをタップしたらどうなるかの処理を追加記述 ==============================
return cell
}
//セルの高さは、適当に設定しています。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return view.frame.size.height / 10
}
//セクションの数は1です
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//fireStoreから、データを取得する関数
func loadData(){
Firestore.firestore().collection("collection").addSnapshotListener { snapShot, error in
if let snapShotDoc = snapShot?.documents{
for doc in snapShotDoc {
let data = doc.data()
if let text = data["text"] as? String {
print(text)
//取得してきたデータを、配列に入れていく。
self.textArray.append(text)
}
}
//データを取得し終わったら、tableViewを更新する。
self.tableView.reloadData()
}
}
}
}
<file_sep>//
// ChatViewController.swift
// ChatApp
//
// Created by ヘパリン類似物質 on 2021/05/18.
//
import UIKit
import Firebase
import SDWebImage
class ChatViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var roomName = String()
var imageString = String()
let db = Firestore.firestore()
//構造体が入る配列は、このように指定する・
var messages:[Message] = []
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var messageTextField: UITextField!
//ログアウトボタンの追加
var logoutBarButtonItem: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
//カスタムセルを使用する宣言
tableView.register(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "Cell") //ここが実際にいるのかどうか、確認すること。
//アプリ内に保存したユーザイメージデータを引っ張ってきて、変数に入れる。
if UserDefaults.standard.object(forKey: "userImage") != nil {
imageString = UserDefaults.standard.object(forKey: "userImage") as! String
}
if roomName == "" {
roomName = "ALL"
}
self.navigationItem.title = roomName
loadMessages(roomName: roomName)
logoutBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addBarButtonTapped(_:)))
logoutBarButtonItem.tintColor = .black
self.navigationItem.rightBarButtonItem = logoutBarButtonItem
}
@objc func addBarButtonTapped(_ sender: UIBarButtonItem) {
let registerVC = storyboard?.instantiateViewController(identifier: "registerVC")
do {
try Auth.auth().signOut()
} catch let error as NSError {
print(error.localizedDescription)
}
navigationController?.pushViewController(registerVC!, animated: true)
print("【+】ボタンが押された!")
}
func loadMessages(roomName:String) {
db.collection(roomName).order(by: "date").addSnapshotListener { snapShot, error in
self.messages = []
if error != nil {
print(error.debugDescription)
return
}
if let snapShotDoc = snapShot?.documents{
for doc in snapShotDoc {
let data = doc.data() //これで、保存されているデータの各値の情報が辞書型で取得できるようになった
//各変数に、保存されているデータを種類別に保存
if let sender = data["sender"] as? String, let body = data["body"] as? String, let imageString = data["imageString"] as? String {
//構造体型のデータをインスタンス化
let newMessage = Message(sender: sender, body: body, imageString: imageString)
self.messages.append(newMessage)
DispatchQueue.main.async {
self.tableView.reloadData()
let indexPath = IndexPath(row: self.messages.count - 1, section: 0)
self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//カスタムセルを使用する宣言
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MessageCell
//チャットデータが入る配列から、データを取得
let message = messages[indexPath.row]
//チャット本文を代入
cell.label.text = message.body
//チャットを送信したユーザによって、imageを表示するかどうかを判定。
if message.sender == Auth.auth().currentUser?.email{
cell.leftImageView.isHidden = true
cell.rightImageview.isHidden = false
cell.rightImageview.sd_setImage(with: URL(string: imageString), completed: nil)
cell.leftImageView.sd_setImage(with: URL(string: message.imageString), completed: nil)
cell.backView.backgroundColor = .systemTeal
cell.label.textColor = .black
} else {
cell.leftImageView.isHidden = false
cell.rightImageview.isHidden = true
cell.rightImageview.sd_setImage(with: URL(string: message.imageString), completed: nil)
cell.leftImageView.sd_setImage(with: URL(string: imageString), completed: nil)
cell.backView.backgroundColor = .systemGreen
cell.label.textColor = .black
}
return cell
}
@IBAction func send(_ sender: Any) {
if let messageBody = messageTextField.text, let sender = Auth.auth().currentUser?.email {
//FireStoreにチャットデータを送信する。保存キーをルーム名としつつ、(送信者、チャット内容、ユーザ画像、時刻)
db.collection(roomName).addDocument(data: ["sender":sender, "body":messageBody, "imageString":imageString, "date": Date().timeIntervalSince1970]) { error in
if error != nil{
print(error.debugDescription)
return
}
DispatchQueue.main.async {
self.messageTextField.text = ""
self.messageTextField.resignFirstResponder()
}
}
}
}
}
<file_sep>//
// CommentModel.swift
// OdaiApp
//
// Created by ヘパリン類似物質 on 2021/05/20.
//
import Foundation
struct CommentModel {
var userName:String
var comment:String
var postDate:Double
}
<file_sep>//
// ViewController.swift
// GooGleMaps-Practice
//
// Created by ヘパリン類似物質 on 2021/06/01.
//
import UIKit
import GoogleMaps
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
//アプリの使用中に、ユーザーに位置情報サービスの使用許可を求める記述
manager.requestWhenInUseAuthorization()
//ユーザーの現在地を報告する更新の生成 ここで、デバイスの現在位置をmanagerに設定している?
manager.startUpdatingLocation()
GMSServices.provideAPIKey("<KEY>")
//ここで、マップ表示時の位置を決めている
let camera = GMSCameraPosition.camera(withLatitude: 35.689506, longitude: 139.6917, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: self.view.frame, camera: camera)
self.view.addSubview(mapView)
//ここで、マップにつけるマーカーの位置を決めている。
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
//マーカーのタイトル等を、決めている
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//locationsに、位置情報が入る。locationに何も入らなかったら、処理をreturnする。
guard let location = locations.first else {
return
}
//coordinate == 座標
let coordinate = location.coordinate
//取得した座標から、
let camera = GMSCameraPosition.camera(withLatitude: coordinate.latitude, longitude: coordinate.longitude, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: self.view.frame, camera: camera)
self.view.addSubview(mapView)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
//マーカーのタイトル等を、決めている
marker.title = "現在地です"
marker.snippet = "現在地だよ"
marker.map = mapView
}
}
//やりたいこと => お店の位置を登録 => 位置情報をタップしたら、そこのお店にマーカーがついて、名前とかが表示されるようにする。
//そのためには、住所と座標を変換するプログラムが必要
//fireStoreには、住所で保存
<file_sep>//
// Feeds.swift
// meigenApp
//
// Created by ヘパリン類似物質 on 2021/05/17.
//
import Foundation
struct Feeds {
let userName:String
let quote:String
let profileURL:String
}
<file_sep>//
// ViewController.swift
// SwiftCountUp-1
//
// Created by ヘパリン類似物質 on 2021/05/11.
//
import UIKit
class ViewController: UIViewController {
var count = 0
@IBOutlet weak var countUpLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
countUpLabel.text = "0"
// Do any additional setup after loading the view.
}
@IBAction func plus(_ sender: Any) {
//カウントアップする
count = count + 1
//ラベルに数字を表示する
countUpLabel.text = String(count)
//10以上になったら、数字を黄色にする
if (count >= 10) {
changeTextColor()
}
}
@IBAction func minus(_ sender: Any) {
//カウントダウンする
count = count - 1
//ラベルに数字を表示する
countUpLabel.text = String(count)
//0以下になったら、数字を白にする
if (count <= 0) {
resetColor()
}
}
func changeTextColor(){
countUpLabel.textColor = .yellow
}
func resetColor(){
countUpLabel.textColor = .blue
}
}
<file_sep>//
// ViewController.swift
// CalcApp
//
// Created by ヘパリン類似物質 on 2021/05/11.
//
import UIKit
//carモデルの設計図をもとに、carModelという実体を作成する。
var carModel = Car()
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
carModel.frontWheel = 20
carModel.rearWheel = 10
}
@IBAction func doAction(_ sender: Any) {
//carModelの設計図内で作成されたメソッド(drive)を呼び出している。
carModel.drive()
carModel.move(toBack: "後ろ", human: "私", count: 3)
let totalWheels = carModel.plusAndMinus(num1: carModel.frontWheel, num2: carModel.rearWheel)
print("タイヤの合計数は、\(totalWheels)です。")
}
}
<file_sep>//
// FeedViewController.swift
// meigenApp
//
// Created by ヘパリン類似物質 on 2021/05/17.
//
import UIKit
import BubbleTransition //画面遷移の際のアニメーション
import Firebase
import FirebaseFirestore //いらない説濃厚
import SDWebImage //画像のURLを使用するために使用
import ViewAnimator //???
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var interactiveTransition:BubbleInteractiveTransition!
let db = Firestore.firestore()
var feeds:[Feeds] = [] //モデルと、構造体の違いとは??
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
//カスタムセルを作成 セルを別ファイルで自分で作成した場合は、表示させたいUIViewControllerで定義する必要がある。
tableView.register(UINib(nibName: "FeedCell", bundle: nil), forCellReuseIdentifier: "feedcell")
tableView.separatorStyle = .none //テーブルの枠線を消す。
loadData()
}
//firestoreから、データを受信する。
func loadData(){
//投稿されたものを受信する,order(by: "createAt")で、古い順にデータを取得している事になる。
db.collection("feed").order(by: "createAt").addSnapshotListener { snapShot, error in
self.feeds = []
//エラーがあった場合、終了
if error != nil{
print(error.debugDescription)
return
}
if let snapShotDoc = snapShot?.documents{
//保存されているデータの数だけ繰り返す。
for doc in snapShotDoc {
let data = doc.data()
//もしデータがしっかり保存されていたら
if let userName = data["userName"] as? String, let quote = data["quote"] as? String, let photoURL = data["photoURL"] as? String{
let newFeeds = Feeds(userName: userName, quote: quote, profileURL: photoURL)
//現状のfireStoreのデータを、feedという構造体で構成された配列で保持する。
self.feeds.append(newFeeds)
//このままだと、古い順にデータが並んでいるので、順番を反転させる。
self.feeds.reverse()
//非同期処理のための記述
DispatchQueue.main.async {
self.tableView.tableFooterView = nil
self.tableView.reloadData()
}
}
}
}
}
}
//セルの数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feeds.count
}
//セルの中身
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//カスタムセルを記述したController(FeedCell.swift)の、クラス名と、Identifierをキーにして、何を参照してセルを作成するかを決める。
let cell = tableView.dequeueReusableCell(withIdentifier: "feedcell", for: indexPath) as! FeedCell
cell.userNameLabel.text = "\(feeds[indexPath.row].userName)さんを表す名言"
cell.quoteLabel.text = (feeds[indexPath.row].quote)
cell.profileImageView.sd_setImage(with: URL(string: feeds[indexPath.row].profileURL), completed: nil)
return cell
}
//セル間の高さを決定する
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return view.frame.size.height / 10
}
//セル間の表示のプロパティ?を編集する
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let marginView = UIView()
marginView.backgroundColor = .clear
return marginView
}
//セルのフッターの高さを調節する。
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return .leastNonzeroMagnitude
}
@IBAction func back(_ sender: Any) {
dismiss(animated: true, completion: nil)
interactiveTransition.finish()
}
}
<file_sep>//
// SoundFile.swift
// questionApp
//
// Created by ヘパリン類似物質 on 2021/05/14.
//
import Foundation
import AVFoundation //音声ファイル関係
class SoundFile {
var player:AVAudioPlayer?
//filename:音声ファイル名,extendionName:拡張子の名前
func playsound(filename:String, extensionName:String) {
//再生する音楽ファイルのデータをsoundURLに格納
let soundURL = Bundle.main.url(forResource: filename, withExtension: extensionName)
//do-catch文---doの中身でエラーが生じた場合に、catchの中身が動く
do {
player = try AVAudioPlayer(contentsOf: soundURL!)
player!.play()
} catch {
print("エラーです!")
}
}
}
<file_sep>//
// DataSet.swift
// instagram
//
// Created by ヘパリン類似物質 on 2021/05/23.
//
import Foundation
struct DataSet {
let userID:String
let userName:String
let comment:String
let profileImage:String
let postDate:Double
let contentImage:String
}
<file_sep>
//プロフィールイメージをFireStorageへ保存、および受信するためのメソッド
import Foundation
import FirebaseStorage
import FirebaseFirestore
class SendDBModel {
//会員登録の際に使用する初期化設定
init(){
}
//投稿の際に使用する変数
var userID = String()
var userName = String()
var comment = String()
var userImageString = String()
var contentImageData = Data()
var db = Firestore.firestore()
//投稿の際に使用する初期化設定
init(userID:String, userName:String, comment:String, userImageString:String, contentImageData:Data) {
self.userID = userID
self.userName = userName
self.comment = comment
self.userImageString = userImageString
self.contentImageData = contentImageData
}
//投稿データを、fireStoreに保存する処理を記述
func sendData(roomNumber:String) {
//FireStorageの、Imagesフォルダの中に、一意の文字列+その時の日付+jpgというデータの保存先を変数に入れたイメージ
let imageRef = Storage.storage().reference().child("images").child("\(UUID().uuidString + String(Date().timeIntervalSince1970)).jpg")
//imageRefという保存先に、というデータをまずは保存する。
imageRef.putData(Data(contentImageData), metadata: nil) { metadata, error in
if error != nil {
print(error.debugDescription)
return
}
//投稿画像URlが変数urlに保存される。
imageRef.downloadURL { [self] url, error in
if error != nil {
print(error.debugDescription)
return
}
//roomNumberをキーにして、辞書型で以下のデータを保存する。
self.db.collection(roomNumber).document().setData(["userID" : self.userID as Any, "userName" : self.userName as Any, "comment" : self.comment as Any, "userImage" : self.userImageString, "contentImage" : url?.absoluteString as Any, "postDate" : Date().timeIntervalSince1970 ])
}
}
}
//プロフィール画像を保存し、会員登録するためのメソッド
func sendProfileImageData(data:Data) {
//関数の引数で受け取ったデータを、UIImage型で、imageに格納
let image = UIImage(data: data)
//imageを、Data型に変更しつつ、容量を圧縮
let profileImage = image?.jpegData(compressionQuality: 0.1)
//FireStorageの、profileImageフォルダの中に、一意の文字列+その時の日付+jpgというデータの保存先を変数に入れたイメージ
let imageRef = Storage.storage().reference().child("profileImage").child("\(UUID().uuidString + String(Date().timeIntervalSince1970)).jpg")
//imageRefという保存先に、profileImageというデータをまずは保存する。
imageRef.putData(Data(profileImage!), metadata: nil) { metadata, error in
if error != nil {
print(error.debugDescription)
return
}
//ここで、帰ってきた画像URLを、アプリ内に保存する
imageRef.downloadURL { url, error in
if error != nil {
print(error.debugDescription)
return
}
//受け取ったURLを、String型に変換して、アプリ内に保存
UserDefaults.standard.set(url?.absoluteString, forKey: "userImage")
}
}
}
//ハッシュタグ用の関数。各ハッシュタグのルームを作成するような感じ
func sendHashTag(hashTag:String) {
//FireStorageの、Imagesフォルダの中に、一意の文字列+その時の日付+jpgというデータの保存先を変数に入れたイメージ
let imageRef = Storage.storage().reference().child("hashTag").child("\(UUID().uuidString + String(Date().timeIntervalSince1970)).jpg")
//imageRefという保存先に、というデータをまずは保存する。
imageRef.putData(Data(contentImageData), metadata: nil) { metadata, error in
if error != nil {
print(error.debugDescription)
return
}
//投稿画像URlが変数urlに保存される。
imageRef.downloadURL { [self] url, error in
if error != nil {
print(error.debugDescription)
return
}
//hashTagをキーにして、辞書型で以下のデータを保存する。
self.db.collection(hashTag).document().setData(["userID" : self.userID as Any, "userName" : self.userName as Any, "comment" : self.comment as Any, "userImage" : self.userImageString, "contentImage" : url?.absoluteString as Any, "postDate" : Date().timeIntervalSince1970 ])
}
}
}
}
<file_sep>//
// IntroViewController.swift
// newsApp
//
// Created by ヘパリン類似物質 on 2021/05/15.
//
import UIKit
import Lottie
//スクロールビュー用のプロトコル追加
class IntroViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
var onboardArray = ["1","2","3","4","5"]
var onboardStringArray = ["あいう","かき","さっさ","っさささ","なんで!",]
override func viewDidLoad() {
super.viewDidLoad()
//ScrollViewのページング(横にスライドしていくやつ)が使用できるようになる。
scrollView.isPagingEnabled = true
setUpScroll()
//Lottieを用いたアニメーションの利用記述
//アニメーションは5種類あるので、for文で回す
for i in 0...4 {
let animationView = AnimationView()
//どのアニメーションファイルを使用するかを規定
let animation = Animation.named(onboardArray[i])
//アニメーションの大きさを決める
animationView.frame = CGRect(x: CGFloat(i) * view.frame.size.width, y: 0, width: view.frame.size.width, height: view.frame.size.height)
//アニメーションの内容を決める
animationView.animation = animation
//アニメーションのプロパティをいくつか設定
animationView.contentMode = .scaleAspectFit
animationView.loopMode = .loop
animationView.play()
scrollView.addSubview(animationView)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isNavigationBarHidden = true
}
func setUpScroll(){
scrollView.delegate = self
//UIscrollViewのサイズを規定
scrollView.contentSize = CGSize(width: view.frame.size.width * 5, height: scrollView.frame.size.height)
for i in 0...4{
//使用するUILabelの大きさを規定する
let onboardLabel = UILabel(frame: CGRect(x: CGFloat(i) * view.frame.size.width, y: view.frame.size.height / 3, width: view.frame.size.width, height: scrollView.frame.size.height))
onboardLabel.font = UIFont.boldSystemFont(ofSize: 15.0)
onboardLabel.textAlignment = .center
onboardLabel.text = onboardStringArray[i]
// onboardLabel.backgroundColor = .blue
//作成したものを画面のLabelに追加
scrollView.addSubview(onboardLabel)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// RoomViewController.swift
// ChatApp
//
// Created by ヘパリン類似物質 on 2021/05/18.
//
import UIKit
import ViewAnimator
import FirebaseAuth
class RoomViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var roomNameArray = ["誰でも話そうよ!","20代たまり場!","1人ぼっち集合","地球住み集合!!","好きなYoutuberを語ろう","大学生集合!!","高校生集合!!","中学生集合!!","暇なひと集合!","A型の人!!"]
var roomImageStringArray = ["0","1","2","3","4","5","6","7","8","9"]
@IBOutlet weak var tableview: UITableView!
//ログアウトボタンの追加
var logoutBarButtonItem: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
tableview.isHidden = true
logoutBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addBarButtonTapped(_:)))
logoutBarButtonItem.tintColor = .black
self.navigationItem.rightBarButtonItem = logoutBarButtonItem
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview.isHidden = false
// let animation = AnimationType.from(direction: .top, offset: 300)
// UIView.animate(views: tableView.visibleCells, animations: [animation],delay: 0,duration: 2)
}
@objc func addBarButtonTapped(_ sender: UIBarButtonItem) {
print("【+】ボタンが押された!")
do {
try Auth.auth().signOut()
} catch let error as NSError {
print(error.localizedDescription)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return roomNameArray.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "RoomCell", for: indexPath)
//デフォルトのセル表示を利用する。
cell.imageView?.image = UIImage(named: roomImageStringArray[indexPath.row])
cell.textLabel?.text = roomNameArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "roomChat", sender: indexPath.row) //ここで飛ばしたsenderは、prepareForSegueのsenderに入る!
}
//ChatViewControllerに処理を渡す前に、ここのしょりが行われ、room名を特定する。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let roomChatVC = segue.destination as! ChatViewController
roomChatVC.roomName = roomNameArray[sender as! Int]
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// Animal.swift
// questionApp
//
// Created by ヘパリン類似物質 on 2021/05/14.
//
import Foundation
class Animal {
func breath(){
print("息をしています。")
}
}
<file_sep>//
// human.swift
// questionApp
//
// Created by ヘパリン類似物質 on 2021/05/14.
//
import Foundation
class Human:Animal {
override func breath() {
super.breath() //継承元のメソッドは呼び出さないと動かない。
profile()
}
func profile(){
print("私は凱です。")
}
}
<file_sep>//
// Message.swift
// ChatApp
//
// Created by ヘパリン類似物質 on 2021/05/18.
//
import Foundation
struct Message {
let sender:String
let body:String
let imageString:String
}
<file_sep>//
// NewsItems.swift
// newsApp
//
// Created by ヘパリン類似物質 on 2021/05/16.
//
import Foundation
class NewsItems{
var title:String?
var url:String?
var pubDate:String?
}
<file_sep>//
// ViewController.swift
// swift-Timer
//
// Created by ヘパリン類似物質 on 2021/05/11.
//
import UIKit //ツールを使用できるようにしている。
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
var timer = Timer() //Timerクラスという設計図から、timerを生成
var count = Int() //Int型の変数を指定
var imageArray = [UIImage]() //UIImage型の配列を指定。
//swiftは、配列を作る際なども、クラスを指定しておく必要がある。
override func viewDidLoad() {
super.viewDidLoad()
//stopボタンを押せなくする。
stopButton.isEnabled = false
//プロパティ-・・・クラスが持っている使用できるメソッド的なもの
count = 0
//for文を用いて、logを表示させる。
for i in 0..<5{
print(i)
let image = UIImage(named: "\(i)") //UIImageは、assetsに入れたデータに対応したクラス?
imageArray.append(image!)
}
//初期画像を表示
imageView.image = UIImage(named: "0" )
}
func startTimer() {
//0.2秒ごとに、timerUpdateという関数を呼ぶ処理
timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)
}
@objc func timerUpdate(){
count = count + 1
if count > 4 {
count = 0
}
imageView.image = imageArray[count]
}
@IBAction func start(_ sender: Any) {
//imageViewのimageに、画像を反映させていく。
//startボタンを押せなくする。
startButton.isEnabled = false
stopButton.isEnabled = true
startTimer()
}
@IBAction func stop(_ sender: Any) {
//imageViewに表示されている画像の流れをストップする。
//startButtonを押せるようにする。
startButton.isEnabled = true
stopButton.isEnabled = false
timer.invalidate() //timerを終了させる。
}
}
<file_sep>//
// ShareViewController.swift
// tiktok
//
// Created by ヘパリン類似物質 on 2021/05/24.
//
import UIKit
import AVKit
import Photos //Photosってどこで使うか、要確認
class ShareViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
//editVCから、選択した音楽の情報と、合成した動画URLを取得する
var captionString = String()
//音声データも入っているものだと確認済み
var passedURL = String()
//動画再生用
var player:AVPlayer?
var playerController:AVPlayerViewController?
override func viewDidLoad() {
super.viewDidLoad()
//キーボードに合わせて表示を調節する記述
let notification = NotificationCenter.default
notification.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
notification.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.isNavigationBarHidden = true
}
override func viewDidAppear(_ animated: Bool) {
print(passedURL)
print("kai")
//完成されたURL(passedURL)を使用して、動画を再生する
setUPvideoPlayer(url: URL(string: passedURL)!)
}
//ここの関数、以前学んだ記述方法でやった場合とで、どのような挙動の違いが出るか確認する。
@objc func keyboardWillShow(notification: Notification?) {
let rect = (notification?.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
let duration: TimeInterval? = notification?.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
UIView.animate(withDuration: duration!) {
self.view.transform = CGAffineTransform(translationX: 0, y: -(rect?.size.height)!)
}
}
@objc func keyboardWillHide(notification: Notification?) {
let duration: TimeInterval? = notification?.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? Double
UIView.animate(withDuration: duration!) {
self.view.transform = CGAffineTransform.identity
}
}
//動画再生メソッド
func setUPvideoPlayer(url:URL){
//前回までの残っていた設定を全て初期化する?
//初期化しなかったらどうなるのか、確認すること。
playerController?.removeFromParent()
player = nil
player = AVPlayer(url: url)
player?.volume = 1.0
view.backgroundColor = .black
//すでに宣言はしているが、メモリを確保するために再度宣言を行う???
playerController = AVPlayerViewController()
//ビデオをどのようなサイズ感で行うかを設定
playerController?.videoGravity = .resizeAspectFill
//動画再生の位置、大きさをここで指定する
playerController?.view.frame = CGRect(x: 23, y: 72, width: view.frame.size.width - 100, height: view.frame.size.height - 260)
playerController?.view.backgroundColor = .green
//再生のシークバー的なやつだと思われる。あとでtrueにして確認
playerController?.showsPlaybackControls = false
//plawerControllerが持つobjectであるplayerの設定をしている。
playerController?.player = player
//UIviewControllerに対して、plawerControllerという子を追加する
self.addChild(playerController!)
//UIviewControllerのviewに、playerControllerのviewを追加する。
self.view.addSubview((playerController?.view)!)
//動画のリピート機能を作成する
//あるタイミングで使用したいメソッドがある場合は、NotificationCenterを使用すると良い。
//selecter = 行うメソッド name = どうゆうタイミングか object:対象は何なのか を、指定する。
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
//動画を再生する
player?.play()
}
@objc func playerItemDidReachEnd(_ notification:Notification) {
if self.player != nil {
self.player?.seek(to: CMTime.zero)
self.player?.volume = 1
self.player?.play()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
textView.resignFirstResponder()
}
//動画URLから、アルバムへと保存をする。
@IBAction func savePhotoLibrary(_ sender: Any) {
PHPhotoLibrary.shared().performChanges {
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(string: self.passedURL)!)
} completionHandler: { result, error in
if error != nil{
print(error.debugDescription)
return
}
if result == true {
print("動画を保存しました!!")
}
}
}
@IBAction func share(_ sender: Any) {
//シェアしたいitemは、動画、楽曲の情報、コメント
//まず、シェアしたいモノをまとめたAny型の配列を作成
let activityItems = [URL(string: passedURL) as Any, "\(textView.text)\n\(captionString)\n#Swiftアプリ練習用"] as Any
let activityController = UIActivityViewController(activityItems: activityItems as! [Any], applicationActivities: nil)
//ここから下の記述が、どのような変化をもたらすのか、確認する
activityController.popoverPresentationController?.sourceView = self.view
activityController.popoverPresentationController?.sourceRect = self.view.frame
self.present(activityController, animated: true, completion: nil)
}
//トップページへ戻るボタン
@IBAction func back(_ sender: Any) {
player?.pause()
player = nil
//一番最初に戻る記述
self.navigationController?.popToRootViewController(animated: true)
}
}
<file_sep>//
// ViewController.swift
// CameraApp
//
// Created by ヘパリン類似物質 on 2021/05/14.
//
import UIKit
import Photos
class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var backImageView: UIImageView!
//チェックモデルのインスタンス化
var checkPermission = CheckPermisson()
override func viewDidLoad() {
super.viewDidLoad()
checkPermission.checkCamera()
}
@IBAction func camera(_ sender: Any) {
let sourceType:UIImagePickerController.SourceType = .camera
createImagePicker(sourcetype: sourceType)
}
@IBAction func album(_ sender: Any) {
let sourceType:UIImagePickerController.SourceType = .photoLibrary
createImagePicker(sourcetype: sourceType)
}
@IBAction func share(_ sender: Any) {
let text = "hello!!"
//データを圧縮する
let image = backImageView.image?.jpegData(compressionQuality: 0.5)
let item = [text, image] as [Any]
let activityVC = UIActivityViewController(activityItems: item, applicationActivities: nil)
//self.presentで、何かしらの動作を立ち上げるタイミング
self.present(activityVC, animated: true, completion: nil)
}
//引数に立ち上がるアプリ(カメラやアルバム)を渡すことで、そのアプリを立ち上げてくれるメソッド
func createImagePicker(sourcetype:UIImagePickerController.SourceType){
let cameraPicker = UIImagePickerController()
cameraPicker.sourceType = sourcetype
cameraPicker.delegate = self
cameraPicker.allowsEditing = true
self.present(cameraPicker, animated: true, completion: nil)
}
//アルバム(カメラ)のキャンセルボタンがタップされた時、画面を終わらす
//デリゲートメソッド
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil) //ここでのpickerは、デリゲートによって、開かれているUIImagePickerControllerが自動的に指定されている。
}
//アルバム(カメラ)で撮影もしくは選択されたデータを、どのように処理をするかのデリケードメソッド
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//もし取り扱うデータ(info[.editedImage] as? UIImage)が存在するならば、処理を行う。
if let pickerImage = info[.editedImage] as? UIImage{
backImageView.image = pickerImage
picker.dismiss(animated: true, completion: nil)
}
}
}
<file_sep>//
// Person.swift
// struct
//
// Created by ヘパリン類似物質 on 2021/05/13.
//
import Foundation
//構造体を作成
struct Person {
var name = String()
var shumi = String()
var movie = String()
}
<file_sep>//
// ViewController.swift
// GamenSenni
//
// Created by ヘパリン類似物質 on 2021/05/12.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var count = 0
var name : String! = "あいうえお"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(name!) //強制的アンラップ,宣言する際の!とは別物
}
@IBAction func plus(_ sender: Any) {
count = count + 1
label.text = String(count) //キャスト
if count == 10{
count = 5
//画面遷移をする。
//Modallyを使用した場合の、遷移方法
// performSegue(withIdentifier: "next", sender: nil)
// let nextVC = segue.destination as! NextViewController
//NavigationControllerを使用した場合の、遷移方法
let nextVC = storyboard?.instantiateViewController(identifier: "next") as! NextViewController
nextVC.count2 = count
navigationController?.pushViewController(nextVC, animated: true)
}
}
@IBAction func button(_ sender: Any) {
let thirdVC = storyboard?.instantiateViewController(identifier: "third") as! ThirdViewController
thirdVC.count3 = count
navigationController?.pushViewController(thirdVC, animated: true)
}
//Modallyを使用して遷移した場合に呼ばれるメソッド
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//nextVCという変数に、NextViewControllerを代入する
let nextVC:NextViewController = segue.destination as! NextViewController
//nextVCの、count2という変数に、countを代入する。
nextVC.count2 = count
}
}
<file_sep>//
// File.swift
// questionApp
//
// Created by ヘパリン類似物質 on 2021/05/14.
//
import Foundation
//imagedMOdelは、写真一つに対するデータ処理を任されている
class ImagesModel {
//画像名を取得して、その画像名が人間かそうでないかをフラグによって判定するための機能
let imageText:String
let answer:Bool
init(imageName:String, correctOrNot:Bool) {
imageText = imageName
answer = correctOrNot
}
}
<file_sep>//
// LoginMovieViewController.swift
// newsApp
//
// Created by ヘパリン類似物質 on 2021/05/15.
//
import UIKit
import AVFoundation //動画など、さまざまなものがつかえるようになる。
class LoginMovieViewController: UIViewController {
var player = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
//動画ファイルの情報を、playerに格納
let path = Bundle.main.path(forResource: "start", ofType: "mov")
player = AVPlayer(url: URL(fileURLWithPath: path!))
//AVPlayer用のレイヤーを作成する。
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
//ビデオをどのように表示するか
playerLayer.videoGravity = .resizeAspectFill
//何回ビデオを再生するか。
playerLayer.repeatCount = 0
//上にログインボタンが来る予定なので、奥に配置する
playerLayer.zPosition = -1
//レイヤーをviewに入れる場合は、insertを使用する
view.layer.insertSublayer(playerLayer, at: 0)
//ビデオを繰り返し再生するための記述
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: .main){(_) in
self.player.seek(to: .zero)
self.player.play()
}
self.player.play() //まず最初に再生しないといけない。
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//ナビゲーションバーを消す
navigationController?.isNavigationBarHidden = true
}
@IBAction func login(_ sender: Any) {
//画面を離れる時に、動画をストップする
player.pause()
}
}
<file_sep>//
// SearchViewController.swift
// GooGleMaps-Practice
//
// Created by ヘパリン類似物質 on 2021/06/02.
//
import UIKit
class SearchViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func button(_ sender: Any) {
let mapVC = storyboard?.instantiateViewController(identifier: "mapVC") as! MapViewController
mapVC.address = textField.text!
navigationController?.pushViewController(mapVC, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// AnswersModel.swift
// OdaiApp
//
// Created by ヘパリン類似物質 on 2021/05/19.
//
import Foundation
struct AnswersModel {
let answers:String
let userName:String
let docID:String
//↓いいね機能を作成する際に追加
let likeCount:Int
//キーをstring型で持つ辞書型を宣言
let likeFlagDic:Dictionary<String, Any>
}
<file_sep>//
// NextViewController.swift
// TwitterLoginPractice
//
// Created by ヘパリン類似物質 on 2021/06/06.
//
import UIKit
import FirebaseAuth
class NextViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.text = Auth.auth().currentUser?.uid
userName.text = Auth.auth().currentUser?.displayName
}
let URL:URL = (Auth.auth().currentUser?.photoURL)!
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var profile: UILabel!
}
<file_sep>//
// ViewController.swift
// OdaiApp
//
// Created by ヘパリン類似物質 on 2021/05/19.
//
import UIKit
import Firebase
import FirebaseFirestore
import EMAlertController
class ViewController: UIViewController,UITextViewDelegate {
//お題データを受信するデータベースの場所を設定
let db1 = Firestore.firestore().collection("Odai").document("6fqTXCag3aCbkQM1RwIZ")
//回答データを送信するデータベースの場所を設定するための変数
let db2 = Firestore.firestore()
var userName = String()
var idString = String() //いいね機能の際に追加
@IBOutlet weak var textview: UITextView!
@IBOutlet weak var odaiLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if UserDefaults.standard.object(forKey: "userName") != nil{
userName = UserDefaults.standard.object(forKey: "userName") as! String
}
textview.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isNavigationBarHidden = true
loadQuestiondata()
if UserDefaults.standard.object(forKey: "documentID") != nil {
idString = UserDefaults.standard.object(forKey: "documentID") as! String
print(idString)
print("aoyama")
}else{
//setDataを使わなければ、データがfireStoreに保存されないが、パスを持ってくることはできる
idString = Firestore.firestore().collection("Answers").document().path
print(idString)
idString = String(idString.dropFirst(8))
UserDefaults.standard.setValue(idString, forKey: "documentID")
}
print(idString)
print("aoyama")
}
func loadQuestiondata(){
//指定したドキュメントから、実際にデータを引っ張ってくる処理
db1.getDocument { snapShot, error in
if error != nil {
print(error.debugDescription)
return
}
let data = snapShot?.data()
self.odaiLabel.text = data!["odaiText"] as! String
}
}
//FireStoreに、回答のデータを送信する
@IBAction func send(_ sender: Any) {
//いいねを含めた際での処理
db2.collection("Answers").document(idString).setData(["answer" : textview.text as Any, "userName": userName as Any, "postDate":Date().timeIntervalSince1970, "like":0, "likeFlagDic":[idString:false]])
//setDataの方は、コメントアウトしています。
// db2.collection("Answers").document().setData(["answer" : textview.text as Any, "userName": userName as Any, "postDate":Date().timeIntervalSince1970 ])
// db2.collection("Answers").addDocument(data: ["answer" : textview.text as Any, "userName": userName as Any, "postDate":Date().timeIntervalSince1970 ]) { error in
//
// if error != nil{
// print(error.debugDescription)
// return
// }
//
// }
//
//アラートを表示させる
alert()
}
//アラート作成
func alert() {
let alert = EMAlertController(icon: UIImage(named: "check"), title: "投稿完了", message: "みんなの回答を見てみよう!")
let doneAction = EMAlertAction(title: "OK", style: .normal)
alert.addAction(doneAction)
present(alert, animated: true, completion: nil)
textview.text = ""
}
@IBAction func checkAnswer(_ sender: Any) {
let checkVC = storyboard?.instantiateViewController(identifier: "checkVC") as! CheckViewController
checkVC.odaiString = odaiLabel.text!
navigationController?.pushViewController(checkVC, animated: true)
}
@IBAction func logout(_ sender: Any) {
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
UserDefaults.standard.removeObject(forKey: "userName")
UserDefaults.standard.removeObject(forKey: "documentID")
} catch let error as NSError {
print("error",error)
}
//前画面に戻る処理
navigationController?.popViewController(animated: true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
textview.resignFirstResponder()
}
}
<file_sep>//
// ViewController.swift
// meigenApp
//
// Created by ヘパリン類似物質 on 2021/05/16.
//
import UIKit
import BubbleTransition //丸が広がるようなアニメーションを作成
import Firebase
class FeedItem{
var meigen:String!
var author:String!
}
class ViewController: UIViewController , XMLParserDelegate, UIViewControllerTransitioningDelegate{
var userName = String()
let db = Firestore.firestore()
let transition = BubbleTransition()
let interactiveTransition = BubbleInteractiveTransition()
var parser = XMLParser()
//XML解析関係
var feeditems = [FeedItem()]
var currentElementName:String!
@IBOutlet weak var meigenLabel: UILabel!
@IBOutlet weak var toFeedButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
toFeedButton.layer.cornerRadius = toFeedButton.frame.width/2 //ボタンを丸にする
self.navigationController?.isNavigationBarHidden = true
//XML解析の記述
let url:String = "http://meigen.doodlenote.net/api?c=1" //httpサイトにアクセスする際は、plistをいじる必要あり。
let urlToSend = URL(string:url)
parser = XMLParser(contentsOf: urlToSend!)!
parser.delegate = self
parser.parse()
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
currentElementName = nil
if elementName == "data" {
feeditems.append(FeedItem())
}else {
currentElementName = elementName
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
if feeditems.count > 0 {
let lastItem = feeditems[feeditems.count - 1]
switch currentElementName {
case "meigen":
lastItem.meigen = string
case "author":
lastItem.author = string
meigenLabel.text = lastItem.meigen + "\n" + lastItem.author
default:
break
}
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentElementName = nil
}
//シェアボタン、機能の作成
@IBAction func share(_ sender: Any) {
var postString = String()
postString = "\(userName)さんを表す名言:\n\(meigenLabel.text!)\n#あなたを表す名変メーカー"
let shareItems = [postString] as [String] //シェアする際の渡すデータは、配列で作成する。
let controller = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
present(controller, animated: true, completion: nil)
}
//firestoreに、データを保存する。
@IBAction func sendData(_ sender: Any) {
if let quote = meigenLabel.text, let userName = Auth.auth().currentUser?.uid{
//保存するデータ内容を記述する。データは、辞書型で記入する。
//Auth.auth.currnetUserで、現在ログインしているユーザーの情報を取得でできる。
//Date().timeIntervalSince1970で、日時を取得できる。
db.collection("feed").addDocument(data: ["userName": Auth.auth().currentUser?.displayName, "quote": meigenLabel.text, "photoURL": Auth.auth().currentUser?.photoURL?.absoluteString, "createAt":Date().timeIntervalSince1970]) { error in
if error != nil{
print(error.debugDescription)
return
}
}
}
}
@IBAction func tofeedVC(_ sender: Any) {
performSegue(withIdentifier: "feedVC", sender: nil)
}
//ログアウト処理
@IBAction func logout(_ sender: Any) {
//ナビゲーションバーを使用した時の、前画面に戻る処理
self.navigationController?.popViewController(animated: true)
do {
try Auth.auth().signOut()
} catch let error as NSError {
print(error.localizedDescription)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let controller = segue.destination as? FeedViewController {
controller.transitioningDelegate = self
controller.modalPresentationStyle = .custom
controller.modalPresentationCapturesStatusBarAppearance = true
controller.interactiveTransition = interactiveTransition
interactiveTransition.attach(to: controller)
}
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .present
transition.startingPoint = toFeedButton.center
transition.bubbleColor = toFeedButton.backgroundColor!
return transition
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .dismiss
transition.startingPoint = toFeedButton.center
transition.bubbleColor = toFeedButton.backgroundColor!
return transition
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactiveTransition
}
}
<file_sep>//
// ViewController.swift
// Tableview-practice
//
// Created by ヘパリン類似物質 on 2021/05/12.
//
import UIKit
//TableViewを用いるためには、UITableViewDelegate, UITableViewDataSource、二つのデリゲートが必要
//キーボードも用いるため、UITextFieldDelegateも記載。
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var tableView: UITableView!
//Stringが入る配列を準備
var textArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
textField.delegate = self
// navigationController?.isNavigationBarHidden = true
}
//viewWillappearで、画面が読み込まれるたびに行う処理を記述
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//ナビゲーションバーを隠す記述
navigationController?.isNavigationBarHidden = true
//セルの選択状態を、解除することができる記述
if let Row = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: Row, animated: true)
}
//Rowという定数に、代入することができたら、trueを返すので、それを条件式として使用しているっぽい。
}
//UITableViewDataSourcewp使用するためには、以下2つのメソッドが必要
//TableViewに表示するセルの数を設定する
// 2 まず、セクションの中のセルの数を確認
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return textArray.count //配列.countで、配列の要素の数を返す
}
//セクションの数を指定する。
// 1 まず、セクションの数を確認
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//どんな内容を返すかを、設定する。numberOfRowsInSectionの数分実行される。
//3 どんなセルを返すのかを指定。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) //
// cell.selectionStyle = .none
cell.textLabel?.text = textArray[indexPath.row]
cell.imageView!.image = UIImage(named: "checkImage")
return cell
}
//cellがタップされたときに行う動作
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//タップした時に、その配列の番号を取り出して、値をわたす。
let nextVC = storyboard?.instantiateViewController(identifier: "next") as! NextViewController
nextVC.toDoString = textArray[indexPath.row] //indexpath.rowで、何番目の要素がタップされたかを取り出すことができる。
navigationController?.pushViewController(nextVC, animated: true)
}
//一つのセルあたりの高さを設定する
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return view.frame.size.height / 6 //viewの高さ全体の1/6を、設定している。
}
//textFieldのreturnが押されたときに、起動
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textArray.append(textField.text!) //textfieldに入ったテキストを配列に挿入
textField.resignFirstResponder() //textfieldを閉じる
textField.text = "" //中身を空にする。
tableView.reloadData()
return true
}
}
<file_sep>//
// NextViewController.swift
// protocol-practice
//
// Created by ヘパリン類似物質 on 2021/05/13.
//
import UIKit
//①、protocolを作成
protocol CatchProtocol {
//Int型のデータをcountという変数に入れるメソッドを定義
func catchData(count:Int)
}
class NextViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var count = Int()
//プロトコルを変数化して、使えるようにする。
var delegate:CatchProtocol?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func plusAction(_ sender: Any) {
count = count + 1
label.text = String(count)
}
@IBAction func back(_ sender: Any) {
//デリゲートメソッドを発動させたクラス(今回は、VC)で行われる処理(nextVCでは実際の処理は行われない。)
delegate?.catchData(count: count) //delegateに、値を入れる処理を書いていないので、もし入っていなかったら処理をしないように、?をつける。
dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// ImagesList.swift
// questionApp
//
// Created by ヘパリン類似物質 on 2021/05/14.
//
import Foundation
class ImagesList {
//ImagesModelで定義されたデータが入る配列を定義
var list = [ImagesModel]()
init(){
list.append(ImagesModel(imageName:"1", correctOrNot:false))
list.append(ImagesModel(imageName:"2", correctOrNot:false))
list.append(ImagesModel(imageName:"3", correctOrNot:false))
list.append(ImagesModel(imageName:"4", correctOrNot:true))
list.append(ImagesModel(imageName:"5", correctOrNot:false))
list.append(ImagesModel(imageName:"6", correctOrNot:true))
list.append(ImagesModel(imageName:"7", correctOrNot:true))
list.append(ImagesModel(imageName:"8", correctOrNot:false))
list.append(ImagesModel(imageName:"9", correctOrNot:true))
}
}
<file_sep>//
// HashTagViewController.swift
// instagram
//
// Created by ヘパリン類似物質 on 2021/05/23.
//
import UIKit
class HashTagViewController: UIViewController, UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, LoadOKDelegate {
//ハッシュタグを受け取る
var hashTag = String()
//loadモデルをインスタンス化
var loadDBModel = LoadDBModel()
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var topImageView: UIImageView!
@IBOutlet weak var collectonView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectonView.delegate = self
collectonView.dataSource = self
loadDBModel.loadOKDelegate = self
self.navigationItem.title = "#\(hashTag)"
//ハッシュタグを渡し、表示するデータの元となる配列(dataSets)を作成
loadDBModel.loadHashTag(hashTag: hashTag)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
topImageView.layer.cornerRadius = 40.0
}
func loadOK(check: Int) {
if check == 1{
collectonView.reloadData()
}
}
//コレクションビューに関する記述
func numberOfSections(in collectionView: UICollectionView) -> Int {
1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
countLabel.text = String(loadDBModel.dataSets.count)
return loadDBModel.dataSets.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
let contentImageView = cell.contentView.viewWithTag(1) as! UIImageView
contentImageView.sd_setImage(with: URL(string: loadDBModel.dataSets[indexPath.row].contentImage), completed: nil)
//topviewには、最新の投稿を表示する。
topImageView.sd_setImage(with: URL(string: loadDBModel.dataSets[0].contentImage), completed: nil)
return cell
}
//cellをタップした際の動き
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let detailVC = self.storyboard?.instantiateViewController(identifier: "detailVC") as! DetailViewController
detailVC.userName = loadDBModel.dataSets[indexPath.row].userName
detailVC.comment = loadDBModel.dataSets[indexPath.row].comment
detailVC.contentImageString = loadDBModel.dataSets[indexPath.row].contentImage
detailVC.profileImage = loadDBModel.dataSets[indexPath.row].profileImage
self.navigationController?.pushViewController(detailVC, animated: true)
}
//レイアウト関係の記述
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.bounds.width/3.0
let height = width
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
<file_sep>//
// ViewController.swift
// protocol-practice
//
// Created by ヘパリン類似物質 on 2021/05/13.
//
import UIKit
class ViewController: UIViewController, CatchProtocol {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func goButton(_ sender: Any) {
performSegue(withIdentifier: "next", sender: nil)
}
func catchData(count: Int) {
label.text = String(count)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "next" {
let nextVC = segue.destination as! NextViewController
nextVC.delegate = self
}
}
}
<file_sep>//
// Geocodemodel.swift
// GooGleMaps-Practice
//
// Created by ヘパリン類似物質 on 2021/06/02.
//
import Foundation
import MapKit
import GoogleMaps
protocol GetCoordinate {
func getCoordinateData(latitude:Double,longitude:Double)
}
class GeocodeModel {
var latitude = Double()
var longitude = Double()
var getCoordinate:GetCoordinate?
func geocode(address: String) {
CLGeocoder().geocodeAddressString(address) { placemarks, error in
//緯度を変数に保存
if let lat = placemarks?.first?.location?.coordinate.latitude {
self.latitude = lat
print("緯度 : \(lat)")
}
//経度を変数に保存
if let lng = placemarks?.first?.location?.coordinate.longitude {
self.longitude = lng
print("経度 : \(lng)")
print("")
}
self.getCoordinate?.getCoordinateData(latitude: self.latitude, longitude: self.longitude)
}
}
}
<file_sep>//
// ViewController.swift
// TwitterLoginPractice
//
// Created by ヘパリン類似物質 on 2021/06/06.
//
import UIKit
import Firebase
import FirebaseFirestore
import FirebaseAuth
import Swifter
class ViewController: UIViewController, AuthUIDelegate {
var provider = OAuthProvider(providerID: "twitter.com")
var auth = AuthUIDelegate.self
override func viewDidLoad() {
super.viewDidLoad()
provider.customParameters = ["lang": "ja"]
}
@IBAction func login(_ sender: Any) {
provider.getCredentialWith(nil) { credential, error in
if error != nil {
print(error.debugDescription)
return
}
if credential != nil {
Auth.auth().signIn(with: credential!) { authResult, error in
if error != nil {
print(error.debugDescription)
return
}
}
}
}
performSegue(withIdentifier: "next", sender: nil)
}
}
<file_sep>//
// ViewController.swift
// Qiita-HashTag
//
// Created by ヘパリン類似物質 on 2021/06/04.
//
import UIKit
import FirebaseFirestore
class ViewController: UIViewController {
//文字列を入力するtextFieldに紐づいています。
@IBOutlet weak var textField: UITextField!
//投稿するボタンに紐づいています。
@IBAction func send(_ sender: Any) {
//入力された文字列を引数に、下記に記述したメソッドを呼んでいます。
Firestore.firestore().collection("collection").document().setData(["text" : textField.text!])
//追加部分 ==================================================================
let hashTagText = textField.text as NSString?
do{
let regex = try NSRegularExpression(pattern: "#\\S+", options: [])
//見つけたハッシュタグを、for文で回す。
for match in regex.matches(in: hashTagText! as String, options: [], range: NSRange(location: 0, length: hashTagText!.length)) {
//見つかったハッシュタグを引数に入れデータベースに保存
Firestore.firestore().collection(hashTagText!.substring(with: match.range)).document().setData(["text" : self.textField.text!])
}
}catch{
}
//追加部分 ==================================================================
//データを保存したら、画面遷移を行います。
let tableVC = storyboard?.instantiateViewController(identifier: "tableVC") as! TableViewController
navigationController?.pushViewController(tableVC, animated: true)
}
}
| d858d3a8112f4ac096b993c2fe6c98aa377c192d | [
"Swift"
]
| 47 | Swift | kaikai8812/swift-practice | 40328815d0fa59bd02a625833e0b02120699c513 | 96c258d9f6ab70029aa3a8abde649724a2f71efd |
refs/heads/master | <file_sep>function setup() {
createCanvas(400, 400);
colorMode(HSB);
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++) {
stroke(i, j, 100);
point(i, j);
}
}
}
function draw() {
background(150, 204, 100);
frameRate(1);
//stationary star
push();
translate(width*0.5, height*0.5);
star(0, 0, 40, 100, 5);
pop();
//rotating star
push();
translate(width*0.5, height*0.5);
fill(200, 102, 100)
rotate(frameCount / 1);
star(0, 0, 40, 100, 5);
pop();
}
function star(x, y, radius1, radius2, npoints) {
var angle = TWO_PI / npoints;
var halfAngle = angle/2.0;
beginShape();
for (var a = 0; a < TWO_PI; a += angle) {
var sx = x + cos(a) * radius2;
var sy = y + sin(a) * radius2;
vertex(sx, sy);
sx = x + cos(a+halfAngle) * radius1;
sy = y + sin(a+halfAngle) * radius1;
vertex(sx, sy);
}
endShape(CLOSE);
}
| b63dc5fb26dff9eac1cf75294fe8845009cfae36 | [
"JavaScript"
]
| 1 | JavaScript | indefinit/CreativeCoding-TuNguyen | d17db5d034cc8b14187ac33116d47e9f48896845 | 20e316b2f9bc3f2b4393bee56214166e752a010b |
refs/heads/master | <repo_name>itu-sass-s2014/networkx-coloring-benchmark<file_sep>/benchmark.py
import networkx as nx
import os
import sys
import re
import glob
import time
import argparse
parser = argparse.ArgumentParser(description='Run benchmark on networkx graph coloring algorithms')
parser.add_argument('--folder', default=".", required=True, help="choose which folder to point to with .col files")
parser.add_argument('--output', default=".", required=False, help="choose which folder to output .csv file to")
parser.add_argument('--iterations', default="5", required=False, help="choose number of iterations for each strategy")
args = parser.parse_args()
# nanoseconds: 1000000000
# microseconds: 1000000
# milliseconds: 1000
current_milli_time = lambda: int(round(time.time() * 1000))
if not os.path.exists(args.output):
os.makedirs(args.output)
def getGraphFromFile(filename):
G = nx.Graph()
with open(filename, 'r') as lines:
for line in lines:
result = re.search("^e.([0-9]+).([0-9]+)", line)
if result:
v1 = int(result.groups()[0])
v2 = int(result.groups()[1])
G.add_edge(v1, v2)
return G
information = dict()
try:
with open(args.folder + '/information.csv', 'r') as lines:
for line in lines:
parts = line.replace('\n', '').split(',')
information[parts[0]] = parts
except IOError as e:
print "running without supplementary information.csv file"
with open(args.output + '/output.csv', 'w') as output:
for filename in glob.glob(args.folder + '/*.col'):
key = filename.split('/').pop()
print key
G = getGraphFromFile(filename)
strategies = ['lf', 'rs', 'sf', 'sl', 'gis', 'cs-bfs', 'cs-dfs', 'slf']
for strategy in strategies:
times = []
times_ic = []
print key, strategy
result_optimal = sys.maxint
result_optimal_ic = sys.maxint
for i in range(0, int(args.iterations)):
start_time = current_milli_time()
result_optimal = min(result_optimal, len(nx.coloring(G, strategy=strategy, interchange=False, returntype='sets')))
times.append(current_milli_time() - start_time)
print key, strategy, "interchange"
for i in range(0, int(args.iterations)):
start_time = current_milli_time()
result_optimal_ic = min(result_optimal_ic, len(nx.coloring(G, strategy=strategy, interchange=True, returntype='sets')))
times_ic.append(current_milli_time() - start_time)
average_time = sum(times) / len(times)
average_time_ic = sum(times_ic) / len(times_ic)
# result_optimal = len(result)
# result_optimal_ic = len(result_ic)
result_nodes = G.number_of_nodes()
result_edges = G.number_of_edges()
if key in information:
info = information[key]
if info[3] == '?':
info[3] = -1
instance_optimal = int(info[3])
instance_nodes = info[1]
instance_edges = info[2]
diff_percent = 100 * (result_optimal - instance_optimal) / instance_optimal
diff_number = result_optimal - instance_optimal
diff_percent_ic = 100 * (result_optimal_ic - instance_optimal) / instance_optimal
diff_number_ic = result_optimal_ic - instance_optimal
else:
instance_optimal = -1
instance_nodes = -1
instance_edges = -1
diff_percent = -1
diff_number = -1
diff_percent_ic = -1
diff_number_ic = -1
output.write(str.format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16}\n", key, strategy, instance_nodes, result_nodes, int(instance_nodes)==result_nodes, instance_edges, result_edges, int(instance_edges)==result_edges, instance_optimal, result_optimal, diff_number, diff_percent, average_time, result_optimal_ic, diff_number_ic, diff_percent_ic, average_time_ic))
# print key, strategy, info[1], '==', G.number_of_nodes(), ',', info[2], '==', G.number_of_edges(), ',', info[3], '==', len(result), diffNumber, diffPercent
<file_sep>/properties-benchmark.py
import networkx as nx
import sys
import re
import os
import glob
import time
import argparse
parser = argparse.ArgumentParser(description='Run benchmark on networkx graph coloring algorithms')
parser.add_argument('--output', default="./properties", required=False, help="choose which folder to output .csv file to")
args = parser.parse_args()
strategies = ['lf', 'rs', 'sl', 'gis', 'cs-bfs', 'cs-dfs', 'slf']
# nanoseconds: 1000000000
# microseconds: 1000000
# milliseconds: 1000
current_milli_time = lambda: int(round(time.time() * 1000))
def benchmark(output, graph, graphname, strategy, interchange):
times = []
opt = sys.maxint
iteration = 5
if strategy == "rs":
iteration = graph.number_of_nodes()
for i in range(0, iteration):
start_time = current_milli_time()
opt = min(opt, len(nx.coloring(graph, strategy=strategy, interchange=interchange, returntype='sets')))
times.append(current_milli_time() - start_time)
avg = sum(times) / len(times)
print graphname, strategy, interchange
output.write(str.format("{0},{1},{2},{3},{4},{5},{6}\n", graphname, graph.number_of_nodes(), graph.number_of_edges(), strategy, interchange, opt, avg))
def helper(output, graph, graphname):
for strategy in strategies:
try:
benchmark(output, graph, graphname, strategy, False)
benchmark(output, graph, graphname, strategy, True)
except nx.exception.NetworkXPointlessConcept:
print ""
if not os.path.exists(args.output):
os.makedirs(args.output)
with open(args.output + '/output.csv', 'w') as output:
helper(output, nx.balanced_tree(2, 5), "balanced_tree") # branching factor, height
helper(output, nx.barbell_graph(50, 50), "barbell_graph")
helper(output, nx.complete_graph(50), "complete_graph")
helper(output, nx.complete_bipartite_graph(50, 50), "complete_bipartite_graph")
helper(output, nx.circular_ladder_graph(50), "circular_ladder_graph")
helper(output, nx.cycle_graph(50), "cycle_graph")
helper(output, nx.dorogovtsev_goltsev_mendes_graph(5), "dorogovtsev_goltsev_mendes_graph")
helper(output, nx.empty_graph(50), "empty_graph")
helper(output, nx.grid_2d_graph(5, 20), "grid_2d_graph")
helper(output, nx.grid_graph([2, 3]), "grid_graph")
helper(output, nx.hypercube_graph(3), "hypercube_graph")
helper(output, nx.ladder_graph(50), "ladder_graph")
helper(output, nx.lollipop_graph(5, 20), "lollipop_graph")
helper(output, nx.path_graph(50), "path_graph")
helper(output, nx.star_graph(50), "star_graph")
helper(output, nx.trivial_graph(), "trivial_graph")
helper(output, nx.wheel_graph(50), "wheel_graph")
helper(output, nx.random_regular_graph(1, 50, 678995), "random_regular_graph_1")
helper(output, nx.random_regular_graph(3, 50, 683559), "random_regular_graph_3")
helper(output, nx.random_regular_graph(5, 50, 515871), "random_regular_graph_5")
helper(output, nx.random_regular_graph(8, 50, 243579), "random_regular_graph_8")
helper(output, nx.random_regular_graph(13, 50, 568324), "random_regular_graph_13")
helper(output, nx.diamond_graph(), "diamond_graph")<file_sep>/README.md
networkx-coloring-benchmark
===========================
<file_sep>/better.py
filename = "./trick/output.csv"
data = dict()
with open(filename, 'r') as lines:
for line in lines:
values = line.split(",")
graph = values[0]
strategy = values[1]
trick = values[8]
optimal_without_ic = values[9]
optimal_with_ic = values[13]
print trick, optimal_without_ic, optimal_with_ic
if strategy == "slf":
optimal = int(optimal_without_ic)
else:
optimal = min(int(optimal_without_ic), int(optimal_with_ic))
if not graph in data:
data[graph] = [[], [], [], [], []]
optimal = int(optimal)
trick = int(trick)
if strategy != "sf":
data[graph][4].append(optimal)
data[graph][3].append(trick)
if trick == -1:
data[graph][2].append(strategy)
elif optimal > trick:
data[graph][1].append(strategy)
else:
data[graph][0].append(strategy)
with open('better.csv', 'w') as output:
for key in data.keys():
output.write(str.format("{0}\t{4}\t{1}\t{5}\t{2}\t{3}\n", key, ', '.join(data[key][0]), ', '.join(data[key][1]), ', '.join(data[key][2]), min(data[key][3]), min(data[key][4]))) | d8130f4f89ce6776a710e97f45516a9ea1588902 | [
"Markdown",
"Python"
]
| 4 | Python | itu-sass-s2014/networkx-coloring-benchmark | df03977ac40f9d4d43ab182b2aa92c72e04cf103 | b60e7c9124e9f5730da8e4571e0c52269f51d6ba |
refs/heads/master | <file_sep># ltse
ltse assignment
Input:
Please provide 3 program args to main class: MyExchange
java MyExchange "/Users/harishpallila/Downloads/trades.csv" "/Users/harishpallila/Downloads/symbols.txt" "/Users/harishpallila/Downloads"
Output:
4 out files will be generated
a. accepted.txt: accepted trades
b. rejected.txt: accepted trades
c. accepted_orders_json.txt: accepted trades in json format for downstream
d. rejected_orders_json.txt: rejected trades in json format for downstream
External jars required:
<classpathentry kind="lib" path="/Users/harishpallila/eclipse-workspace/jars/jackson-annotations-2.9.8.jar"/>
<classpathentry kind="lib" path="/Users/harishpallila/eclipse-workspace/jars/jackson-core-2.9.8.jar"/>
<classpathentry kind="lib" path="/Users/harishpallila/eclipse-workspace/jars/jackson-databind-2.9.8.jar"/>
<file_sep>package com.ltse;
import java.sql.Timestamp;
public class TradeValidations {
public static final ITradeValidation<Timestamp> timestampValidation = (t) -> {
return ValidatorUtil.getTimestamp(t.getTimestamp());
};
public static final ITradeValidation<String> brokerValidation = (t) -> {
return ValidatorUtil.getString(t.getBroker());
};
public static final ITradeValidation<Long> sequenceIdValidation = (t) -> {
return ValidatorUtil.getLong(t.getSequenceId());
};
public static final ITradeValidation<String> typeValidation = (t) -> {
return ValidatorUtil.getString(t.getType());
};
public static final ITradeValidation<String> symbolValidation = (t) -> {
return ValidatorUtil.getString(t.getSymbol());
};
public static final ITradeValidation<Long> quantityValidation = (t) -> {
return ValidatorUtil.getLong(t.getQuantity());
};
public static final ITradeValidation<Double> priceValidation = (t) -> {
return ValidatorUtil.getDouble(t.getPrice());
};
public static final ITradeValidation<String> sideValidation = (t) -> {
return ValidatorUtil.getString(t.getSide());
};
}
<file_sep>package com.ltse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Utils {
public static void writeToFile(final List<Trade> result, final String filePath, final boolean asJSON) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final SimpleDateFormat df = new SimpleDateFormat(com.ltse.ValidatorUtil.datePattern);
mapper.setDateFormat(df);
final BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
try {
for (final Trade each : result)
writer.write(asJSON ? mapper.writeValueAsString(each) + "\n" : each.resultString() + "\n");
} finally {
writer.close();
}
}
public static void appendToFile(final List<String> result, final String filePath) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final SimpleDateFormat df = new SimpleDateFormat(com.ltse.ValidatorUtil.datePattern);
mapper.setDateFormat(df);
final BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true));
try {
for (final String each : result)
writer.write(each + "\n");
} finally {
writer.close();
}
}
}
<file_sep>package com.ltse;
public class RawTrade {
private final String timestamp;
private final String broker;
private final String sequenceId;
private final String type;
private final String symbol;
private final String quantity;
private final String price;
private final String side;
public RawTrade(final Builder builder) {
this.timestamp = builder.timestamp;
this.broker = builder.broker;
this.sequenceId = builder.sequenceId;
this.type = builder.type;
this.symbol = builder.symbol;
this.quantity = builder.quantity;
this.price = builder.price;
this.side = builder.side;
}
public String getBroker() {
return broker;
}
public String getSequenceId() {
return sequenceId;
}
public String getType() {
return type;
}
public String getSymbol() {
return symbol;
}
public String getQuantity() {
return quantity;
}
public String getPrice() {
return price;
}
public String getSide() {
return side;
}
public String getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return "RawTrade [timestamp=" + timestamp + ", broker=" + broker + ", sequenceId=" + sequenceId + ", type="
+ type + ", symbol=" + symbol + ", quantity=" + quantity + ", price=" + price + ", side=" + side + "]";
}
public static class Builder {
private String timestamp;
private String broker;
private String sequenceId;
private String type;
private String symbol;
private String quantity;
private String price;
private String side;
public Builder timestamp(final String ts) {
this.timestamp = ts;
return this;
}
public Builder broker(final String broker) {
this.broker = broker;
return this;
}
public Builder sequenceId(final String sequenceId) {
this.sequenceId = sequenceId;
return this;
}
public Builder type(final String type) {
this.type = type;
return this;
}
public Builder symbol(final String symbol) {
this.symbol = symbol;
return this;
}
public Builder quantity(final String quantity) {
this.quantity = quantity;
return this;
}
public Builder price(final String price) {
this.price = price;
return this;
}
public Builder side(final String side) {
this.side = side;
return this;
}
public RawTrade build() {
return new RawTrade(this);
}
}
}
<file_sep>package com.ltse;
import static com.ltse.Utils.writeToFile;
import static com.ltse.Utils.appendToFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MyExchange {
private final List<Trade> acceptedTrades = new ArrayList<Trade>();
private final List<Trade> rejectedTrades = new ArrayList<Trade>();
private final List<String> badTrades = new ArrayList<String>();
private TradeParser tradeParser;
private TradeValidator tradeValidator;
private TradeRuleEngine ruleEngine;
private String tradesFilePath;
private String validTickersFilePath;
public MyExchange(final TradeParser tradeParser, final TradeValidator tradeValidator, final TradeRuleEngine ruleEngine, final String tradesFilePath, final String validTickersFilePath) {
this.tradeParser = tradeParser;
this.tradeValidator = tradeValidator;
this.ruleEngine = ruleEngine;
this.tradesFilePath = tradesFilePath;
this.validTickersFilePath = validTickersFilePath;
}
public List<Trade> getAcceptedTrades() {
return acceptedTrades;
}
public List<Trade> getRejectedTrades() {
return rejectedTrades;
}
public List<String> getBadTrades() {
return badTrades;
}
private void initRulesEngine() throws FileNotFoundException {
ruleEngine.init(this.validTickersFilePath);
}
public void runExchange() throws FileNotFoundException {
// init
initRulesEngine();
// parse
tradeParser.parseTrades(this.tradesFilePath, true);
badTrades.addAll(tradeParser.getBadRawTrades());
final List<RawTrade> goodRawTrades = tradeParser.getGoodrawTrades();
for (final RawTrade eachRawTrade : goodRawTrades) {
// validate
final Trade processedTrade = tradeValidator.validateAndGenerateTrade(eachRawTrade);
if (!processedTrade.isAcceptedTrade()) {
rejectedTrades.add(processedTrade);
continue;
}
// apply rules
ruleEngine.processTrade(processedTrade);
if (processedTrade.isAcceptedTrade())
acceptedTrades.add(processedTrade);
else
rejectedTrades.add(processedTrade);
}
}
public static void main(String[] args) throws IOException {
if (args.length != 3) {
System.err.println("Please provide 3 args; 1st: tradesFilePath, 2nd: tickerFilePath, 3rd:outDir");
System.exit(-1);
}
final String tradesFilePath = args[0];
final String tickersFilePath = args[1];
final String outDir = args[2];
final TradeParser tradeParser = new TradeParser();
final TradeValidator tradeValidator = new TradeValidator();
final TradeRuleEngine ruleEngine = new TradeRuleEngine();
final MyExchange exchange = new MyExchange(tradeParser, tradeValidator, ruleEngine, tradesFilePath, tickersFilePath);
exchange.runExchange();
writeToFile(exchange.getAcceptedTrades(), outDir + "/accepted.txt", false);
writeToFile(exchange.getRejectedTrades(), outDir + "/rejected.txt", false);
appendToFile(exchange.getBadTrades(), outDir + "/rejected.txt");
writeToFile(exchange.getAcceptedTrades(), outDir + "/accepted_orders_json.txt", true);
writeToFile(exchange.getRejectedTrades(), outDir + "/rejected_orders_json.txt", true);
}
}
<file_sep>package com.ltse;
import static org.junit.Assert.assertEquals;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
public class TradeParserTest {
@Test
public void testWithoutHeader() throws IOException {
File temp = writeFile(false);
TradeParser tp = new TradeParser();
tp.parseTrades(temp.getPath(), false);
assertEquals("good trade count failed", 2, tp.getGoodrawTrades().size());
assertEquals("bad trade count failed", 1, tp.getBadRawTrades().size());
}
@Test
public void testWithHeader() throws IOException {
File temp = writeFile(true);
TradeParser tp = new TradeParser();
tp.parseTrades(temp.getPath(), true);
assertEquals("good trade count failed", 2, tp.getGoodrawTrades().size());
assertEquals("bad trade count failed", 1, tp.getBadRawTrades().size());
}
private File writeFile(boolean addHeader) throws IOException {
File temp = File.createTempFile("trades", ".tmp");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
if (addHeader)
bw.write("timestamp,broker,sequenceid,type,symbol,quantity,price,side\n");
bw.write("10/5/2017 10:00:00,Fidelity,1,2,BARK,100,1.195,Buy\n");
bw.write("10/5/2017 10:00:01,<NAME>,1,2,CARD,200,6.855,Sell\n");
bw.write("10/5/2017 10:00:03,Wells,1,2,CARD,6.855,Sell\n");
bw.close();
return temp;
}
}
<file_sep>package com.ltse;
public interface IRule {
public boolean apply(Trade tb);
}
<file_sep>package com.ltse;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TradeValidatorTest {
@Test
public void testValidateAndGenerateTrade() {
TradeValidator tv = new TradeValidator();
RawTrade.Builder builder = new RawTrade.Builder();
builder.symbol("AAPL").broker("Fidelity").sequenceId("1").timestamp("10/5/2019 11:10:23");
RawTrade rt = new RawTrade(builder);
Trade result = tv.validateAndGenerateTrade(rt);
assertEquals("Invalid trade", false, result.isAcceptedTrade());
assertEquals("Incorrect reason code length", 4, result.getReasonCode().split(";").length);
assertEquals("Incorrect reason code", "failed type validation;failed quantity validation;failed price validation;failed side validation", result.getReasonCode());
}
@Test
public void testValidateAndGenerateTradeGoodTrade() {
TradeValidator tv = new TradeValidator();
RawTrade.Builder builder = new RawTrade.Builder();
builder.symbol("AAPL").broker("Fidelity").sequenceId("1").timestamp("10/5/2019 11:10:23").type("1").quantity("100").price("100.10").side("Buy");
RawTrade rt = new RawTrade(builder);
Trade result = tv.validateAndGenerateTrade(rt);
assertEquals("Valid trade", true, result.isAcceptedTrade());
assertEquals("correct reason code", "", result.getReasonCode());
}
}
| 66e1d06bbb22c88bbc812767c47bb06d810839aa | [
"Markdown",
"Java"
]
| 8 | Markdown | harishpallila/ltse | ef4d8ab2044450c05a88bf4542887827320dbde4 | 7f65d4661b90e6c0f0c26ffee2377d62fb28f200 |
refs/heads/master | <repo_name>JeffCohen/classroom<file_sep>/data.rb
movieData = [
{
"id" => 15,
"title" => "Air",
"rating" => "PG-13",
"runtime" => "95 min",
"genre" => "Sci-Fi, Thriller",
"released" => "08/14/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMjE2NjcwMjA2OF5BMl5BanBnXkFtZTgwODA5NTkxNjE@._V1_SX300.jpg",
"plot" => "In the near future, breathable air is nonexistent and two engineers tasked with guarding the last hope for mankind struggle to preserve their own lives while administering to their vital task at hand."
},
{
"id" => 18,
"title" => "Aloha",
"rating" => "PG-13",
"runtime" => "105 min",
"genre" => "Comedy, Drama, Romance",
"released" => "05/29/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMTg4Mjc0NTE1NV5BMl5BanBnXkFtZTgwNzcwNTQ3NTE@._V1_SX300.jpg",
"plot" => "A celebrated military contractor returns to the site of his greatest career triumphs and reconnects with a long-ago love while unexpectedly falling for the hard-charging Air Force watch-dog assigned to him."
},
{
"id" => 21,
"title" => "American Sniper",
"rating" => "R",
"runtime" => "133 min",
"genre" => "Action, Biography, Drama",
"released" => "01/16/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMTkxNzI3ODI4Nl5BMl5BanBnXkFtZTgwMjkwMjY4MjE@._V1_SX300.jpg",
"plot" => "Navy S.E.A.L. sniper <NAME>'s pinpoint accuracy saves countless lives on the battlefield and turns him into a legend. Back home to his wife and kids after four tours of duty, however, Chris finds that it is the war he can't leave behind."
},
{
"id" => 24,
"title" => "Ant-Man",
"rating" => "PG-13",
"runtime" => "117 min",
"genre" => "Action, Adventure, Sci-Fi",
"released" => "07/17/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMjM2NTQ5Mzc2M15BMl5BanBnXkFtZTgwNTcxMDI2NTE@._V1_SX300.jpg",
"plot" => "Armed with a super-suit with the astonishing ability to shrink in scale but increase in strength, cat burglar <NAME> must embrace his inner hero and help his mentor, Dr. <NAME>, plan and pull off a heist that will save the world."
},
{
"id" => 37,
"title" => "Batman vs. Robin",
"rating" => "PG-13",
"runtime" => "80 min",
"genre" => "Animation, Action, Adventure",
"released" => "04/14/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMjI0ODY2MDE5Nl5BMl5BanBnXkFtZTgwMTk0NTcyNTE@._V1_SX300.jpg",
"plot" => "While <NAME> struggles to cope with Batman's no-killing rule, he soon starts to believe that his destiny lies within a secret society known as, The Court of Owls."
},
{
"id" => 73,
"title" => "Daddy's Home",
"rating" => "PG-13",
"runtime" => "96 min",
"genre" => "Comedy",
"released" => "12/25/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMTQ0OTE1MTk4N15BMl5BanBnXkFtZTgwMDM5OTk5NjE@._V1_SX300.jpg",
"plot" => "A mild-mannered radio executive strives to become the best stepdad to his wife's two children, but complications ensue when their freewheeling and freeloading real father arrives, forcing him to compete for the affection of the kids."
},
{
"id" => 84,
"title" => "Dope",
"rating" => "R",
"runtime" => "103 min",
"genre" => "Comedy, Crime, Drama",
"released" => "06/19/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMjA3MjYyNTk0Nl5BMl5BanBnXkFtZTgwODc1NzQ1NTE@._V1_SX300.jpg",
"plot" => "Life changes for Malcolm, a geek who's surviving life in a tough neighborhood, after a chance invitation to an underground party leads him and his friends into a Los Angeles adventure."
},
{
"id" => 90,
"title" => "Entourage",
"rating" => "R",
"runtime" => "104 min",
"genre" => "Comedy",
"released" => "06/03/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMTQ3NjYxMDE1OV5BMl5BanBnXkFtZTgwMjgzOTE4MzE@._V1_SX300.jpg",
"plot" => "Movie star <NAME>, together with his boys Eric, Turtle, and Johnny, are back - and back in business with super agent-turned-studio head Ari Gold on a risky project that will serve as Vince's directorial debut."
},
{
"id" => 129,
"title" => "Inside Out",
"rating" => "PG",
"runtime" => "95 min",
"genre" => "Animation, Adventure, Comedy",
"released" => "06/19/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BOTgxMDQwMDk0OF5BMl5BanBnXkFtZTgwNjU5OTg2NDE@._V1_SX300.jpg",
"plot" => "After young Riley is uprooted from her Midwest life and moved to San Francisco, her emotions - Joy, Fear, Anger, Disgust and Sadness - conflict on how best to navigate a new city, house, and school."
},
{
"id" => 130,
"title" => "Insurgent",
"rating" => "PG-13",
"runtime" => "119 min",
"genre" => "Adventure, Sci-Fi, Thriller",
"released" => "03/20/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMTgxOTYxMTg3OF5BMl5BanBnXkFtZTgwMDgyMzA2NDE@._V1_SX300.jpg",
"plot" => "Beatrice Prior must confront her inner demons and continue her fight against a powerful alliance which threatens to tear her society apart with the help from others on her side."
},
{
"id" => 168,
"title" => "Minions",
"rating" => "PG",
"runtime" => "91 min",
"genre" => "Animation, Comedy, Family",
"released" => "07/10/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BMTg2MTMyMzU0M15BMl5BanBnXkFtZTgwOTU3ODk4NTE@._V1_SX300.jpg",
"plot" => "Minions Stuart, Kevin and Bob are recruited by Scarlet Overkill, a super-villain who, alongside her inventor husband Herb, hatches a plot to take over the world."
},
{
"id" => 222,
"title" => "Star Wars: The Force Awakens",
"rating" => "PG-13",
"runtime" => "135 min",
"genre" => "Action, Adventure, Fantasy",
"released" => "12/18/15",
"cast" => "<NAME>, <NAME>, <NAME>, <NAME>",
"poster" => "https://ia.media-imdb.com/images/M/MV5BOTAzODEzNDA<KEY>",
"plot" => "Three decades after the defeat of the Galactic Empire, a new threat arises. The First Order attempts to rule the galaxy and only a ragtag group of heroes can stop them, along with the help of the Resistance."
}
]
<file_sep>/README.md
# Welcome to Your New App!
Get started in 3 easy steps:
1. In your **Terminal pane**, type: `bundle`
1. In your **Terminal pane**, type: `./catchup`
2. Click the green **Run** button (or use the menu `Run > Run With > Ruby on Rails (stable + Ruby 2.2)`)
If you're in class and fall behind, you can run this command to catch up:
`./catchup`
<file_sep>/db/seeds.rb
movies = [
{
"imdb_key" => 'tt0082971',
"price" => 1295,
"year" => 1981,
"mpaa" => 'PG',
"title" => 'Raiders of the Lost Ark',
"poster" => 'raiders.jpg',
"plot" => 'Archaeologist and adventurer <NAME> is hired by the US government to find the Ark of the Covenant before the Nazis.'
},
{
"imdb_key" => 'tt2488496',
"price" => 4295,
"year" => 2015,
"mpaa" => 'PG',
"title" => 'Star Wars: The Force Awakens',
"poster" => 'star_wars.jpg',
"plot" => 'Three decades after the defeat of the Galactic Empire, a new threat arises. The First Order attempts to rule the galaxy and only a ragtag group of heroes can stop them, along with the help of the Resistance.'
},
{
"imdb_key" => 'tt0112384',
"price" => 6295,
"year" => 1995,
"mpaa" => 'PG',
"title" => 'Apollo 13',
"poster" => 'apollo_13.jpg',
"plot" => 'NASA must devise a strategy to return Apollo 13 to Earth safely after the spacecraft undergoes massive internal damage putting the lives of the three astronauts on board in jeopardy.'
},
{
"imdb_key" => 'tt0162222',
"price" => 1295,
"year" => 2000,
"mpaa" => 'PG-13',
"title" => 'Cast Away',
"poster" => 'cast_away.jpg',
"plot" => 'A FedEx executive must transform himself physically and emotionally to survive a crash landing on a deserted island.'
},
{
"imdb_key" => 'tt2015381',
"price" => 3295,
"year" => 2014,
"mpaa" => 'PG-13',
"title" => 'Guardians of the Galaxy',
"poster" => 'guardians.jpg',
"plot" => 'A group of intergalactic criminals are forced to work together to stop a fanatical warrior from taking control of the universe.'
}
]
movies.each do |movie_data|
m = Movie.new
m.title = movie_data["title"]
m.plot = movie_data["plot"]
m.imdb_key = movie_data["imdb_key"]
m.price = movie_data["price"]
m.year = movie_data["year"]
m.mpaa = movie_data["mpaa"]
m.poster_url = movie_data["poster"]
m.save
end
print "There are now #{Movie.count} movies in the database.\n"
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources "cards"
resources "movies"
# root 'cards#index'
end
| 087b64a80626e8eea39c3e91e7b242b237887d38 | [
"Markdown",
"Ruby"
]
| 4 | Ruby | JeffCohen/classroom | 52cb95ebfbbfcfceedf3949cdff220052021d965 | fbd6d80e67a194892fe8391442c4bc260cd4673d |
refs/heads/master | <file_sep>package com.seniorfinalpro.seniorproject311.Model;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by Pc100 on 17/12/2559.
*/
public class ListModel implements Serializable {
ArrayList<ItemModle> list = new ArrayList<>();
public ArrayList<ItemModle> getList() {
return list;
}
public void setList(ArrayList<ItemModle> list) {
this.list = list;
}
}
<file_sep>package com.seniorfinalpro.seniorproject311.Model;
import java.io.Serializable;
/**
* Created by Pc100 on 17/12/2559.
*/
public class CloudModel implements Serializable{
public int getAll() {
return all;
}
public void setAll(int all) {
this.all = all;
}
int all;
}
| f1a8e65b3c97da25a428a00840f04d2b533f915d | [
"Java"
]
| 2 | Java | nook0019/SeniorProject311 | ba77ad0d24beffc76229720f4cdb6a474282c46c | 31a6ab9ba44bf4a1453f53e7b8d672f5957c04ee |
refs/heads/master | <file_sep>#!/bin/sh
set -e
export PGUSER="$POSTGRES_USER"
"${psql[@]}" --dbname="$DB" <<-'EOSQL'
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION "uuid-ossp";
EOSQL
<file_sep>[]()
[]()
# docker-min-postgres-postgis
A very minimalist Docker image with PostgreSQL 10.4 and PostGIS 2.4.4.
Build based on PostgreSQL [official images](https://hub.docker.com/_/postgres/).
## Build the image
```sh
docker build -t postgis .
```
## Usage
Should be used for development purposes only.
Use it with Vagrant:
```
d.image = "jean553/minimalist-postgres-postgis"
```
## Credits
Mainly based on examples from the project https://github.com/appropriate/docker-postgis,
distributed under the MIT license (https://github.com/appropriate/docker-postgis/blob/master/LICENSE).
<file_sep>FROM postgres:10.4
RUN apt-get update \
&& apt-get install -y postgis \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir -p /docker-entrypoint-initdb.d
COPY ./initdb-postgis.sh /docker-entrypoint-initdb.d/postgis.sh
| 4c16b9874310d5488dbea60e4cd62fefa358d6a3 | [
"Markdown",
"Dockerfile",
"Shell"
]
| 3 | Shell | jean553/minimalist-postgres-postgis | 901dd76622c142b11c356ebb3b32ba593067105c | c3450796da42566e162c56e10f1ca3e76a795778 |
refs/heads/master | <file_sep>import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
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.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class Task3 {
/*
The Lord of The Rings,5,4,4,,3,2
Apocalypto,3,5,4,,5,4
Apollo 13,,,4,5,,5
*/
public static class UserRatingMapper extends Mapper<Object, Text, IntWritable, IntWritable> {
private final static IntWritable ONE = new IntWritable(1);
private final static IntWritable ZERO = new IntWritable(0);
private final IntWritable user = new IntWritable();
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
final String[] tokens = value.toString().split(",", -1);
for (int i = 1; i < tokens.length; i++) {
user.set(i);
context.write(user, tokens[i].isEmpty() ? ZERO : ONE);
}
}
}
public static class UserRatingSumReducer extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
private final IntWritable sum = new IntWritable();
@Override
protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int numRatings = 0;
for (IntWritable val : values) {
numRatings += val.get();
}
sum.set(numRatings);
context.write(key, sum);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("mapreduce.output.textoutputformat.separator", ",");
Job job = Job.getInstance(conf, "Task3");
job.setJarByClass(Task3.class);
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
// add code here
job.setMapperClass(UserRatingMapper.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(IntWritable.class);
job.setCombinerClass(UserRatingSumReducer.class);
job.setReducerClass(UserRatingSumReducer.class);
TextInputFormat.addInputPath(job, new Path(otherArgs[0]));
TextOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
<file_sep>import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.*;
import java.util.*;
public class A4Application {
static class RoomState {
private Long occupancy;
private Long capacity;
private String output;
RoomState() {
}
RoomState(Long occupancy, Long capacity) {
this.occupancy = occupancy;
this.capacity = capacity;
}
boolean isOk() {
return occupancy == null || capacity == null || occupancy <= capacity;
}
boolean isOverloaded() {
return !isOk();
}
void setOutput(String output) {
this.output = output;
}
boolean hasOutput() {
return output != null;
}
String getOutput() {
return output;
}
@Override
public String toString() {
return String.format("RoomState{occupancy=%s, capacity=%s}", occupancy, capacity);
}
}
static class RoomStateSerializer implements Serializer<RoomState> {
@Override
public byte[] serialize(String s, RoomState roomState) {
if (roomState == null) return null;
return String.format("%s,%s", roomState.occupancy, roomState.capacity).getBytes();
}
}
static class RoomStateDeserializer implements Deserializer<RoomState> {
@Override
public RoomState deserialize(String s, byte[] bytes) {
if (bytes == null) return null;
String[] tokens = new String(bytes).split(",");
Long occupancy = !tokens[0].equals("null") ? Long.valueOf(tokens[0]) : null;
Long capacity = !tokens[1].equals("null") ? Long.valueOf(tokens[1]) : null;
return new RoomState(occupancy, capacity);
}
}
public static void main(String[] args) throws Exception {
// do not modify the structure of the command line
String bootstrapServers = args[0];
String appName = args[1];
String studentTopic = args[2];
String classroomTopic = args[3];
String outputTopic = args[4];
String stateStoreDir = args[5];
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, appName);
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.STATE_DIR_CONFIG, stateStoreDir);
Serde<RoomState> stateSerde = Serdes.serdeFrom(new RoomStateSerializer(), new RoomStateDeserializer());
StreamsBuilder builder = new StreamsBuilder();
// student -> latest room
KTable<String, String> students = builder.table(studentTopic);
// room -> current capacity
KTable<String, Long> roomCapacity = builder.<String, String>table(classroomTopic)
.mapValues((ValueMapper<String, Long>) Long::valueOf);
// room -> current occupancy
KTable<String, Long> roomOccupancy = students
.groupBy((student, room) -> KeyValue.pair(room, student))
.count();
/*
* 1. Join current occupancy with current capacity,
* 2. Group the joined stream by room,
* 3. Accumulate a state for each room using aggregate(),
* 4. Filter only the notable state changes (overloaded or OK) from the aggregation stream to the output topic.
*/
roomOccupancy
.outerJoin(roomCapacity, (occupancy, capacity) -> {
System.out.printf("joining on room: occupancy=%s, capacity=%s\n", occupancy, capacity);
return new RoomState(occupancy, capacity);
}, Materialized.with(Serdes.String(), stateSerde))
.toStream()
.groupByKey()
.aggregate(RoomState::new, (room, newState, prevState) -> {
System.out.printf("aggregate: room=%s, newState=%s prevState=%s\n", room, newState, prevState);
if (newState.isOverloaded()) {
newState.setOutput(String.valueOf(newState.occupancy));
} else if (newState.isOk() && prevState.isOverloaded()) {
newState.setOutput("OK");
}
return newState;
}, Materialized.with(Serdes.String(), stateSerde))
.toStream()
.filter((room, state) -> state.hasOutput())
.mapValues(RoomState::getOutput)
.to(outputTopic);
KafkaStreams streams = new KafkaStreams(builder.build(), props);
// this line initiates processing
streams.start();
// shutdown hook for Ctrl+C
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
}
}
<file_sep>#!/bin/sh
export JAVA_HOME=/usr/lib/jvm/java-8-oracle
export SCALA_HOME=/usr
export CLASSPATH=".:/opt/spark-latest/jars/*"
TASK=Task3
echo --- Deleting
rm $TASK.jar
rm $TASK*.class
echo --- Compiling
$SCALA_HOME/bin/scalac -J-Xmx1g $TASK.scala
if [ $? -ne 0 ]; then
exit
fi
echo --- Jarring
$JAVA_HOME/bin/jar -cf $TASK.jar $TASK*.class
echo --- Running
INPUT=/tmp/smalldata.txt
OUTPUT=/user/${USER}/a2_starter_code_output/
hdfs dfs -rm -R $OUTPUT
hdfs dfs -copyFromLocal sample_input/smalldata.txt /tmp
time spark-submit --master yarn --class $TASK --driver-memory 4g --executor-memory 4g $TASK.jar $INPUT $OUTPUT
hdfs dfs -ls $OUTPUT
hdfs dfs -copyToLocal $OUTPUT /home2/p99patel/outputSpark/
<file_sep>import java.net.InetAddress;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.*;
public class BENode {
static Logger log;
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.println("Usage: java BENode FE_host FE_port BE_port");
System.exit(-1);
}
String hostFE = args[0];
int portFE = Integer.parseInt(args[1]);
// initialize log4j
BasicConfigurator.configure();
log = Logger.getLogger(BENode.class.getName());
// create client to front end
TSocket sock = new TSocket(hostFE, portFE);
TTransport transport = new TFramedTransport(sock);
TProtocol protocol = new TBinaryProtocol(transport);
BcryptService.Client feClient = new BcryptService.Client(protocol);
// Continuously ping the front-end to notify of this backend nodes existence
BEHeartbeat heartBeat = new BEHeartbeat(getHostName(), args[2], transport, feClient);
heartBeat.start();
// launch Thrift server
int portBE = Integer.parseInt(args[2]);
log.info("Launching BE node on port " + portBE + " at host " + getHostName());
BcryptService.Processor processor = new BcryptService.Processor<BcryptService.Iface>(new BcryptServiceHandler());
TNonblockingServerTransport socket = new TNonblockingServerSocket(portBE);
TThreadedSelectorServer.Args sargs = new TThreadedSelectorServer.Args(socket)
.protocolFactory(new TBinaryProtocol.Factory())
.transportFactory(new TFramedTransport.Factory())
.processorFactory(new TProcessorFactory(processor));
// sargs.maxWorkerThreads(64);
// TThreadPoolServer creates uses a different thread for each client connection (from a fixed pool of threads)
// Using TThreadPoolServer is throwing this ERROR org.apache.thrift.server.TThreadPoolServer - Thrift error occurred during processing of message.
//org.apache.thrift.transport.TTransportException
// TThreadedSelectorServer server = new TThreadedSelectorServer(sargs);
TThreadedSelectorServer server = new TThreadedSelectorServer(sargs);
server.serve();
}
private static void print(String s) {
System.out.println(Thread.currentThread().getName() + ": " + s);
}
private static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
return "localhost";
}
}
}
<file_sep>import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransport;
import org.mindrot.jbcrypt.BCrypt;
public class BcryptServiceHandler implements BcryptService.Iface {
// # threads = # cores -> TODO: might want a few more threads than cores
private static final int NUM_THREADS = Runtime.getRuntime().availableProcessors();
private final boolean isBackEnd;
BcryptServiceHandler() {
this(false);
}
BcryptServiceHandler(boolean isFrontEnd) {
this.isBackEnd = !isFrontEnd;
}
@Override
public List<String> hashPassword(List<String> password, short logRounds) throws IllegalArgument, TException {
return isBackEnd
? performHashPassword(password, logRounds)
: offloadHashPasswordToBE(password, logRounds);
}
@Override
public List<Boolean> checkPassword(List<String> password, List<String> hash) throws IllegalArgument, TException {
return isBackEnd
? performCheckPassword(password, hash)
: offloadCheckPasswordToBE(password, hash);
}
@Override
public void ping(String host, String port) throws IllegalArgument, TException {
// Front end received ping from backend @host:port
System.out.println("Received ping from " + host + ":" + port);
FEWorkerManager.addWorker(host, port);
}
private List<String> performHashPassword(List<String> passwords, short logRounds) throws IllegalArgument, TException {
final int numPasswords = passwords.size();
System.out.println("hashing passwords " + passwords.size());
try {
if (numPasswords > 1) { // parallelize the computation
// Make sure this is <= number of fixed threads in the executor
final int threads = Math.min(NUM_THREADS, numPasswords);
final int passwordsPerThread = numPasswords / threads;
System.out.printf("running in parallel: %s threads, %s pwds per thread\n", threads, passwordsPerThread);
final String[] result = new String[numPasswords];
ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < threads; i++) {
final int start = i * passwordsPerThread;
final int end = i < threads - 1 ? (i + 1) * passwordsPerThread : numPasswords;
executorService.submit(() -> {
for (int j = start; j < end; j++) {
result[j] = BCrypt.hashpw(passwords.get(j), BCrypt.gensalt(logRounds));
}
});
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
System.out.println("finished hashing " + Arrays.asList(result));
return Arrays.asList(result);
} else { // run it on a single thread if there's only one password
List<String> res = new ArrayList<>(passwords.size());
for (String pass : passwords) {
res.add(BCrypt.hashpw(pass, BCrypt.gensalt(logRounds)));
}
System.out.println("finished hashing");
return res;
}
} catch (Exception e) {
System.out.println("hashing password failed! " + e.getMessage());
throw new IllegalArgument(e.getMessage());
}
}
private List<String> offloadHashPasswordToBE(List<String> passwords, short logRounds) throws IllegalArgument, TException {
if (passwords.isEmpty()) {
throw new IllegalArgument("Password list is empty!");
} else if (logRounds < 4 || logRounds > 30) {
throw new IllegalArgument("Log rounds out of range! Must be within [4, 30]");
}
FEWorkerManager.WorkerMetadata workerBE = FEWorkerManager.findAvailableWorker();
System.out.println(Thread.currentThread().getName() + " FOUND WORKER: " + workerBE);
while (workerBE != null) {
// Found a worker! Sending workload to BE
workerBE.obtainClientConnection();
TTransport transportToBE = workerBE.getTransport();
BcryptService.Client clientToBE = workerBE.getClient();
try {
final int workload = (int) (passwords.size() * Math.pow(2, logRounds));
workerBE.setBusy(true);
workerBE.incrementLoad(workload);
transportToBE.open();
List<String> hashes = clientToBE.hashPassword(passwords, logRounds);
transportToBE.close();
workerBE.decrementLoad(workload);
workerBE.setBusy(false);
System.out.println("Worker replied with hashes " + hashes);
return hashes;
} catch (Exception e) {
// The chosen workerBE failed to hashPasswords (might be down)
// remove it from our pool of workers and try to find another worker
System.out.println("Worker failed: " + e.getMessage());
FEWorkerManager.removeWorker(workerBE);
workerBE = FEWorkerManager.findAvailableWorker();
} finally {
if (transportToBE.isOpen()) {
transportToBE.close();
}
}
}
// No workers available! Perform the hashing here on the FE
System.out.println("No BE workers available! Performing locally");
return performHashPassword(passwords, logRounds);
}
private List<Boolean> performCheckPassword(List<String> passwords, List<String> hashes) throws IllegalArgument, TException {
final int numPasswords = passwords.size();
System.out.println("checking passwords " + passwords.size());
try {
if (numPasswords > 1) { // parallelize the computation
// Make sure this is <= number of fixed threads in the executor
final int threads = Math.min(NUM_THREADS, numPasswords);
final int passwordsPerThread = numPasswords / threads;
final Boolean[] result = new Boolean[numPasswords];
System.out.printf("running in parallel: %s threads, %s pwds per thread\n", threads, passwordsPerThread);
ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
for (int t = 0; t < threads; t++) {
final int start = t * passwordsPerThread;
final int end = t < threads - 1 ? (t + 1) * passwordsPerThread : numPasswords;
executorService.submit(() -> {
for (int i = start; i < end; i++) {
boolean check;
try {
check = BCrypt.checkpw(passwords.get(i), hashes.get(i));
} catch (Exception e) {
check = false;
}
result[i] = check;
}
});
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
System.out.println("finished checking " + Arrays.asList(result));
return Arrays.asList(result);
} else { // run it on a single thread if there's only one password
List<Boolean> res = new ArrayList<>(passwords.size());
for (int i = 0; i < passwords.size(); i++) {
boolean check;
try {
check = BCrypt.checkpw(passwords.get(i), hashes.get(i));
} catch (Exception e) {
check = false;
}
res.add(check);
}
System.out.println("finished checking");
return res;
}
} catch (Exception e) {
System.out.println("hashing password failed!");
throw new IllegalArgument(e.getMessage());
}
}
private List<Boolean> offloadCheckPasswordToBE(List<String> password, List<String> hash) throws IllegalArgument, TException {
// Error checking at FE (throw error at client):
if (password.isEmpty() || hash.isEmpty()) {
throw new IllegalArgument("Password or hash list is empty!");
} else if (password.size() != hash.size()) {
throw new IllegalArgument("Password and hash lists have unequal length!");
}
FEWorkerManager.WorkerMetadata workerBE = FEWorkerManager.findAvailableWorker();
while (workerBE != null) {
// Found a worker! Sending workload to BE
workerBE.obtainClientConnection();
TTransport transportToBE = workerBE.getTransport();
BcryptService.Client clientToBE = workerBE.getClient();
try {
final int workload = password.size();
workerBE.setBusy(true);
workerBE.incrementLoad(workload);
transportToBE.open();
List<Boolean> checks = clientToBE.checkPassword(password, hash);
transportToBE.close();
workerBE.decrementLoad(workload);
workerBE.setBusy(false);
System.out.println("Worker replied with checks" + checks);
return checks;
} catch (Exception e) {
// The chosen workerBE failed to hashPasswords (might be down)
// remove it from our pool of workers and try to find another worker
System.out.println("Worker failed: " + e.getMessage());
FEWorkerManager.removeWorker(workerBE);
workerBE = FEWorkerManager.findAvailableWorker();
} finally {
if (transportToBE.isOpen()) {
transportToBE.close();
}
}
}
// No workers available! Perform the hashing here on the FE
return performCheckPassword(password, hash);
}
}
<file_sep>import org.apache.thrift.transport.TTransport;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class BEHeartbeat {
private static final int PING_PERIOD_SECONDS = 3;
private final Runnable ping;
private final ScheduledExecutorService pingExecutor = Executors.newSingleThreadScheduledExecutor();
BEHeartbeat(String host, String port, TTransport transport, BcryptService.Client client) {
ping = () -> {
System.out.println("Attempting to ping FE");
try {
transport.open();
client.ping(host, port);
transport.close();
System.out.println("Ping FE successful");
} catch (Exception e) {
System.out.println("FE not up yet");
}
};
}
void start() {
pingExecutor.scheduleAtFixedRate(ping, 0, PING_PERIOD_SECONDS, TimeUnit.SECONDS);
}
}
<file_sep>#!/bin/bash
#
# <NAME>, 2016-2019
#
# brew install [email protected]
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
JAVA=$JAVA_HOME/bin/java
JAVA_CC=$JAVA_HOME/bin/javac
THRIFT_CC=thrift
echo --- Cleaning
rm -f *.jar
rm -f *.class
rm -fr gen-java
echo --- Compiling Thrift IDL
$THRIFT_CC --version &> /dev/null
ret=$?
if [ $ret -ne 0 ]; then
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "ERROR: The Thrift compiler does not work on this host."
echo " Please build on one of the eceubuntu or ecetesla hosts."
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
exit 1
fi
$THRIFT_CC --version
$THRIFT_CC --gen java:generated_annotations=suppress a1.thrift
echo --- Compiling Java
$JAVA_CC -version
$JAVA_CC gen-java/*.java -cp .:"lib/*"
$JAVA_CC *.java -cp .:gen-java/:"lib/*":"jBCrypt-0.4/*"
echo --- Done, now run your code.
echo Examples:
echo $JAVA '-cp .:gen-java/:"lib/*":"jBCrypt-0.4/*" FENode 10123'
echo $JAVA '-cp .:gen-java/:"lib/*":"jBCrypt-0.4/*" BENode localhost 10123 10124'
echo $JAVA '-cp .:gen-java/:"lib/*":"jBCrypt-0.4/*" Client localhost 10123 hello'
<file_sep>#!/bin/sh
ssh -i ~/Desktop/student_p99patel -L 8080:127.0.0.1:3128 [email protected] "rm -rf a2"
scp -r ~/Desktop/4A/ECE_454/assignments/a2 <EMAIL>:/home2/p99patel/
<file_sep>import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class Task1 {
// add code here
public static class MaxRatingMapper extends Mapper<Object, Text, Text, Text> {
private Text title = new Text();
private Text maxUsers = new Text();
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
final String[] tokens = value.toString().split(",", -1);
title.set(tokens[0]);
int maxRating = 0;
for (int i = 1; i < tokens.length; i++) {
if (tokens[i].isEmpty()) continue;
int rating = Integer.parseInt(tokens[i]);
if (rating > maxRating) {
maxRating = rating;
maxUsers.clear();
maxUsers.set(String.valueOf(i));
} else if (rating == maxRating) {
byte[] bytes = String.format(",%s", i).getBytes();
maxUsers.append(bytes, 0, bytes.length);
}
}
context.write(title, maxUsers);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("mapreduce.output.textoutputformat.separator", ",");
Job job = Job.getInstance(conf, "Task1");
job.setJarByClass(Task1.class);
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
// add code here
job.setMapperClass(MaxRatingMapper.class);
job.setNumReduceTasks(0);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
TextInputFormat.addInputPath(job, new Path(otherArgs[0]));
TextOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
<file_sep>#!/bin/bash
#
# <NAME>, 2016
#
#source settings.sh
#JAVA_CC=$JAVA_HOME/bin/javac
#THRIFT_CC=./thrift-0.12.0
export CLASSPATH=".:gen-java/:lib/*"
echo --- Cleaning
rm -f *.class
rm -fr gen-java
echo --- Compiling Thrift IDL
thrift --version &> /dev/null
ret=$?
if [ $ret -ne 0 ]; then
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "ERROR: The Thrift compiler does not work on this host."
echo " Please build on one of the eceubuntu or ecetesla hosts."
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
exit 1
fi
thrift --version
thrift --gen java:generated_annotations=suppress a3.thrift
echo --- Compiling Java
javac -version
javac gen-java/*.java
javac *.java
<file_sep>#!/bin/sh
export JAVA_HOME=/usr/lib/jvm/java-8-oracle
export CLASSPATH=`hadoop classpath`
TASK=Task4
echo --- Deleting
rm $TASK.jar
rm $TASK*.class
echo --- Compiling
$JAVA_HOME/bin/javac $TASK.java
if [ $? -ne 0 ]; then
exit
fi
echo --- Jarring
$JAVA_HOME/bin/jar -cf $TASK.jar $TASK*.class
echo --- Running
INPUT=/tmp/smalldata.txt
OUTPUT=/user/${USER}/a2_starter_code_output/
hdfs dfs -rm -R $OUTPUT
hdfs dfs -copyFromLocal sample_input/smalldata.txt /tmp
time yarn jar $TASK.jar $TASK -D mapreduce.map.java.opts=-Xmx4g $INPUT $OUTPUT
hdfs dfs -ls $OUTPUT
hdfs dfs -copyToLocal $OUTPUT /home2/p99patel/outputHadoop/
| 7e9f95c2f1f2bc861e515dcdf2925c0f6aefebcf | [
"Java",
"Shell"
]
| 11 | Java | y226xie/ece454 | 3eba42d0a53fb5320eade05a4b2b6c601fc0d603 | cc1c1ec277de38f4b2ad5c4aeb49b82690d7bf43 |
refs/heads/master | <repo_name>Midenko/taskFormAngular2<file_sep>/src/app/services/filling-languages.service/filling-rus.ts
export const VALIDATION_MESSAGES_RUS = {
"name": {
"required": "Введите имя",
},
"email": {
"required": "Введите E-mail",
"pattern": "Неверный E-mail"
},
"login": {
"required": "Введите логин",
},
"password": {
"required": "Введите пароль",
"pattern": "Пароль должен содержать не меньше 6 символов"
},
"repeatPassword": {
"required": "Повторите пароль",
"repeatPasswordValidator": "Введённые пароли не совподают"
}
};
export const REGISTRATION_FILLING_RUS = {
"header": "Регистрация",
"name": "Имя",
"login": "Логин",
"email": "E-mail",
"password": "<PASSWORD>",
"repeatPassword": "<PASSWORD>",
"buttonNext": "Дальше"
};
export const CONFIRMATION_FILLING_RUS = {
"header": "Подтверждение",
"welcome": "Добро пожаловать, ",
"buttonBack": "Обратно к регестрации"
};<file_sep>/src/app/services/filling-languages.service/filling-eng.ts
export const VALIDATION_MESSAGES_ENG = {
"name": {
"required": "Enter your name",
},
"email": {
"required": "Enter your E-mail",
"pattern": "Error E-mail"
},
"login": {
"required": "Enter your login",
},
"password": {
"required": "Enter your password",
"pattern": "At least 6 characters"
},
"repeatPassword": {
"required": "Repeat password",
"repeatPasswordValidator": "Passwords must match"
}
};
export const REGISTRATION_FILLING_ENG = {
"header": "Registration",
"name": "Name",
"login": "Login",
"email": "E-mail",
"password": "<PASSWORD>",
"repeatPassword": "<PASSWORD>",
"buttonNext": "Next"
};
export const CONFIRMATION_FILLING_ENG = {
"header": "Confirmation",
"welcome": "Welcome ",
"buttonBack": "go to regestration"
};
<file_sep>/README.md
Необходимо реализовать двухстраничный модуль регистрации. Обязательно использовать роутинг.
Первая страница — форма регистрации.
https://drive.google.com/open?id=0B8NpA0i6Rq6QQm5ZajA2SFRRd0U
Вторая страница — подтверждение успешной регистрации.
https://drive.google.com/open?id=0B8NpA0i6Rq6QVGZGNlZUN054M3c
1. Первая страница содержит форму со след полями, указанными на первой картинке.
2. Все поля валидируются, все поля обязательны.
3. Поле почты проверяется на валидность формата.
4. Поле пароля и подтверждение пароля должны содержать 2 разные директивы. Директива на поле с паролем принимает регулярное выражение по которому валидируется пароль, поле подтверждение пароля валидируется на соответствие данным введенным в поле пароль.
5. Все валидируемые поля отображают сообщения об ошибках, в случае некорректного заполнения.
6. Валидация всех полей происходит по кнопке зарегистрировать.
7. В случае успешного прохождения всех валидаций, попадаем на страницу подтверждения регистрации, содержащий текст “Welcome <Name>”.
На форму подтверждения регистрации можно добавить кнопку, которая ведет на первую страницу (на регистрацию) где полностью очищена форма.
Добавить мультиязычность.
<file_sep>/src/app/services/filling-languages.service/filling-languages.service.ts
import { Injectable } from "@angular/core";
import {VALIDATION_MESSAGES_ENG, REGISTRATION_FILLING_ENG, CONFIRMATION_FILLING_ENG} from "./filling-eng";
import {VALIDATION_MESSAGES_RUS, REGISTRATION_FILLING_RUS, CONFIRMATION_FILLING_RUS} from "./filling-rus";
@Injectable()
export class FillingLanguageService {
filling: {} = {
"eng" : {
"validationMesssages": VALIDATION_MESSAGES_ENG,
"registrationFilling": REGISTRATION_FILLING_ENG,
"confirmationFilling": CONFIRMATION_FILLING_ENG
},
"rus": {
"validationMesssages": VALIDATION_MESSAGES_RUS,
"registrationFilling" : REGISTRATION_FILLING_RUS,
"confirmationFilling": CONFIRMATION_FILLING_RUS
}
};
selectedLanguage: string = "rus";
getValidationMesssages(): any {
return this.filling[this.selectedLanguage].validationMesssages;
}
getRegistrationFilling(): any {
return this.filling[this.selectedLanguage].registrationFilling;
}
getConfirmationFilling(): any {
return this.filling[this.selectedLanguage].confirmationFilling;
}
}<file_sep>/src/app/components/test-form.component/test-form.component.ts
import {Component, OnInit, DoCheck} from "@angular/core";
import {FormGroup, Validators, FormControl} from "@angular/forms";
import { Router } from "@angular/router";
import {User} from "../../services/user.service/user";
import {UserService} from "../../services/user.service/user.service";
import {FillingLanguageService} from "../../services/filling-languages.service/filling-languages.service";
import {repeatPasswordValidator} from "../../functions/validators";
const EMAIL_REGEXP: string = "[A-Za-z0-9._&-]+@[A-Za-z0-9.-]+\.[a-z]{2,4}";
// Буквы, цифры, дефисы, подчёркивания, точки и @. Минимум 6 символов
const PASSWORD_REGEXP: string = "^[A-Za-z0-9.@_-]{6,}$";
@Component({
moduleId: module.id,
selector: "testForm",
templateUrl: "test-form.component.html",
styleUrls: ["test-form.component.css"]
})
export class TestFormComponent implements OnInit, DoCheck {
userForm: FormGroup;
users: User[] = [];
path: string = "confirmation";
validationMessages: object;
filling: object;
formErrors = {
"name": "",
"login": "",
"email": "",
"password": "",
"repeatPassword": ""
};
constructor(private userService: UserService, private router: Router, private fls: FillingLanguageService) {
this.userForm = new FormGroup({
name: new FormControl("", Validators.required),
login: new FormControl("", [Validators.required]),
email: new FormControl("", [Validators.required, Validators.pattern(EMAIL_REGEXP)]),
password: new FormControl("", [Validators.required, Validators.pattern(PASSWORD_REGEXP)]),
repeatPassword: new FormControl("", [Validators.required])
}, repeatPasswordValidator);
}
ngOnInit() {
this.getUsers();
this.validationMessages = this.fls.getValidationMesssages();
this.filling = this.fls.getRegistrationFilling();
}
ngDoCheck() {
this.validationMessages = this.fls.getValidationMesssages();
this.filling = this.fls.getRegistrationFilling();
}
onSubmit(): void {
let form: FormGroup = this.userForm;
this.setErrorMessage(form);
if (this.isValidate() && this.loginValidate()) {
this.addUser(form.value);
this.userService.lastName = form.value.name;
this.router.navigate([this.path]);
}
}
addUser(userData: any = this.userForm.value): void {
if (this.isValidate()) {
this.userService.addUser(userData);
}
}
getUsers(): User[] {
this.userService.getUsers().then(users => this.users = users);
return this.users;
}
setErrorMessage(form: any) {
for (let field in this.formErrors) {
this.formErrors[field] = "";
let control = form.get(field);
if (!control.valid || !form.valid) {
let message = this.validationMessages[field];
for (let key in control.errors) {
this.formErrors[field] += message[key] + ". ";
}
for (let key in form.errors) {
if (message[key]) {
this.formErrors[field] = message[key] + " ";
}
}
}
}
}
isValidate(): boolean {
return (this.userForm.status === "VALID");
}
loginValidate(users: User[] = this.getUsers()): boolean {
let checkedLogin = this.userForm.value.login;
let field = "login";
for (let user of users) {
if (user.login === checkedLogin) {
this.formErrors[field] = "This login already exists";
return false;
}
}
return true;
}
}<file_sep>/src/app/app.module.ts
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { ReactiveFormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
import { TestFormComponent } from "./components/test-form.component/test-form.component";
import { ConfirmationComponent } from "./components/confirmation.component/confirmation.component";
import { RadioButtonComponent } from "./components/radio-button.component/radio-button.component";
import { AppRoutingModule } from "./route/app-routing.module";
import { UserService } from "./services/user.service/user.service";
import { FillingLanguageService } from "./services/filling-languages.service/filling-languages.service";
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
AppRoutingModule,
],
declarations: [
AppComponent,
TestFormComponent,
ConfirmationComponent,
RadioButtonComponent
],
providers: [
UserService,
FillingLanguageService
],
bootstrap: [AppComponent]
})
export class AppModule {}<file_sep>/src/app/services/user.service/user.service.ts
import { Injectable } from "@angular/core";
import { User } from "./user";
import { USERS } from "./users";
@Injectable()
export class UserService {
lastName: string;
getUsers(): Promise<User[]> {
return Promise.resolve(USERS);
}
getUser(id: number): Promise<User> {
return this.getUsers()
.then(users => users.find(user => user.id === id));
}
addUser(userData: any): void {
let user = new User();
user.id = USERS.length + 1;
let {name, login, email, password} = userData;
user.name = name;
user.login = login;
user.email = email;
user.password = <PASSWORD>;
USERS.push(user);
}
}<file_sep>/src/app/components/radio-button.component/radio-button.component.ts
import {Component} from "@angular/core";
import { FillingLanguageService} from "../../services/filling-languages.service/filling-languages.service";
@Component({
moduleId: module.id,
selector: "radioButton",
templateUrl: "radio-button.component.html"
})
export class RadioButtonComponent {
selectedLanguale: string = this.fls.selectedLanguage;
constructor(private fls: FillingLanguageService) {}
changeLanguage(lang: string) {
this.selectedLanguale = lang;
this.fls.selectedLanguage = lang;
}
}
<file_sep>/src/app/components/confirmation.component/confirmation.component.ts
import {Component, OnInit, DoCheck} from "@angular/core";
import {UserService} from "../../services/user.service/user.service";
import {FillingLanguageService} from "../../services/filling-languages.service/filling-languages.service";
@Component({
moduleId: module.id,
selector: "confirmation",
templateUrl: "confirmation.component.html",
styleUrls: ["confirmation.component.css"],
})
export class ConfirmationComponent implements OnInit, DoCheck {
name: string;
filling: object;
constructor(private userService: UserService, private fls: FillingLanguageService) { }
ngOnInit(): void {
this.setName();
this.filling = this.fls.getConfirmationFilling();
}
ngDoCheck() {
this.filling = this.fls.getConfirmationFilling();
}
setName(): void {
this.name = this.userService.lastName;
}
}<file_sep>/src/app/functions/validators.ts
import {FormGroup} from "@angular/forms";
export function repeatPasswordValidator(g: FormGroup): { [key: string]: any } {
return g.get("password").value === g.get("repeatPassword").value
? null : {"repeatPasswordValidator": {}};
}
| f17a6d5792f290c76d936fa9fcfad73956e3df99 | [
"Markdown",
"TypeScript"
]
| 10 | TypeScript | Midenko/taskFormAngular2 | a832d76030b7bfccd4802a5075df1c41f1cc74a7 | 4b74f492581c04fe00dc45df62d045f407e22420 |
refs/heads/master | <repo_name>Usevalad/MegaKitTest<file_sep>/app/src/main/java/com/vsevolod/megakittest/model/Driver.java
/*
* Copyright (c) 2017.
* <NAME>
* <EMAIL>
*/
package com.vsevolod.megakittest.model;
import com.vsevolod.megakittest.constant.Constants;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
/**
* Created by <NAME> on 8/8/17.
* <EMAIL>
*/
public class Driver extends RealmObject implements Model {
@PrimaryKey
private long uid;
private String firstName;
private String lastName;
private String phoneNumber;
private RealmList<Car> cars;
public Driver(String firstName, String lastName, String phoneNumber, RealmList<Car> cars) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.cars = cars;
}
public Driver(String firstName, String lastName, String phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
}
/**
* Realm needs a public constructor with no arguments
*/
public Driver() {
}
public long getId() {
return uid;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Override
public int getDataType() {
return Constants.DATA_TYPE_DRIVER;
}
}<file_sep>/app/src/main/java/com/vsevolod/megakittest/view/FABView.java
/*
* Copyright (c) 2017.
* <NAME>
* <EMAIL>
*/
package com.vsevolod.megakittest.view;
import android.content.Context;
import android.support.design.widget.FloatingActionButton;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.vsevolod.megakittest.R;
/**
* Created by <NAME> on 8/9/17.
* <EMAIL>
*/
public class FABView {
private FloatingActionButton mFAB;
private FloatingActionButton mFABCar;
private FloatingActionButton mFABDriver;
private Animation mFabOpen;
private Animation mFabClose;
private Animation mRotateForward;
private Animation mRotateBackward;
private boolean isFabOpen = false;
public FABView(View rootView) {
Context context = rootView.getContext();
mFAB = (FloatingActionButton) rootView.findViewById(R.id.fab);
mFABCar = (FloatingActionButton) rootView.findViewById(R.id.fab_car);
mFABDriver = (FloatingActionButton) rootView.findViewById(R.id.fab_driver);
mFabOpen = AnimationUtils.loadAnimation(context, R.anim.fab_open);
mFabClose = AnimationUtils.loadAnimation(context, R.anim.fab_close);
mRotateForward = AnimationUtils.loadAnimation(context, R.anim.rotate_forward);
mRotateBackward = AnimationUtils.loadAnimation(context, R.anim.rotate_backward);
}
public void setOnClickListeners(View.OnClickListener onClickListener) {
mFABCar.setOnClickListener(onClickListener);
mFABDriver.setOnClickListener(onClickListener);
mFAB.setOnClickListener(onClickListener);
}
public void removeOnClickListeners() {
mFABCar.setOnClickListener(null);
mFABDriver.setOnClickListener(null);
mFAB.setOnClickListener(null);
}
public void animateFAB() {
if (isFabOpen) {
mFAB.startAnimation(mRotateBackward);
mFABCar.startAnimation(mFabClose);
mFABDriver.startAnimation(mFabClose);
mFABCar.setClickable(false);
mFABDriver.setClickable(false);
isFabOpen = false;
} else {
mFAB.startAnimation(mRotateForward);
mFABCar.startAnimation(mFabOpen);
mFABDriver.startAnimation(mFabOpen);
mFABCar.setClickable(true);
mFABDriver.setClickable(true);
isFabOpen = true;
}
}
}<file_sep>/app/src/main/java/com/vsevolod/megakittest/view/CarView.java
/*
* Copyright (c) 2017.
* <NAME>
* <EMAIL>
*/
package com.vsevolod.megakittest.view;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.vsevolod.megakittest.R;
import com.vsevolod.megakittest.Repository;
import com.vsevolod.megakittest.model.Car;
/**
* Created by <NAME> on 8/8/17.
* <EMAIL>
*/
public class CarView {
private final Context mContext;
private final ImageView mCarImageView;
private final TextView mManufacturerTextView;
private final TextView mModelTextView;
private final TextView mBodyTypeTextView;
public CarView(View rootView) {
this.mContext = rootView.getContext();
this.mCarImageView = (ImageView) rootView.findViewById(R.id.details_car_image_view);
this.mManufacturerTextView = (TextView) rootView.findViewById(R.id.details_car_manufacturer_text_view);
this.mModelTextView = (TextView) rootView.findViewById(R.id.details_car_model_text_view);
this.mBodyTypeTextView = (TextView) rootView.findViewById(R.id.details_car_body_type_text_view);
}
// FIXME: 8/8/17 добавать заглушку в пикассо
public void showCar(Car car) {
if (car != null) {
String bodyType, model, manufacturer;
bodyType = mContext.getString(R.string.car_body_type, car.getBodyType());
model = mContext.getString(R.string.car_model, car.getModel());
manufacturer = mContext.getString(R.string.car_manufacturer, car.getManufacturer());
mBodyTypeTextView.setText(bodyType);
mModelTextView.setText(model);
mManufacturerTextView.setText(manufacturer);
Picasso.with(mContext)
.load(Repository.getCarPhoto())
.into(mCarImageView);
}
}
public void updateCar(Car car) {// FIXME: 8/9/17 add edit views
if (car != null) {
String bodyType, model, manufacturer;
bodyType = mContext.getString(R.string.car_body_type, car.getBodyType());
model = mContext.getString(R.string.car_model, car.getModel());
manufacturer = mContext.getString(R.string.car_manufacturer, car.getManufacturer());
mBodyTypeTextView.setText(bodyType);
mModelTextView.setText(model);
mManufacturerTextView.setText(manufacturer);
Picasso.with(mContext)
.load(Repository.getCarPhoto())
.into(mCarImageView);
}
}
public void createCar() {
}
}<file_sep>/app/src/main/java/com/vsevolod/megakittest/adapter/CarAdapter.java
/*
* Copyright (c) 2017.
* <NAME>
* <EMAIL>
*/
package com.vsevolod.megakittest.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
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.squareup.picasso.Picasso;
import com.vsevolod.megakittest.R;
import com.vsevolod.megakittest.Repository;
import com.vsevolod.megakittest.activity.CarActivity;
import com.vsevolod.megakittest.constant.IntentKey;
import com.vsevolod.megakittest.model.Car;
import java.util.List;
/**
* Created by <NAME> on 8/8/17.
* <EMAIL>
*/
public class CarAdapter extends RecyclerView.Adapter<CarAdapter.CarHolder> {
private final String TAG = this.getClass().getSimpleName();
private Context mContext;
private List<Car> mData;
public CarAdapter(Context context, @NonNull List<Car> data) {
Log.d(TAG, "MyRecyclerAdapter: constructor");
this.mContext = context;
this.mData = data;
}
@Override
public CarHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder");
View view = LayoutInflater.from(parent.getContext()).
inflate(R.layout.recycler_view_item_car, parent, false);
return new CarHolder(view);
}
@Override
public void onBindViewHolder(CarHolder holder, int position) {
Log.d(TAG, "onBindViewHolder");
Car car = mData.get(position);
String bodyType, model, manufacturer;
bodyType = mContext.getString(R.string.car_body_type, car.getBodyType());
model = mContext.getString(R.string.car_model, car.getModel());
manufacturer = mContext.getString(R.string.car_manufacturer, car.getManufacturer());
holder.mBodyTypeTextView.setText(bodyType);
holder.mModelTextView.setText(model);
holder.mManufacturerTextView.setText(manufacturer);
Picasso.with(mContext)
.load(Repository.getCarPhoto())
.into(holder.mCarImageView);
}
@Override
public int getItemCount() {
return mData.size();
}
class CarHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mCarImageView;
private TextView mModelTextView;
private TextView mManufacturerTextView;
private TextView mBodyTypeTextView;
private CardView mCarCardView;
private CarHolder(View itemView) {
super(itemView);
mModelTextView = (TextView) itemView.findViewById(R.id.main_car_model_text_view);
mManufacturerTextView = (TextView) itemView.findViewById(R.id.main_car_manufacturer_text_view);
mBodyTypeTextView = (TextView) itemView.findViewById(R.id.main_car_body_type_text_view);
mCarImageView = (ImageView) itemView.findViewById(R.id.main_car_image_view);
mCarCardView = (CardView) itemView.findViewById(R.id.car_card_view);
mCarCardView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CarActivity.class);
long id = mData.get(getAdapterPosition()).getId();
intent.putExtra(IntentKey.ACTION, IntentKey.READ);
intent.putExtra(IntentKey.ID, id);
mContext.startActivity(intent);
}
}
}<file_sep>/app/src/main/java/com/vsevolod/megakittest/provider/DriverProvider.java
/*
* Copyright (c) 2017.
* <NAME>
* <EMAIL>
*/
package com.vsevolod.megakittest.provider;
import android.os.AsyncTask;
import com.vsevolod.megakittest.Repository;
import com.vsevolod.megakittest.model.Driver;
import java.util.List;
/**
* Created by <NAME> on 8/8/17.
* <EMAIL>
*/
public class DriverProvider {
public void getDriver(Callback callback, long id) {
new LoadDriverTask(callback, id).execute();
}
class LoadDriverTask extends AsyncTask<Void, Void, Driver> {
private Callback callback;
private long id;
public LoadDriverTask(Callback callback, long id) {
this.callback = callback;
this.id = id;
}
@Override
protected Driver doInBackground(Void... params) {
List<Driver> drivers = Repository.getDrivers();
for (Driver driver : drivers) {
if (driver.getId() == id) {
return driver;
}
}
return null;
}
@Override
protected void onPostExecute(Driver driver) {
super.onPostExecute(driver);
callback.onDriverLoaded(driver);
}
}
public interface Callback {
void onDriverLoaded(Driver driver);
}
}<file_sep>/app/src/main/java/com/vsevolod/megakittest/view/MyRecyclerView.java
/*
* Copyright (c) 2017.
* <NAME>
* <EMAIL>
*/
package com.vsevolod.megakittest.view;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.vsevolod.megakittest.R;
import com.vsevolod.megakittest.application.MyApplication;
/**
* Created by <NAME> on 8/9/17.
* <EMAIL>
*/
public class MyRecyclerView {
private RecyclerView mRecyclerView;
public MyRecyclerView(View rootView) {
this.mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
}
public void showRecyclerView(RecyclerView.Adapter adapter) {
mRecyclerView.setLayoutManager(new LinearLayoutManager(MyApplication.getContext()));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(adapter);
}
}<file_sep>/app/src/main/java/com/vsevolod/megakittest/constant/IntentKey.java
/*
* Copyright (c) 2017.
* <NAME>
* <EMAIL>
*/
package com.vsevolod.megakittest.constant;
/**
* Created by <NAME> on 8/9/17.
* <EMAIL>
*/
public class IntentKey {
public static final String ID = "id";
public static final String DATA_TYPE = "data type";
public static final String ACTION = "action";
public static final String CREATE = "create new data";
public static final String UPDATE = "edit existing data";
public static final String READ = "read existing data";
} | f9aeda760516c2559343e580f5e30e1bce0af6ec | [
"Java"
]
| 7 | Java | Usevalad/MegaKitTest | b604dfe025e91843bbc8ed6ac86389efb117de07 | a4dc98815c14556f3ea75618a5b84b79026a9afb |
refs/heads/master | <file_sep>import {createBottomTabNavigator} from 'react-navigation-tabs';
import Home from '../screens/Tabs/Home';
import Search from '../screens/Tabs/Search';
import Notification from '../screens/Tabs/Notification';
import Profile from '../screens/Tabs/Profile';
import {View} from 'react-native';
import { createStackNavigator } from 'react-navigation-stack';
import React from 'react';
import MessagesLink from '../components/MessagesLink';
import NavIcon from '../components/NavIcon';
import {Platform} from 'react-native';
import { stackStyles } from './config';
import Detail from '../screens/Detail';
import styles from '../styles';
import UserDetail from '../screens/UserDetail';
const stackFactory = (initialRoute,customConfig)=>
createStackNavigator({
initialRoute:{
screen:initialRoute,
navigationOptions:{
...customConfig
}
},
Detail:{
screen:Detail,
navigationOptions:{
//뒤로가기 버튼 색깔
title:"Photo"
}
},
UserDetail:{
screen: UserDetail,
navigationOptions:({navigation}) => ({
title: navigation.getParam("username")
})
}
},{
defaultNavigationOptions:{
headerBackTitle: null,
headerTintColor: styles.blackColor,
headerStyle:{...stackStyles}
}
}
);
export default createBottomTabNavigator(
{
Home:{
screen: stackFactory(Home,{
headerRight : () => <MessagesLink />,
headerTitle:(
<NavIcon
name="logo-instagram"
size={36}
/>
)
}),
navigationOptions:{
tabBarIcon:({focused}) => (
<NavIcon
focused={focused}
name={Platform.OS ==="ios" ? "ios-home": "md-home"}
/>
)
}
},
Search:{
screen:stackFactory(Search,{
headerBackTitle : null
}),
navigationOptions:{
tabBarIcon:({focused}) =>(
<NavIcon
focused={focused}
name={Platform.OS === "ios" ? "ios-search" : "md-search"}
/>
)
}
},
Add:{
screen:View,
navigationOptions:{
tabBarOnPress:({navigation})=>
navigation.navigate("PhotoNavigation"),
tabBarIcon:({focused}) =>(
<NavIcon
focused={focused}
name={Platform.OS ==="ios"? "ios-add":"md_add"}
size={32}
/>
)
}
},
Notification:{
screen: stackFactory(Notification,{
title:"Notifications"
}),
navigationOptions:{
tabBarIcon:({focused}) => (
<NavIcon
focused={focused}
name={Platform.OS === "ios"
? focused
? "ios-heart"
: "ios-heart-empty"
:focused
? "md-heart"
:"md-heart-empty"
}
/>
)
}
},
Profile:{
screen:stackFactory(Profile,{
title:"Profile"
}),
navigationOptions:{
tabBarIcon:({focused}) => (
<NavIcon
focused={focused}
name={Platform.OS==="ios"?"ios-person":"md-person"}
/>
)
}
}
},
{
initialRouteName:"Profile",
tabBarOptions:{
showLabel:false,
style:{
backgroundColor:"#FAFAFA"
}
}
}
);
<file_sep>export const stackStyles ={
backgroundColor:"#FAFAFA"
};<file_sep>import React from 'react';
import { Ionicons } from '@expo/vector-icons';
import PropTypes from 'prop-types';
import styles from '../styles';
const NavIcon = ({
focused=true ,
name,
color=styles.blackColor,
size=30
}) => (
<Ionicons
name={name}
color={focused?color:styles.darkGreyColor}
size={size}
/>
);
NavIcon.propTypes = {
name:PropTypes.string.isRequired,
color:PropTypes.string,
size:PropTypes.number,
focused:PropTypes.bool
};
export default NavIcon;
<file_sep>import React, { useState } from "react";
import styled from "styled-components";
import {Image, ActivityIndicator, Alert} from 'react-native';
import useInput from '../../hooks/useInput';
import styles from '../../styles';
import constants from '../../constants';
import axios from 'axios';
const View = styled.View`
flex: 1;
`;
const Text = styled.Text`
color:white;
font-weight: 600;
`;
const Container = styled.View`
padding:20px;
flex-direction: row;
`;
const Form = styled.View`
justify-content: flex-start;
`;
const STextInput = styled.TextInput`
margin-bottom:10px;
border: 0px solid ${styles.lightGreyColor};
border-bottom-width:1px;
padding-bottom:10px;
width: ${constants.width -180};
`;
const Button = styled.TouchableOpacity`
background-color: ${props => props.theme.blueColor};
padding: 10px;
border-radius:4px;
align-items:center;
justify-content:center;
`;
export default ({ navigation }) => {
const [loading,setIsLoading] = useState(false);
const [fileUrl, setFileUrl] = useState("");
const photo = navigation.getParam("photo");
const captionInput = useInput("dsfsd");
const locationInput = useInput("dfdfdf");
const handleSubmit = async() => {
if(captionInput.value ==="" || locationInput.value === ""){
Alert.alert("All fields are required");
}
const formData = new FormData();
const name = photo.filename;
const [,type] = name.split(".");
formData.append("file",{
name,
type: type.toLowerCase(),
uri:photo.uri
});
try{
const {
data:{location}
} = await axios.post("http://localhost:4000/api/upload", formData,{
headers: {
"content-type": "multipart/form-data"
}
});
setFileUrl(location);
}catch(e){
console.log(e)
Alert.alert("Can't upload", "Try later");
};
}
return (
<View>
<Container>
<Image
source={{uri:photo.uri}}
style={{height:80, width:80, marginRight:30}}
/>
<Form>
<STextInput
onChangeText={captionInput.onChange}
value={captionInput.value}
placeholder="Caption"
multiline={true}
placeholderTextColor={styles.darkGreyColor}
/>
<STextInput
onChangeText={locationInput.onChange}
value={locationInput.value}
placeholder="Location"
multiline={true}
placeholderTextColor={styles.darkGreyColor}
/>
<Button onPress={handleSubmit}>
{loading ? (
<ActivityIndicator color="white" />
):(
<Text>Upload</Text>
)}
</Button>
</Form>
</Container>
</View>
);
};<file_sep>import {createMaterialTopTabNavigator} from 'react-navigation-tabs';
import SelectPhoto from '../screens/Photo/SelectPhoto';
import TakePhoto from '../screens/Photo/TakePhoto';
import UploadPhoto from '../screens/Photo/UploadPhoto';
import { createStackNavigator } from 'react-navigation-stack';
import { stackStyles } from './config';
import styles from '../styles';
const PhotoTabs = createMaterialTopTabNavigator(
{
Select:{
screen:SelectPhoto,
navigationOptions:{
tabBarLabel: "Select"
}
},
Take:{
screen:TakePhoto,
navigationOptions:{
tabBarLabel: "Take"
}
}
},{
tabBarPosition:"bottom",
tabBarOptions:{
indicatorStyle:{
backgroundColor:styles.blackColor,
marginBottom: 20
},
labelStyle:{
color:styles.blackColor,
fontWeight: "600"
},
style:{
paddingBottom: 20,
...stackStyles
}
}
}
);
export default createStackNavigator({
Tabs:{
screen:PhotoTabs,
navigationOptions:{
title: "Choose Photo",
headerBackTitle:null
}
},
Upload:{
screen: UploadPhoto,
navigationOptions:{
title:"Upload"
}
}
},
{
defaultNavigationOptions:{
headerStyles:{
...stackStyles
},
headerTintColor: styles.blackColor
}
}
);
<file_sep>export default {
blackColor:"#262626",
greyColor:"#FAFAFA",
darkGreyColor:"#999",
lightGreyColor:"rgb(230, 230, 230)",
redColor:"#ED4956",
blueColor:"#3897f0",
darkBlueColor:"#003569"
}<file_sep>const options = {
uri:"http://localhost:4000"
}
export default options | 4b2e5c89e37242b35bd49a749e093f8994613d95 | [
"JavaScript"
]
| 7 | JavaScript | kingjaejun/jungram-app | a0b31806f8838323a5989970576c4830761f075a | 871153f8722cd7b39f18512be975045d88d74161 |
refs/heads/master | <file_sep>/********************************************************************************
** Form generated from reading UI file 'mailclient.ui'
**
** Created by: Qt User Interface Compiler version 5.5.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAILCLIENT_H
#define UI_MAILCLIENT_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MailClient
{
public:
QWidget *centralWidget;
QTabWidget *tabWidget;
QWidget *tab;
QWidget *verticalLayoutWidget;
QVBoxLayout *verticalLayout;
QLabel *label;
QTextEdit *textEdit;
QGridLayout *gridLayout;
QVBoxLayout *verticalLayout_3;
QComboBox *comboBox;
QPushButton *pushButton_2;
QTextEdit *textEdit_inbox;
QSpacerItem *verticalSpacer;
QTextEdit *textEdit_sent;
QLabel *label_2;
QLabel *label_3;
QVBoxLayout *verticalLayout_4;
QComboBox *comboBox_2;
QPushButton *pushButton_3;
QPushButton *pushButton;
QWidget *tab_2;
QWidget *gridLayoutWidget_2;
QGridLayout *gridLayout_2;
QLineEdit *lineEdit_topic;
QTextEdit *textEdit_text;
QLabel *label_4;
QPushButton *pushButton_4;
QLabel *label_5;
QLineEdit *lineEdit_user;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MailClient)
{
if (MailClient->objectName().isEmpty())
MailClient->setObjectName(QStringLiteral("MailClient"));
MailClient->resize(516, 660);
centralWidget = new QWidget(MailClient);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
tabWidget = new QTabWidget(centralWidget);
tabWidget->setObjectName(QStringLiteral("tabWidget"));
tabWidget->setGeometry(QRect(0, 0, 511, 591));
tab = new QWidget();
tab->setObjectName(QStringLiteral("tab"));
verticalLayoutWidget = new QWidget(tab);
verticalLayoutWidget->setObjectName(QStringLiteral("verticalLayoutWidget"));
verticalLayoutWidget->setGeometry(QRect(10, 0, 491, 541));
verticalLayout = new QVBoxLayout(verticalLayoutWidget);
verticalLayout->setSpacing(6);
verticalLayout->setContentsMargins(11, 11, 11, 11);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
label = new QLabel(verticalLayoutWidget);
label->setObjectName(QStringLiteral("label"));
verticalLayout->addWidget(label);
textEdit = new QTextEdit(verticalLayoutWidget);
textEdit->setObjectName(QStringLiteral("textEdit"));
verticalLayout->addWidget(textEdit);
gridLayout = new QGridLayout();
gridLayout->setSpacing(6);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
verticalLayout_3 = new QVBoxLayout();
verticalLayout_3->setSpacing(6);
verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3"));
comboBox = new QComboBox(verticalLayoutWidget);
comboBox->setObjectName(QStringLiteral("comboBox"));
verticalLayout_3->addWidget(comboBox);
pushButton_2 = new QPushButton(verticalLayoutWidget);
pushButton_2->setObjectName(QStringLiteral("pushButton_2"));
verticalLayout_3->addWidget(pushButton_2);
gridLayout->addLayout(verticalLayout_3, 2, 1, 1, 1);
textEdit_inbox = new QTextEdit(verticalLayoutWidget);
textEdit_inbox->setObjectName(QStringLiteral("textEdit_inbox"));
gridLayout->addWidget(textEdit_inbox, 4, 0, 1, 1);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout->addItem(verticalSpacer, 0, 0, 1, 1);
textEdit_sent = new QTextEdit(verticalLayoutWidget);
textEdit_sent->setObjectName(QStringLiteral("textEdit_sent"));
gridLayout->addWidget(textEdit_sent, 2, 0, 1, 1);
label_2 = new QLabel(verticalLayoutWidget);
label_2->setObjectName(QStringLiteral("label_2"));
gridLayout->addWidget(label_2, 1, 0, 1, 1);
label_3 = new QLabel(verticalLayoutWidget);
label_3->setObjectName(QStringLiteral("label_3"));
gridLayout->addWidget(label_3, 3, 0, 1, 1);
verticalLayout_4 = new QVBoxLayout();
verticalLayout_4->setSpacing(6);
verticalLayout_4->setObjectName(QStringLiteral("verticalLayout_4"));
comboBox_2 = new QComboBox(verticalLayoutWidget);
comboBox_2->setObjectName(QStringLiteral("comboBox_2"));
verticalLayout_4->addWidget(comboBox_2);
pushButton_3 = new QPushButton(verticalLayoutWidget);
pushButton_3->setObjectName(QStringLiteral("pushButton_3"));
verticalLayout_4->addWidget(pushButton_3);
gridLayout->addLayout(verticalLayout_4, 4, 1, 1, 1);
verticalLayout->addLayout(gridLayout);
pushButton = new QPushButton(verticalLayoutWidget);
pushButton->setObjectName(QStringLiteral("pushButton"));
verticalLayout->addWidget(pushButton);
tabWidget->addTab(tab, QString());
tab_2 = new QWidget();
tab_2->setObjectName(QStringLiteral("tab_2"));
gridLayoutWidget_2 = new QWidget(tab_2);
gridLayoutWidget_2->setObjectName(QStringLiteral("gridLayoutWidget_2"));
gridLayoutWidget_2->setGeometry(QRect(10, 10, 331, 301));
gridLayout_2 = new QGridLayout(gridLayoutWidget_2);
gridLayout_2->setSpacing(6);
gridLayout_2->setContentsMargins(11, 11, 11, 11);
gridLayout_2->setObjectName(QStringLiteral("gridLayout_2"));
gridLayout_2->setContentsMargins(0, 0, 0, 0);
lineEdit_topic = new QLineEdit(gridLayoutWidget_2);
lineEdit_topic->setObjectName(QStringLiteral("lineEdit_topic"));
gridLayout_2->addWidget(lineEdit_topic, 0, 1, 1, 1);
textEdit_text = new QTextEdit(gridLayoutWidget_2);
textEdit_text->setObjectName(QStringLiteral("textEdit_text"));
gridLayout_2->addWidget(textEdit_text, 2, 0, 1, 2);
label_4 = new QLabel(gridLayoutWidget_2);
label_4->setObjectName(QStringLiteral("label_4"));
gridLayout_2->addWidget(label_4, 0, 0, 1, 1);
pushButton_4 = new QPushButton(gridLayoutWidget_2);
pushButton_4->setObjectName(QStringLiteral("pushButton_4"));
gridLayout_2->addWidget(pushButton_4, 3, 0, 1, 1);
label_5 = new QLabel(gridLayoutWidget_2);
label_5->setObjectName(QStringLiteral("label_5"));
gridLayout_2->addWidget(label_5, 1, 0, 1, 1);
lineEdit_user = new QLineEdit(gridLayoutWidget_2);
lineEdit_user->setObjectName(QStringLiteral("lineEdit_user"));
gridLayout_2->addWidget(lineEdit_user, 1, 1, 1, 1);
tabWidget->addTab(tab_2, QString());
MailClient->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MailClient);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 516, 27));
MailClient->setMenuBar(menuBar);
mainToolBar = new QToolBar(MailClient);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
MailClient->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MailClient);
statusBar->setObjectName(QStringLiteral("statusBar"));
MailClient->setStatusBar(statusBar);
retranslateUi(MailClient);
tabWidget->setCurrentIndex(0);
QMetaObject::connectSlotsByName(MailClient);
} // setupUi
void retranslateUi(QMainWindow *MailClient)
{
MailClient->setWindowTitle(QApplication::translate("MailClient", "MailClient", 0));
label->setText(QApplication::translate("MailClient", "Client", 0));
pushButton_2->setText(QApplication::translate("MailClient", "Go back", 0));
label_2->setText(QApplication::translate("MailClient", "sent", 0));
label_3->setText(QApplication::translate("MailClient", "inbox", 0));
pushButton_3->setText(QApplication::translate("MailClient", "Go back", 0));
pushButton->setText(QApplication::translate("MailClient", "Update", 0));
tabWidget->setTabText(tabWidget->indexOf(tab), QApplication::translate("MailClient", "Tab 1", 0));
label_4->setText(QApplication::translate("MailClient", "Topic", 0));
pushButton_4->setText(QApplication::translate("MailClient", "Send", 0));
label_5->setText(QApplication::translate("MailClient", "Recipient", 0));
tabWidget->setTabText(tabWidget->indexOf(tab_2), QApplication::translate("MailClient", "Tab 2", 0));
} // retranslateUi
};
namespace Ui {
class MailClient: public Ui_MailClient {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAILCLIENT_H
<file_sep>#include "mailclient.h"
#include "ui_mailclient.h"
MailClient::MailClient(const QString &strHost, int nPort, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MailClient),
m_nNextBlockSize(0)
{
m_pTcpSocket = new QTcpSocket(this);
ui->setupUi(this);
m_pTcpSocket->connectToHost(strHost, nPort);
connect(m_pTcpSocket, SIGNAL(connected()), SLOT(slotConnected()));
connect(m_pTcpSocket, SIGNAL(readyRead()), SLOT(slotReadyRead()));
connect(m_pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError)));
ui->textEdit->setReadOnly(true);
ui->textEdit_inbox->setReadOnly(true);
ui->textEdit_sent->setReadOnly(true);
//connect(ui->pushButton, SIGNAL(clicked()), SLOT(slotSendToServer()));
//connect(ui->lineEdit, SIGNAL(returnPressed()), this, SLOT(slotSendToServer()));
}
void MailClient::slotReadyRead()
{
QDataStream in(m_pTcpSocket);
in.setVersion(QDataStream::Qt_4_5);
for (;;) {
if (!m_nNextBlockSize) {
if (m_pTcpSocket->bytesAvailable() < sizeof(quint16)) {
break;
}
in >> m_nNextBlockSize;
}
if (m_pTcpSocket->bytesAvailable() < m_nNextBlockSize)
break;
QTime time;
QString str;
in >> time >> str;
//qDebug() << str;
str = parssingMessage(str);
ui->textEdit->append(time.toString() + " " + str);
m_nNextBlockSize = 0;
}
}
void MailClient::slotError(QAbstractSocket::SocketError err)
{
QString strError =
"Error: " + (err == QAbstractSocket::HostNotFoundError ?
"The host was not found." :
err == QAbstractSocket::RemoteHostClosedError ?
"The remote host is closed." :
err == QAbstractSocket::ConnectionRefusedError ?
"The connection was refused." :
QString(m_pTcpSocket->errorString())
);
ui->textEdit->append(strError);
}
void MailClient::SendToServer(QString str)
{
QByteArray arrBlock;
QDataStream out(&arrBlock, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_5);
out << quint16(0) << QTime::currentTime() << str;
out.device()->seek(0);
out << quint16(arrBlock.size() - sizeof(quint16));
m_pTcpSocket->write(arrBlock);
}
void MailClient::slotConnected()
{
ui->textEdit->append("Received the connected() signal");
}
QString MailClient::parssingMessage(QString str)
{
QStringList blocks;
blocks = str.split("%D");
if (blocks.at(0) == "u"){
if (blocks.at(1) != "Register User Ok!"){
bool bOk;
while(1){
username = QInputDialog::getText(0, "Connection to server", "Username:", QLineEdit::Normal, "user", &bOk);
if (bOk)
break;
}
SendToServer("u%D" + username);
}
else
return username + "connected!";
}
else if (blocks.at(0) == "i"){
if (blocks.at(1) == "Inbox"){
ui->comboBox_2->clear();
ui->textEdit_inbox->setText("");
for (int i = 4; i < blocks.size(); ++i){
ui->textEdit_inbox->append(blocks.at(i));
ui->comboBox_2->addItem(blocks.at(i));
}
return "Mail \"Sent\" updated!";
}
else if (blocks.at(1) == "Sent"){
ui->comboBox->clear();
ui->textEdit_sent->setText("");
for (int i = 4; i < blocks.size(); ++i){
ui->textEdit_sent->append(blocks.at(i));
ui->comboBox->addItem(blocks.at(i));
}
return "Mail \"Inbox\" updated!";
}
}
else if (blocks.at(0) == "s"){
QMessageBox* pmbx =
new QMessageBox(QMessageBox::Information, "MessageFromServer",
blocks.at(1),
QMessageBox::Ok);
int n = pmbx->exec();
delete pmbx;
if (n == QMessageBox::Ok) {
ui->lineEdit_topic->clear();
ui->textEdit_text->clear();
}
return blocks.at(1);
}
else if (blocks.at(0) == "r"){
if (blocks.at(1) == "sent"){
ui->textEdit_sent->clear();
for (int i = 2; i < blocks.size(); ++i)
ui->textEdit_sent->append(blocks.at(i));
return "get Message";
}
if (blocks.at(1) == "inbox"){
ui->textEdit_inbox->clear();
for (int i = 2; i < blocks.size(); ++i)
ui->textEdit_inbox->append(blocks.at(i));
return "get Message";
}
}
return str.remove(0,3).replace("%D", ",");
}
MailClient::~MailClient()
{
delete ui;
}
void MailClient::on_pushButton_clicked()
{
SendToServer("i%D" + username);
}
void MailClient::on_pushButton_4_clicked()
{
SendToServer("s%D" + username + "%D"+ ui->lineEdit_user->text() + "%D" + ui->lineEdit_topic->text() + "%D" + ui->textEdit_text->toPlainText());
}
void MailClient::on_comboBox_activated(const QString &arg1)
{
SendToServer("r%D" + username + "%D"+ "sent" + "%D" + arg1);
}
void MailClient::on_pushButton_2_clicked()
{
SendToServer("i%D" + username);
}
void MailClient::on_comboBox_2_activated(const QString &arg1)
{
SendToServer("r%D" + username + "%D"+ "inbox" + "%D" + arg1);
}
void MailClient::on_pushButton_3_clicked()
{
SendToServer("i%D" + username);
}
<file_sep>#include "mailserver.h"
#include "ui_mailserver.h"
MailServer::MailServer(QString host, int nPort ,QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MailServer),
m_nNextBlockSize(0)
{
m_ptcpServer = new QTcpServer(this);
if (!m_ptcpServer->listen(QHostAddress::Any, nPort)) {
QMessageBox::critical(0,
"Server Error",
"Unable to start the server:"
+ m_ptcpServer->errorString()
);
m_ptcpServer->close();
return;
}
connect(m_ptcpServer, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
ui->setupUi(this);
}
void MailServer::slotNewConnection()
{
QTcpSocket* pClientSocket = m_ptcpServer->nextPendingConnection();
connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater()));
connect(pClientSocket, SIGNAL(readyRead()), this, SLOT(slotReadClient()));
sendToClient(pClientSocket, "u%DConnected!");
}
void MailServer::slotReadClient()
{
QTcpSocket* pClientSocket = (QTcpSocket*)sender();
QDataStream in(pClientSocket);
in.setVersion(QDataStream::Qt_4_5);
for (;;) {
if (!m_nNextBlockSize) {
if (pClientSocket->bytesAvailable() < sizeof(quint16)) {
break;
}
in >> m_nNextBlockSize;
}
if (pClientSocket->bytesAvailable() < m_nNextBlockSize)
break;
QTime time;
QString str;
in >> time >> str;
QString strMessage = time.toString() + " " + "Client has sent — " + str;
strMessage = parssingMessage(pClientSocket, str);
ui->textEdit->append(strMessage);
m_nNextBlockSize = 0;
//sendToClient(pClientSocket, "Server Response: Received \"" + str + "\"");
}
}
bool MailServer::checUsername(QString name){
logins.setFileName("../login_pass.lp");
if (logins.open(QFile::ReadOnly | QFile::Text)){
QTextStream in(&logins);
QString line;
while (!in.atEnd()){
line = in.readLine();
if (line == name){
logins.close();
return true;
}
}
}
logins.close();
return false;
}
QString MailServer::parssingMessage(QTcpSocket* pSocket, QString str){
QStringList blocks;
blocks = str.split("%D");
qDebug() << blocks.at(0);
if (blocks.at(0) == "u"){
if (!checUsername(blocks.at(1))){
sendToClient(pSocket, "u%DUsername incorrect!");
return "User: " + blocks.at(1) + " Connection error. Bad username";
}
else
sendToClient(pSocket, "u%DRegister User Ok!");
return "User: " + blocks.at(1) + " Connected!";
}
else if (blocks.at(0) == "s"){
if (!checUsername(blocks.at(2))){
sendToClient(pSocket,"s%D" + blocks.at(2) + " Bad username recipient");
return blocks.at(2) + " Bad username recipient";
}
else{
QDateTime CurrentTime;
CurrentTime = QDateTime::currentDateTime();
QFile mail("clients/" + blocks.at(1) + "/sent/" + blocks.at(2) + CurrentTime.toString("<ddMMyyyy>[hh:mm:ss]"));
if (mail.open(QFile::ReadWrite | QFile::Text))
{
QTextStream in(&mail);
in << "Topic: " << blocks.at(3) << "\n\n";
in << blocks.at(4);
}
mail.close();
QFile mail1("clients/" + blocks.at(2) + "/inbox/" + blocks.at(1) + CurrentTime.toString("<ddMMyyyy>[hh:mm:ss]"));
if (mail1.open(QFile::ReadWrite | QFile::Text))
{
QTextStream in(&mail1);
in << "Topic: " << blocks.at(3) << "\n\n";
in << blocks.at(4);
}
mail1.close();
sendToClient(pSocket,"s%D" + blocks.at(2) + ": has received a letter!");
return "the user: " + blocks.at(1) + " sent mail " + blocks.at(2);
}
}
else if (blocks.at(0) == "r"){
QFile mail("clients/" + blocks.at(1) + "/" + blocks.at(2) + "/" + blocks.at(3));
if (mail.open(QFile::ReadOnly | QFile::Text))
{
QString text;
QTextStream in(&mail);
QString line;
line = in.readLine();
text = line + "%D";
while (!in.atEnd()){
line = in.readLine();
text += line + '\n';
}
sendToClient(pSocket,"r%D" + blocks.at(2) + "%D" + blocks.at(3) + "%D" + text);
return "The user: " + blocks.at(1) + " views: " + blocks.at(3);
}
else
sendToClient(pSocket,"r%D" + blocks.at(2) + "%D" + blocks.at(3) + "%D" + " Error mail name");
return "The user: " + blocks.at(1) + " Error mail name";
}
else if (blocks.at(0) == "i"){
QDir dirInbox("clients/" + blocks.at(1) + "/inbox");
QStringList inbox = dirInbox.entryList(QStringList("*"));
sendToClient(pSocket,"i%DInbox%D" + inbox.join("%D"));
QDir dirSent("clients/" + blocks.at(1) + "/sent");
QStringList sent = dirSent.entryList(QStringList("*"));
sendToClient(pSocket,"i%DSent%D" + sent.join("%D"));
//ui->textEdit->append((QString)sent.join("\n"));
return "the user: " + blocks.at(1) + " received information";
}
return str.replace("%D",",");
}
void MailServer::sendToClient(QTcpSocket* pSocket, const QString& str)
{
QByteArray arrBlock;
QDataStream out(&arrBlock, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_5);
out << quint16(0) << QTime::currentTime() << str;
out.device()->seek(0);
out << quint16(arrBlock.size() - sizeof(quint16));
pSocket->write(arrBlock);
qDebug() << arrBlock.toHex();
}
MailServer::~MailServer()
{
delete ui;
}
<file_sep>#ifndef MAILSERVER_H
#define MAILSERVER_H
#include <QApplication>
#include <QMainWindow>
//#include <QWidget>
#include <QMessageBox>
#include <QTextEdit>
#include <QLabel>
#include <QTime>
#include <QFile>
#include <QVBoxLayout>
#include <QBoxLayout>
#include <QtNetwork/QtNetwork>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QTcpServer>
class QTcpServer;
class QTextEdit;
class QTcpSocket;
namespace Ui {
class MailServer;
}
class MailServer : public QMainWindow
{
Q_OBJECT
private:
QTcpServer* m_ptcpServer;
QTextEdit* m_ptxt;
quint16 m_nNextBlockSize;
Ui::MailServer *ui;
bool checUsername(QString name);
QString parssingMessage(QTcpSocket* pSocket, QString str);
QFile logins;
private:
void sendToClient(QTcpSocket* pSocket, const QString& str);
public slots:
virtual void slotNewConnection();
void slotReadClient();
public:
explicit MailServer(QString host, int nPort, QWidget *parent = 0);
~MailServer();
};
#endif // MAILSERVER_H
<file_sep>/********************************************************************************
** Form generated from reading UI file 'mailserver.ui'
**
** Created by: Qt User Interface Compiler version 5.5.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAILSERVER_H
#define UI_MAILSERVER_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MailServer
{
public:
QWidget *centralWidget;
QWidget *verticalLayoutWidget;
QVBoxLayout *verticalLayout;
QLabel *label;
QTextEdit *textEdit;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MailServer)
{
if (MailServer->objectName().isEmpty())
MailServer->setObjectName(QStringLiteral("MailServer"));
MailServer->resize(441, 374);
centralWidget = new QWidget(MailServer);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
verticalLayoutWidget = new QWidget(centralWidget);
verticalLayoutWidget->setObjectName(QStringLiteral("verticalLayoutWidget"));
verticalLayoutWidget->setGeometry(QRect(10, 0, 421, 301));
verticalLayout = new QVBoxLayout(verticalLayoutWidget);
verticalLayout->setSpacing(6);
verticalLayout->setContentsMargins(11, 11, 11, 11);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
label = new QLabel(verticalLayoutWidget);
label->setObjectName(QStringLiteral("label"));
verticalLayout->addWidget(label);
textEdit = new QTextEdit(verticalLayoutWidget);
textEdit->setObjectName(QStringLiteral("textEdit"));
verticalLayout->addWidget(textEdit);
MailServer->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MailServer);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 441, 27));
MailServer->setMenuBar(menuBar);
mainToolBar = new QToolBar(MailServer);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
MailServer->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MailServer);
statusBar->setObjectName(QStringLiteral("statusBar"));
MailServer->setStatusBar(statusBar);
retranslateUi(MailServer);
QMetaObject::connectSlotsByName(MailServer);
} // setupUi
void retranslateUi(QMainWindow *MailServer)
{
MailServer->setWindowTitle(QApplication::translate("MailServer", "MailServer", 0));
label->setText(QApplication::translate("MailServer", "Server", 0));
} // retranslateUi
};
namespace Ui {
class MailServer: public Ui_MailServer {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAILSERVER_H
<file_sep>/****************************************************************************
** Meta object code from reading C++ file 'mailclient.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../MailClient/mailclient.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mailclient.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_MailClient_t {
QByteArrayData data[15];
char stringdata0[244];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MailClient_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MailClient_t qt_meta_stringdata_MailClient = {
{
QT_MOC_LITERAL(0, 0, 10), // "MailClient"
QT_MOC_LITERAL(1, 11, 13), // "slotReadyRead"
QT_MOC_LITERAL(2, 25, 0), // ""
QT_MOC_LITERAL(3, 26, 9), // "slotError"
QT_MOC_LITERAL(4, 36, 28), // "QAbstractSocket::SocketError"
QT_MOC_LITERAL(5, 65, 13), // "slotConnected"
QT_MOC_LITERAL(6, 79, 15), // "parssingMessage"
QT_MOC_LITERAL(7, 95, 3), // "str"
QT_MOC_LITERAL(8, 99, 21), // "on_pushButton_clicked"
QT_MOC_LITERAL(9, 121, 23), // "on_pushButton_4_clicked"
QT_MOC_LITERAL(10, 145, 21), // "on_comboBox_activated"
QT_MOC_LITERAL(11, 167, 4), // "arg1"
QT_MOC_LITERAL(12, 172, 23), // "on_pushButton_2_clicked"
QT_MOC_LITERAL(13, 196, 23), // "on_comboBox_2_activated"
QT_MOC_LITERAL(14, 220, 23) // "on_pushButton_3_clicked"
},
"MailClient\0slotReadyRead\0\0slotError\0"
"QAbstractSocket::SocketError\0slotConnected\0"
"parssingMessage\0str\0on_pushButton_clicked\0"
"on_pushButton_4_clicked\0on_comboBox_activated\0"
"arg1\0on_pushButton_2_clicked\0"
"on_comboBox_2_activated\0on_pushButton_3_clicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MailClient[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
10, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 64, 2, 0x08 /* Private */,
3, 1, 65, 2, 0x08 /* Private */,
5, 0, 68, 2, 0x08 /* Private */,
6, 1, 69, 2, 0x08 /* Private */,
8, 0, 72, 2, 0x08 /* Private */,
9, 0, 73, 2, 0x08 /* Private */,
10, 1, 74, 2, 0x08 /* Private */,
12, 0, 77, 2, 0x08 /* Private */,
13, 1, 78, 2, 0x08 /* Private */,
14, 0, 81, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
QMetaType::Void, 0x80000000 | 4, 2,
QMetaType::Void,
QMetaType::QString, QMetaType::QString, 7,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 11,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 11,
QMetaType::Void,
0 // eod
};
void MailClient::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
MailClient *_t = static_cast<MailClient *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->slotReadyRead(); break;
case 1: _t->slotError((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break;
case 2: _t->slotConnected(); break;
case 3: { QString _r = _t->parssingMessage((*reinterpret_cast< QString(*)>(_a[1])));
if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break;
case 4: _t->on_pushButton_clicked(); break;
case 5: _t->on_pushButton_4_clicked(); break;
case 6: _t->on_comboBox_activated((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 7: _t->on_pushButton_2_clicked(); break;
case 8: _t->on_comboBox_2_activated((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 9: _t->on_pushButton_3_clicked(); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QAbstractSocket::SocketError >(); break;
}
break;
}
}
}
const QMetaObject MailClient::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MailClient.data,
qt_meta_data_MailClient, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *MailClient::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MailClient::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_MailClient.stringdata0))
return static_cast<void*>(const_cast< MailClient*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MailClient::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 10)
qt_static_metacall(this, _c, _id, _a);
_id -= 10;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 10)
qt_static_metacall(this, _c, _id, _a);
_id -= 10;
}
return _id;
}
QT_END_MOC_NAMESPACE
<file_sep>#include "mailclient.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MailClient client("localhost", 2323);
client.show();
return a.exec();
}
<file_sep>#include "mailserver.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MailServer server("localhost", 2323);
server.show();
return a.exec();
}
<file_sep>#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char name[10][10];
char messages[10][200];
int message_counter = 0;
int main()
{
int sock, listener;
struct sockaddr_in addr;
char buf[1024];
int bytes_read;
listener = socket(AF_INET, SOCK_STREAM, 0);
if(listener < 0)
{
perror("socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(6312);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
const int on = 1;
if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) {
perror("setsockopt");
exit(2);
}
if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
exit(3);
}
listen(listener, 1);
while(1)
{
sock = accept(listener, 0,0 );
if(sock < 0)
{
perror("accept");
exit(4);
}
while(1)
{
memset(buf, 0, 1024);
bytes_read = recv(sock, buf, 1024, 0);
if(bytes_read <= 0) break;
printf("%s", buf);
if(buf[0] == 's'){
puts("отправляю сообщение");
strncpy(name[message_counter], buf+1, 10);
strncpy(messages[message_counter], buf+11, 200);
message_counter++;
}
else if(buf[0] == 'r'){
puts("читаем сообщения");
int i;
for(i = 0; i< 10; i++){
if(strncmp(buf+1, name[i], 10) == 0){
printf("Для ", name[i], messages[i]); //????? вывести, кому письмо
send(sock, messages[i], 200, 0);
}
}
}
else if(buf[0] == 'i'){
puts("хотим получить информацию о почтовом ящике");
int i,j;
for(i = 0; i< 10; i++){
for (j = 0; j < 10; j++) {
if(strncmp(buf+1, name[i], 10) == 0){
printf("В вашем почтовом ящике: ", i, " писем" ); //?
printf(j+1 ,"письмо: ", messages[i]);
j++;
send(sock, messages[i], 200, 0);
}
}
}
}
else
puts("команда не распознана");
}
close(sock);
}
return 0;
}
<file_sep>#ifndef MAILCLIENT_H
#define MAILCLIENT_H
#include <QMainWindow>
#include <QDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QLineEdit>
#include <QPushButton>
#include <QTextEdit>
#include <QLabel>
#include <QTime>
#include <QVBoxLayout>
#include <QBoxLayout>
#include <QtNetwork/QtNetwork>
#include <QtNetwork/QTcpSocket>
class QTcpServer;
class QTextEdit;
class QTcpSocket;
namespace Ui {
class MailClient;
}
class MailClient : public QMainWindow
{
Q_OBJECT
public:
explicit MailClient(const QString& strHost, int nPort, QWidget *parent = 0);
~MailClient();
private:
Ui::MailClient *ui;
QTcpSocket* m_pTcpSocket;
QTextEdit* m_ptxtInfo;
QLineEdit* m_ptxtInput;
quint16 m_nNextBlockSize;
QString username;
void SendToServer(QString str);
private slots:
void slotReadyRead();
void slotError(QAbstractSocket::SocketError);
//void slotSendToServer();
void slotConnected();
QString parssingMessage(QString str);
void on_pushButton_clicked();
void on_pushButton_4_clicked();
void on_comboBox_activated(const QString &arg1);
void on_pushButton_2_clicked();
void on_comboBox_2_activated(const QString &arg1);
void on_pushButton_3_clicked();
};
#endif // MAILCLIENT_H
| a1bd511ce12e67374bb4ae920d6a0949088be545 | [
"C",
"C++"
]
| 10 | C++ | valeryrodina/TelecomCourse | 592f623427af6544f03b00f662b162dd7fbee4c3 | bfb2360dd545f7fbb9b18999392f3d9616e220a5 |
refs/heads/main | <repo_name>CmdSoda/thehunted_adn<file_sep>/README.md
# Average Damage Numbers for "The Hunted: The Board Game"
<file_sep>/thehunted/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace thehunted
{
class Program
{
const int cycles = 1000000;
const int CLOSE_RANGE = 1;
const int MEDIUM_RANGE = 2;
const int LONG_RANGE = 3;
const int STEAM = 1;
const int ELECTRIC = 2;
const int GUN = 3;
const int FALKE = 4;
const int ZAUNKOENIG = 5;
const int ZAUNKOENIG2 = 6;
const int FAT = 7;
const int FAT2 = 8;
const int max = 11;
static void print_result(string name, double[] results)
{
//Console.Write(name + " = \t");
for (int n = 0; n < max; n++)
{
double number = Math.Round(results[n] / cycles, 2);
if (number <= 0.05)
Console.Write("-" + "\t");
else
Console.Write(number + "\t");
}
Console.WriteLine("");
}
static void Main(string[] args)
{
double[] steam_close = new double[max];
double[] steam_medium = new double[max];
double[] steam_long = new double[max];
double[] electric_close = new double[max];
double[] electric_medium = new double[max];
double[] electric_long = new double[max];
double[] falke_close = new double[max];
double[] falke_medium = new double[max];
double[] falke_long = new double[max];
double[] zaun_close = new double[max];
double[] zaun_medium = new double[max];
double[] zaun_long = new double[max];
double[] zaun2_close = new double[max];
double[] zaun2_medium = new double[max];
double[] zaun2_long = new double[max];
double[] gun_close = new double[max];
double[] gun_medium = new double[max];
double[] gun_long = new double[max];
Dice.init();
for (double i = 0; i < cycles; i++)
{
for (int n = 0; n < max; n++)
{
steam_close[n] += weapon(n - 2, CLOSE_RANGE, STEAM);
steam_medium[n] += weapon(n - 2, MEDIUM_RANGE, STEAM);
steam_long[n] += weapon(n - 2, LONG_RANGE, STEAM);
electric_close[n] += weapon(n - 2, CLOSE_RANGE, ELECTRIC);
electric_medium[n] += weapon(n - 2, MEDIUM_RANGE, ELECTRIC);
electric_long[n] += weapon(n - 2, LONG_RANGE, ELECTRIC);
falke_close[n] += weapon(n - 2, CLOSE_RANGE, FALKE);
falke_medium[n] += weapon(n - 2, MEDIUM_RANGE, FALKE);
falke_long[n] += weapon(n - 2, LONG_RANGE, FALKE);
zaun_close[n] += weapon(n - 2, CLOSE_RANGE, ZAUNKOENIG);
zaun_medium[n] += weapon(n - 2, MEDIUM_RANGE, ZAUNKOENIG);
zaun_long[n] += weapon(n - 2, LONG_RANGE, ZAUNKOENIG);
zaun2_close[n] += weapon(n - 2, CLOSE_RANGE, ZAUNKOENIG2);
zaun2_medium[n] += weapon(n - 2, MEDIUM_RANGE, ZAUNKOENIG2);
zaun2_long[n] += weapon(n - 2, LONG_RANGE, ZAUNKOENIG2);
gun_close[n] += weapon(n - 2, CLOSE_RANGE, GUN);
gun_medium[n] += weapon(n - 2, MEDIUM_RANGE, GUN);
gun_long[n] += weapon(n - 2, LONG_RANGE, GUN);
}
}
print_result("steam_close", steam_close);
print_result("elec_close", electric_close);
print_result("falke_close", falke_close);
print_result("zaun_close", zaun_close);
print_result("zaun2_close", zaun2_close);
print_result("gun_close", gun_close);
Console.WriteLine();
print_result("steam_medium", steam_medium);
print_result("elec_medium", electric_medium);
print_result("falke_medium", falke_medium);
print_result("zaun_medium", zaun_medium);
print_result("zaun2_medium", zaun2_medium);
print_result("gun_medium", gun_medium);
Console.WriteLine();
print_result("steam_long", steam_long);
print_result("elec_long", electric_long);
print_result("falke_long", falke_long);
print_result("zaun_long", zaun_long);
print_result("zaun2_long", zaun2_long);
print_result("gun_long", gun_long);
}
static int weapon(int modifier, int range, int type)
{
int um = Dice.d6() + Dice.d6(); // unmodified
int n = um;
// U1: Hit Check
if ((type == FALKE && um <= 5) || (type == ZAUNKOENIG && um <= 6) || (type == ZAUNKOENIG2 && um <= 7))
{
}
else
{
n += modifier;
if (type == ELECTRIC && range == MEDIUM_RANGE)
n += 1;
if (type == ELECTRIC && range == LONG_RANGE)
n += 2;
if (range == CLOSE_RANGE && n >= 9)
return 0;
if (range == MEDIUM_RANGE && n >= 8)
return 0;
if (range == LONG_RANGE && n >= 7)
return 0;
}
// U3: Damage Chart
int damage = Dice.d6();
if (type == GUN)
{
damage--;
switch (damage)
{
case 0:
return 2;
case 1:
return 2;
case 2:
return 1;
case 3:
return 1;
case 4:
case 5:
case 6:
return 1;
}
}
else {
// dud check
if (Dice.d6() == 1)
return 0;
switch (damage)
{
case 0:
return 0;
case 1:
return 4;
case 2:
return 3;
case 3:
return 2;
case 4:
case 5:
case 6:
return 1;
}
}
return 0;
}
}
}
<file_sep>/thehunted/Dice.cs
using System;
using System.Diagnostics;
namespace thehunted
{
public class Dice
{
private static Random r;
public static void init()
{
r = new Random((int)DateTime.Now.Ticks);
}
public static int d6()
{
int value = r.Next(1, 7);
Debug.Assert(value >= 1 && value <= 6);
return value;
}
}
}
| ce415adef4684430b3665534384a82ccdb6cc120 | [
"Markdown",
"C#"
]
| 3 | Markdown | CmdSoda/thehunted_adn | 0234866f60bdee5b1a5fb77e75d1cc672fb5a4f1 | ccabbf616007ec063ad79148956b97e3cb61d467 |
refs/heads/master | <repo_name>Vipin77/Java-Solution-NearBySystem<file_sep>/nearbySystem/nearbySystem-dal/src/main/java/org/nearby/dto/Registration.java
package org.nearby.dto;
import java.security.Timestamp;
public class Registration {
private String firstName;
private String lastName;
private String mobileNumber;
private String password;
private String email;
private String address;
private Integer isdeleted;
private Integer isactive;
private Timestamp createdDate;
private Timestamp updatedDate;
private String type;
private Integer categoryId;
private String subCategory;
private String state;
private String city;
private byte[] profile;
private double avgrating;
private String businessName;
private String homeService;
private String latitude;
private String longitude;
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getHomeService() {
return homeService;
}
public void setHomeService(String homeService) {
this.homeService = homeService;
}
public double getAvgrating() {
return avgrating;
}
public void setAvgrating(double avgrating) {
this.avgrating = avgrating;
}
public byte[] getProfile() {
return profile;
}
public void setProfile(byte[] profile) {
this.profile = profile;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getIsdeleted() {
return isdeleted;
}
public void setIsdeleted(Integer isdeleted) {
this.isdeleted = isdeleted;
}
public Integer getIsactive() {
return isactive;
}
public void setIsactive(Integer isactive) {
this.isactive = isactive;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
public Timestamp getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Timestamp updatedDate) {
this.updatedDate = updatedDate;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getCategory() {
return categoryId;
}
public void setCategory(Integer category) {
this.categoryId = category;
}
public String getSubCategory() {
return subCategory;
}
public void setSubCategory(String subCategory) {
this.subCategory = subCategory;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
<file_sep>/nearbySystem/nearbySystem-dal/src/main/java/org/nearby/dao/AddressConverter.java
package org.nearby.dao;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import org.nearby.dto.GoogleResponse;
import org.nearby.dto.Result;
public class AddressConverter {
private static final String URL = "http://maps.googleapis.com/maps/api/geocode/json";
public GoogleResponse convertToLatLong(String fullAddress) throws IOException {
URL url = new URL(URL + "?address=" + URLEncoder.encode(fullAddress, "UTF-8") + "&sensor=false");
// Open the Connection
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
System.out.println(in.available());
/* byte[] b=new byte[in.available()];
in.read(b);
String s=new String(b);
System.out.println(s);
*/
ObjectMapper mapper = new ObjectMapper();
GoogleResponse response = mapper.readValue(in, GoogleResponse.class);
int count=0;
while(!response.getStatus().equals("OK")){
count++;
System.out.println("count = "+count);
conn = url.openConnection();
in = conn.getInputStream();
mapper = new ObjectMapper();
response=null;
response = (GoogleResponse) mapper.readValue(in, GoogleResponse.class);
}
in.close();
return response;
}
public static List<String> getLatorLong(String address) throws IOException
{
List<String> list= new ArrayList<String>();
GoogleResponse res = new AddressConverter().convertToLatLong(address);
if (res.getStatus().equals("OK")) {
for (Result result : res.getResults()) {
System.out.println("Lattitude of address is :" + result.getGeometry().getLocation().getLat());
System.out.println("Longitude of address is :" + result.getGeometry().getLocation().getLng());
System.out.println("Location is " + result.getGeometry().getLocation_type());
list.add(result.getGeometry().getLocation().getLat());
list.add(result.getGeometry().getLocation().getLng());
return list;
}
} else {
list=getLatorLong(address);
}
return list;
}
}<file_sep>/nearbySystem/nearbySystem-nearby/src/main/java/org/nearby/controller/DistanceCalculator.java
package org.nearby.controller;
public class DistanceCalculator {
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506) + " Miles\n");
//first is <NAME>
System.out.println(distance(22.66215, 75.9035,22.731457, 75.914391) + " Kilometers\n");
System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506) + " Nautical Miles\n");
System.out.println(" Your Result >>> "+DistanceCalculator.bearing(22.731457, 75.914391,22.66215, 75.9035));
}
private static double distance(double lat1, double lon1, double lat2, double lon2) {
String unit="k";
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == "K") {
dist = dist * 1.609344;
} else if (unit == "N") {
dist = dist * 0.8684;
}
return (dist);
}
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private static double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
protected static String bearing(double lat1, double lon1, double lat2, double lon2){
double longitude1 = lon1;
double longitude2 = lon2;
double latitude1 = Math.toRadians(lat1);
double latitude2 = Math.toRadians(lat2);
double longDiff= Math.toRadians(longitude2-longitude1);
double y= Math.sin(longDiff)*Math.cos(latitude2);
double x=Math.cos(latitude1)*Math.sin(latitude2)-Math.sin(latitude1)*Math.cos(latitude2)*Math.cos(longDiff);
double resultDegree= (Math.toDegrees(Math.atan2(y, x))+360)%360;
String coordNames[] = {"N","NNE", "NE","ENE","E", "ESE","SE","SSE", "S","SSW", "SW","WSW", "W","WNW", "NW","NNW", "N"};
double directionid = Math.round(resultDegree / 22.5);
if (directionid < 0) {
directionid = directionid + 16;
//no. of contains in array
}
String compasLoc=coordNames[(int) directionid];
return compasLoc;
}
}
<file_sep>/nearbySystem/nearbySystem-dal/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.javaSolutions</groupId>
<artifactId>nearbySystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.5.0</version>
</dependency>
<!-- Spring 4 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!-- Servlet+JSP+JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<!-- Apache Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Spring CORS JARS -->
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>java-property-utils</artifactId>
<version>1.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
<!--
https://mvnrepository.com/artifact/postgresql/postgresql
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1200-jdbc41</version>
</dependency>
https://mvnrepository.com/artifact/org.postgresql/postgresql
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.0.0</version>
</dependency>
-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.7.5</version>
</dependency>
<!-- multipart -->
<!-- <dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency> -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
<!-- Apache Tiles -->
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-api</artifactId>
<version>3.0.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-core</artifactId>
<version>3.0.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>3.0.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-servlet</artifactId>
<version>3.0.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-template</artifactId>
<version>3.0.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-el</artifactId>
<version>3.0.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.ning</groupId>
<artifactId>async-http-client</artifactId>
<version>1.9.8</version>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Form Validation using Annotations -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
</dependencies>
<artifactId>nearbySystem-dal</artifactId>
</project><file_sep>/nearbySystem/nearbySystem-dal/src/main/java/org/nearby/dao/UserDao.java
package org.nearby.dao;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialException;
import org.nearby.dto.CategoryType;
import org.nearby.dto.EmployeeRegistration;
import org.nearby.dto.EmployerRegistration;
import org.nearby.dto.JobCategory;
import org.nearby.dto.JobMaster;
import org.nearby.dto.Registration;
import org.nearby.dto.ReviewDto;
import org.nearby.dto.ServiceDto;
import org.nearby.dto.ServiceProvider;
import org.nearby.dto.SubCategoryType;
import org.nearby.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.mysql.jdbc.Blob;
@Repository
public class UserDao {
private static final UserDto UserDto = null;
@Autowired
JdbcTemplate template;
public void storeSp(Registration userRegistration) throws IOException, SerialException, SQLException {
// TODO Auto-generated method stub
final Integer subCategoryId = template
.queryForObject("select subcategoryId from service_category where service='"
+ userRegistration.getSubCategory() + "'and categoryId=" + userRegistration.getCategory()
+ " and type= '" + userRegistration.getType() + "'", Integer.class);
final String query = "insert into registration_master(firstName,lastName,mobileNumber,email,address,state,city,isdeleted,isactive,createdDate,updatedDate,subcategoryId,profile,avgrating,homeService,businessName,password) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
final String firstName = userRegistration.getFirstName();
final String lastName = userRegistration.getLastName();
final String mobileNumber = userRegistration.getMobileNumber();
final String password = userRegistration.getPassword();
final String email = userRegistration.getEmail();
final String address = userRegistration.getAddress();
final String businessName = userRegistration.getBusinessName();
final String homeSevice = userRegistration.getHomeService();
final String city = userRegistration.getCity();
final String state = userRegistration.getState();
String country = "India";
final SerialBlob blob = new javax.sql.rowset.serial.SerialBlob(userRegistration.getProfile());
int status = template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setString(3, mobileNumber);
ps.setString(4, email);
ps.setString(5, address);
ps.setString(6, state);
ps.setString(7, city);
ps.setInt(8, 0);
ps.setInt(9, 0);
ps.setTimestamp(10, timestamp);
ps.setTimestamp(11, timestamp);
ps.setInt(12, subCategoryId);
ps.setBlob(13, blob);
ps.setDouble(14, 0);
ps.setString(15, homeSevice);
ps.setString(16, businessName);
ps.setString(17, password);
return ps;
}
});
final Integer spId = template.queryForObject(
"select spId from registration_master where mobileNumber= '" + userRegistration.getMobileNumber() + "'",
Integer.class);
final String query2 = "insert into sp_master(spId,latitude,longitude) values(?,?,?)";
System.out.println(userRegistration.getLatitude()+" .. "+userRegistration.getLongitude());
final Double lat=Double.parseDouble(userRegistration.getLatitude());
final Double longg=Double.parseDouble(userRegistration.getLongitude());
int status2 = template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query2);
ps.setInt(1, spId);
ps.setDouble(2, lat);
ps.setDouble(3, longg);
return ps;
}
});
}
public int storeUser(UserDto uDto) throws IOException, SerialException, SQLException {
// TODO Auto-generated method stub
final String query = "insert into user_master(firstName,lastName,mobile,password,emailId,address,city,state,country,profile,latitude,longitude,isdeleted,isactive,createdDate,updatedDate) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
final String firstName = uDto.getFirstName();
final String lastName = uDto.getLastName();
final String mobileNumber = uDto.getMobile();
final String password = <PASSWORD>();
final String email = uDto.getEmailId();
final String address = uDto.getAddress();
final String city = uDto.getCity();
final String state = uDto.getState();
final Double latitude = uDto.getLatitude();
final Double longitude = uDto.getLongitude();
final String country = "India";
final SerialBlob blob = new javax.sql.rowset.serial.SerialBlob(uDto.getProfile());
int status = template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setString(3, mobileNumber);
ps.setString(4, password);
ps.setString(5, email);
ps.setString(6, address);
ps.setString(7, city);
ps.setString(8, state);
ps.setString(9, country);
ps.setBlob(10, blob);
ps.setDouble(11,latitude);
ps.setDouble(12,longitude);
ps.setInt(13, 0);
ps.setInt(14, 0);
ps.setTimestamp(15, timestamp);
ps.setTimestamp(16, timestamp);
return ps;
}
});
return status;
}
public void storeCategoryType(final String categoryType) {
// TODO Auto-generated method stub
final String query = "insert into category_master(categoryType)values(?)";
template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, categoryType);
return ps;
}
});
}
public void storeSubCategoryType(final String categoryType, final String subCategoryType, final String type) {
// TODO Auto-generated method stub
final String query = "insert into service_category(categoryId,service,type)values(?,?,?)";
template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query);
ps.setInt(1, Integer.parseInt(categoryType));
ps.setString(2, subCategoryType);
ps.setString(3, type);
return ps;
}
});
}
public List<CategoryType> fetchType() {
// TODO Auto-generated method stub
List<CategoryType> dto = template.query("select * from category_master",
new BeanPropertyRowMapper<CategoryType>(CategoryType.class));
for(CategoryType category:dto){
List<SubCategoryType> sub = template.query("select * from service_category where categoryId=" + category.getCategoryId() + " ",
new BeanPropertyRowMapper<SubCategoryType>(SubCategoryType.class));
category.setSubCategoryType(sub);
}
return dto;
}
public List<String> fetchAllServices(int cid) {
// TODO Auto-generated method stub
List<ServiceDto> dto = template.query("select * from service_category where categoryId=" + cid + " ",
new BeanPropertyRowMapper<ServiceDto>(ServiceDto.class));
List<String> list = new ArrayList<String>();
for (ServiceDto local : dto) {
System.out.println(local.getService() + " - " + local.getType());
list.add(local.getService() + " - " + local.getType());
}
return list;
}
public List<String> fetchServiceName(int cid) {
// TODO Auto-generated method stub
List<SubCategoryType> dto =template.query("select service from service_category where subcategoryId="+cid+"",
new BeanPropertyRowMapper<SubCategoryType>(SubCategoryType.class));
List<String> s= new ArrayList<String>();
for(SubCategoryType sub:dto){
s.add(sub.getService());
}
return s;
}
public List<String> fetchCategoryName(int cid) {
// TODO Auto-generated method stub
List<CategoryType> dto =template.query("select categoryType from category_master where categoryId="+cid+"",
new BeanPropertyRowMapper<CategoryType>(CategoryType.class));
List<String> s= new ArrayList<String>();
for(CategoryType sub:dto){
s.add(sub.getCategoryType());
}
return s;
}
public List<String> fetchAllEmail() {
// TODO Auto-generated method stub
List<Registration> dto = template.query("select email from registration_master",
new BeanPropertyRowMapper<Registration>(Registration.class));
List<String> list = new ArrayList<String>();
for (Registration local : dto) {
list.add(local.getEmail());
}
return list;
}
public List<String> fetchAllMobile() {
// TODO Auto-generated method stub
List<Registration> dto = template.query("select mobileNumber from registration_master",
new BeanPropertyRowMapper<Registration>(Registration.class));
List<String> list = new ArrayList<String>();
for (Registration local : dto) {
list.add(local.getMobileNumber());
}
return list;
}
public List<String> fetchAllUserMobile() {
// TODO Auto-generated method stub
List<UserDto> dto = template.query("select mobile from user_master",
new BeanPropertyRowMapper<UserDto>(UserDto.class));
List<String> list = new ArrayList<String>();
for (UserDto local : dto) {
list.add(local.getMobile());
}
return list;
}
public List<String> fetchAllUserEmail() {
// TODO Auto-generated method stub
List<UserDto> dto = template.query("select emailId from user_master",
new BeanPropertyRowMapper<UserDto>(UserDto.class));
List<String> list = new ArrayList<String>();
for (UserDto local : dto) {
list.add(local.getEmailId());
}
return list;
}
public List<String> fetchAllServicesForUser(int cid) {
// TODO Auto-generated method stub
List<ServiceDto> dto = template.query(
"select distinct service from service_category where categoryId=" + cid + " ",
new BeanPropertyRowMapper<ServiceDto>(ServiceDto.class));
List<String> list = new ArrayList<String>();
for (ServiceDto local : dto) {
list.add(local.getService());
}
return list;
}
public List<ServiceProvider> fetchSPLocation(String serviceid, String latitude, String longitude) {
List<ServiceProvider> providers = new ArrayList<ServiceProvider>();
List<ServiceProvider> list = template.query(
"SELECT s.firstName,s.mobileNumber,s.email,s.address,s.spId,s.profile,s.avgrating,s.lastname,s.businessName,p.latitude,p.longitude,( 6371 * ACOS( COS( RADIANS("
+ latitude + " ) ) * COS( RADIANS( p.latitude ) ) * COS( RADIANS( p.longitude )- RADIANS("
+ longitude + " ) ) + SIN( RADIANS( " + latitude
+ ") ) * SIN( RADIANS( p.latitude ) ) ) ) AS distance FROM registration_master s ,sp_master p , service_category sc WHERE sc.subcategoryId="
+ serviceid
+ " AND sc.subcategoryId=s.subcategoryId AND s.spId=p.spId HAVING distance <2",
new BeanPropertyRowMapper<ServiceProvider>(ServiceProvider.class));
providers.addAll(list);
// TODO Auto-generated method stub
return providers;
}
public void storeEmployer(EmployerRegistration dto) {
// TODO Auto-generated method stub
final String query = "insert into employer_registration_master(name,mobileNumber,email,address,state,city,type,dob,createdDate,isactive,isdeleted,updatedDate,password) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
final String name = dto.getName();
final String mobileNo = dto.getMobileNumber();
final String address = dto.getAddress();
final String state = dto.getState();
final String city = dto.getCity();
final String email = dto.getEmail();
final String password = <PASSWORD>();
final String type = dto.getType();
final Date dob = dto.getDob();
final Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
int status = template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, name);
ps.setString(2, mobileNo);
ps.setString(3, email);
ps.setString(4, address);
ps.setString(5, state);
ps.setString(6, city);
ps.setString(7, type);
ps.setDate(8, dob);
ps.setTimestamp(9, timeStamp);
ps.setInt(10, 0);
ps.setInt(11, 0);
ps.setTimestamp(12, timeStamp);
ps.setString(13, password);
return ps;
}
});
}
public Integer fetchUserInfo(String userId, String pass) {
// TODO Auto-generated method stub
try {
Integer user = template
.queryForObject("select employeeId from employee_registration_master where mobileNumber= '" + userId
+ "' and password= '" + pass + "'", Integer.class);
if (user != null) {
return user;
}
} catch (Exception e) {
return 0;
}
return 0;
}
public Integer fetchEmployerInfo(String userId, String pass) {
// TODO Auto-generated method stub
try {
Integer user = template
.queryForObject("select employerId from employer_registration_master where mobileNumber= '" + userId
+ "' and password= '" + pass + "'", Integer.class);
if (user != null) {
return user;
}
} catch (Exception e) {
return 0;
}
return 0;
}
public void storeJobPostDao(JobMaster dto) {
// TODO Auto-generated method stub
final String query = "insert into job_master(employerId,job_title,age,gender,salary,address,type,created_date,updated_date,created_by,isdeleted,isActive,jobDescription,jobCategoryId,jobSubCategory) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
final Timestamp time = new Timestamp(System.currentTimeMillis());
final Integer userId = dto.getUserId();
final String job_title = dto.getJob_title();
final String address = dto.getAddress();
final String age = dto.getAge();
final String gender = dto.getGender();
final Double salary = dto.getSalary();
final String type = dto.getType();
final String jd = dto.getJobDescription();
final Integer jobCategory = Integer.parseInt(dto.getJobCategory());
final String jobSubCategory = dto.getJobSubCategory();
int status = template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query);
ps.setInt(1, userId);
ps.setString(2, job_title);
ps.setString(3, age);
ps.setString(4, gender);
ps.setDouble(5, salary);
ps.setString(6, address);
ps.setString(7, type);
ps.setTimestamp(8, time);
ps.setTimestamp(9, time);
ps.setInt(10, userId);
ps.setInt(11, 0);
ps.setInt(12, 0);
ps.setString(13, jd);
ps.setInt(14, jobCategory);
ps.setString(15, jobSubCategory);
return ps;
}
});
}
public List<JobMaster> fetchAllJobs() {
// TODO Auto-generated method stub
List<JobMaster> list = template.query("select * from job_master",
new BeanPropertyRowMapper<JobMaster>(JobMaster.class));
return list;
}
public JobMaster fetchJob(Integer jobId) {
// TODO Auto-generated method stub
JobMaster dto = template.queryForObject("select * from job_master where jobId=" + jobId,
new BeanPropertyRowMapper<JobMaster>(JobMaster.class));
return dto;
}
public void updatePostedJob(JobMaster dto) {
// TODO Auto-generated method stub
template.update("update job_master set job_title = '" + dto.getJob_title() + "', age='" + dto.getAge()
+ "', address='" + dto.getAddress() + "',salary=" + dto.getSalary() + ",jobDescription='"
+ dto.getJobDescription() + "', updated_date='" + new Timestamp(System.currentTimeMillis())
+ "' where jobId =" + dto.getJobId());
}
public void deletPostedJob(String jobId) {
// TODO Auto-generated method stub
template.update("delete from job_master where jobId=" + Integer.parseInt(jobId));
}
public void storeEmployee(EmployeeRegistration dto) {
// TODO Auto-generated method stub
final String query = "insert into employee_registration_master(firstName,lastName,fatherName,gender,mobileNumber,email,"
+ "contactAddress,permanentAddress,dob,maritalStatus,numberOfChild,age,"
+ "salaryExpectation,jobNeeded,educationDetails,identityProof,created_date,updated_date,isDeleted,isActive,password) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
final String fname = dto.getFirstName();
final String lName = dto.getLastName();
final String fatherName = dto.getFatherName();
final String gender = dto.getGender();
final String mobNo = dto.getMobileNumber();
final String password = dto.getPassword();
final String email = dto.getEmail();
final String conAddress = dto.getContactAddress();
final String perAddres = dto.getPermanentAddress();
final Date dob = dto.getDob();
final String marital = dto.getMaritalStatus();
final Integer noOfChild = dto.getNoOfChild();
final Integer age = dto.getAge();
final Double salary = dto.getSalaryExpectation();
final String job = dto.getJobNeeded();
final String education = dto.getEducationDetails();
final String identity = dto.getIdentity();
final Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, fname);
ps.setString(2, lName);
ps.setString(3, fatherName);
ps.setString(4, gender);
ps.setString(5, mobNo);
ps.setString(6, email);
ps.setString(7, conAddress);
ps.setString(8, perAddres);
ps.setDate(9, dob);
ps.setString(10, marital);
ps.setInt(11, noOfChild);
ps.setInt(12, 0);
ps.setDouble(13, salary);
ps.setString(14, job);
ps.setString(15, education);
ps.setString(16, identity);
ps.setTimestamp(17, timeStamp);
ps.setTimestamp(18, timeStamp);
ps.setInt(19, 0);
ps.setInt(20, 0);
ps.setString(21, password);
return ps;
}
});
}
public List<JobCategory> fetchAllJobCategory() {
// TODO Auto-generated method stub
List<JobCategory> list = template.query("select * from job_category",
new BeanPropertyRowMapper<JobCategory>(JobCategory.class));
return list;
}
public List<String> fetchAllSubCategory(int cid) {
// TODO Auto-generated method stub
List<JobCategory> list2 = template.query("select * from job_subcategory where jobCategoryId=" + cid + " ",
new BeanPropertyRowMapper<JobCategory>(JobCategory.class));
List<String> list = new ArrayList<String>();
for (JobCategory local : list2) {
list.add(local.getSubCategory());
}
return list;
}
public List<JobMaster> fetchAvailableJobs(String userId) {
// TODO Auto-generated method stub
try {
String jobNeeded = template.queryForObject(
"select jobNeeded from employee_registration_master where employeeId='" + userId + "'",
String.class);
if (jobNeeded != null) {
List<JobMaster> list = template.query(
"select * from job_master where jobSubCategory='" + jobNeeded + "'",
new BeanPropertyRowMapper<JobMaster>(JobMaster.class));
return list;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public List<EmployeeRegistration> fetchAvailableEmployee(String subCatValue) {
// TODO Auto-generated method stub
List<EmployeeRegistration> list = template.query(
"select * from employee_registration_master where jobNeeded='" + subCatValue + "'",
new BeanPropertyRowMapper<EmployeeRegistration>(EmployeeRegistration.class));
return list;
}
public List<ServiceProvider> fetchSearchProvider(String city, String area, String subCategory) {
List<Integer> subCategoryIdList = template.queryForList(
"select subcategoryId from service_category where service='" + subCategory + "'", Integer.class);
List<ServiceProvider> providers = new ArrayList<ServiceProvider>();
for (Integer subCategoryId : subCategoryIdList) {
List<ServiceProvider> list = template
.query("SELECT s.spId,s.businessName,s.firstName,s.mobileNumber,s.lastname,s.address,s.email,s.profile,s.avgrating,p.latitude,p.longitude FROM registration_master s ,sp_master p WHERE city LIKE '%"
+ city + "%' AND address LIKE '%" + area + "%' AND subcategoryId=" + subCategoryId
+ " AND s.spId=p.spId", new BeanPropertyRowMapper<ServiceProvider>(ServiceProvider.class));
providers.addAll(list);
}
return providers;
}
public List<ReviewDto> fetchReview(String spId) {
List<ReviewDto> providers = new ArrayList<ReviewDto>();
List<ReviewDto> list = template.query("SELECT review,rating,userId FROM sp_review WHERE spId=" + spId + "",
new BeanPropertyRowMapper<ReviewDto>(ReviewDto.class));
providers.addAll(list);
return providers;
}
public int insertContactDetail(final int spId,final String lat,final String longi,final String userId) {
// TODO Auto-generated method stub
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
final String query2 = "insert into user_spmaster(spId,userId,latitude,longitude,Date) values(?,?,?,?,?)";
int result = template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query2);
ps.setInt(1, spId);
ps.setString(2, userId);
ps.setDouble(3,Double.parseDouble(lat));
ps.setDouble(4,Double.parseDouble(longi));
ps.setTimestamp(5,timestamp);
return ps;
}
});
return result;
}
public int addReview(final int spId,final String review,final int userId,final double rating) {
int status=0;
try{
Integer rId = template.queryForObject("SELECT reviewId FROM sp_review WHERE spId='"+spId+"' AND userId='"+userId+"'", Integer.class);
status=1;
if(rating==0){
template.update("UPDATE sp_review SET review='"+review+"' WHERE reviewId='"+rId+"'");
}
else{
template.update("UPDATE sp_review SET review='"+review+"', rating='"+rating+"' WHERE reviewId='"+rId+"'");
}
}catch(Exception e){
final String query2 = "insert into sp_review(spId,userId,review,rating) values(?,?,?,?)";
status = template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query2);
ps.setInt(1, spId);
ps.setInt(2, userId);
ps.setString(3,review);
ps.setDouble(4,rating);
return ps;
}
});
}
List<ReviewDto> providers = new ArrayList<ReviewDto>();
List<ReviewDto> list = template.query("SELECT rating FROM sp_review WHERE spId=" + spId + "",
new BeanPropertyRowMapper<ReviewDto>(ReviewDto.class));
providers.addAll(list);
double rat=0;
for(ReviewDto rDto:providers){
rat=rat+Double.parseDouble(rDto.getRating());
}
double noofrating=list.size();
double avgrating=rat/noofrating;
DecimalFormat df = new DecimalFormat(".#");
avgrating= Double.parseDouble(df.format(avgrating));
template.update("UPDATE registration_master SET avgrating='"+avgrating+"' WHERE spId='"+spId+"'");
return status;
}
public UserDto fetchUser(String mobile, String password) {
try {
UserDto user = template
.queryForObject("select * from user_master where mobile= '" + mobile
+ "' and password= '" +password+ "'",new BeanPropertyRowMapper<UserDto>(UserDto.class));
if (user != null) {
System.out.println("Login user "+user.getFirstName());
return user;
}
} catch (Exception e) {
return null;
}
return null;
}
public int verifySp(String mobile, String password) {
try {
Integer user = template
.queryForObject("select spId from registration_master where mobileNumber= '" + mobile
+ "' and password= '" + password + "'", Integer.class);
if (user != null) {
return user;
}
} catch (Exception e) {
return 0;
}
return 0;
}
public ServiceProvider fetchSp(String spId) {
try {
ServiceProvider user = template
.queryForObject("select * from registration_master where spId= '" +spId+"'",new BeanPropertyRowMapper<ServiceProvider>(ServiceProvider.class));
if (user != null) {
System.out.println("Login user "+user.getFirstName());
return user;
}
}catch (EmptyResultDataAccessException e) {
return null;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public UserDto fetchUser(String userId) {
UserDto user= template.queryForObject("SELECT * FROM user_master WHERE userId=" + userId + "",
new BeanPropertyRowMapper<UserDto>(UserDto.class));
return user;
}
public int fetchNoOfReview(int spId) {
Integer user = template.queryForObject("SELECT COUNT(*) FROM sp_review WHERE spId='"+spId+"'", Integer.class);
return user;
}
public ReviewDto fetchUserReviewDetails(int spId,int userId) {
try{
ReviewDto rDto= template.queryForObject("SELECT * FROM sp_review WHERE spId='"+spId+"' AND userId='"+userId+"'",
new BeanPropertyRowMapper<ReviewDto>(ReviewDto.class));
System.out.println(rDto.getReview()+" of sp id "+spId+" with user id "+userId);
return rDto;
}catch(Exception e){
return null;
}
}
}
<file_sep>/nearbySystem/nearbySystem-nearby/src/main/java/org/nearby/controller/HomeController.java
package org.nearby.controller;
import java.io.IOException;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.rowset.serial.SerialException;
import org.nearby.dao.UserDao;
import org.nearby.dto.CategoryType;
import org.nearby.dto.Registration;
import org.nearby.dto.ReviewDto;
import org.nearby.dto.ServiceProvider;
import org.nearby.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@MultipartConfig
@Controller
public class HomeController {
@Autowired
UserDao userDao;
@RequestMapping(value = "/adminHome")
public String adminHome() {
return "loginPage";
}
@RequestMapping(value = "/spLoginPage")
public String spLoginPage() {
return "spLoginPage";
}
@RequestMapping(value = "/sploginVerify", method = RequestMethod.POST)
public ModelAndView sploginVerify(HttpServletRequest servletRequest) throws SQLException {
String mobile = servletRequest.getParameter("userName");
String pass = servletRequest.getParameter("password");
int spId=userDao.verifySp(mobile, pass);
if(spId!=0){
HttpSession session = servletRequest.getSession(true);
session.setAttribute("spId",spId);
ModelAndView map = new ModelAndView("spHome");
return map;
}
ModelAndView map = new ModelAndView("spLoginPage");
map.addObject("message", "Invalid username and password");
return map;
}
@RequestMapping(value = "/fetchsp",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ServiceProvider> fetchsp(HttpServletRequest request) throws SQLException {
String Id = request.getParameter("spId");
ServiceProvider spDto = userDao.fetchSp(Id);
Blob blob = spDto.getProfile();
int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);
spDto.setImg(blobAsBytes);
spDto.setProfile(null);
return new ResponseEntity<ServiceProvider>(spDto,HttpStatus.OK);
}
@RequestMapping(value = "/splogout")
public String splogout(HttpServletRequest request, RedirectAttributes redirectAttributes) {
HttpSession session = request.getSession(false);
session.invalidate();
redirectAttributes.addFlashAttribute("message", "Logout successfully");
return "redirect:/spLoginPage";
}
@RequestMapping(value = "/userLoginPage")
public String userLoginPage() {
return "userLoginPage";
}
@RequestMapping(value = "/logout")
public String logout(HttpServletRequest request, RedirectAttributes redirectAttributes) {
HttpSession session = request.getSession(false);
session.setAttribute("aId",null);
session.invalidate();
redirectAttributes.addFlashAttribute("message", "Logout successfully");
return "redirect:/adminHome";
}
@RequestMapping(value = "/userlogout")
public ModelAndView userlogout(HttpServletRequest request) {
HttpSession session = request.getSession(false);
session.invalidate();
List<CategoryType> listOfCategory = userDao.fetchType();
ModelAndView map = new ModelAndView("userHome");
map.addObject("listOfType", listOfCategory);
return map;
}
@RequestMapping(value = "/userRegistration")
public ModelAndView userRegistration(Model model) {
model.addAttribute("userDto", new UserDto());
ModelAndView map = new ModelAndView("userRegistration");
return map;
}
@RequestMapping(value = "/storeUser", method = RequestMethod.POST )
public String userSp(HttpServletRequest request,RedirectAttributes redirectAttributes) throws IOException, SerialException, SQLException{
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multiRequest.getFile("profile");
byte []b=file.getBytes();
String latitude=request.getParameter("latitude");
String longitude=request.getParameter("longitude");
String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String mobile=request.getParameter("mobile");
String password=request.getParameter("password");
String email=request.getParameter("emailId");
String address=request.getParameter("address");
String country=request.getParameter("country").trim();
String state=request.getParameter("state1").trim();
System.out.println("State of user = "+state);
String city=request.getParameter("city").trim();
UserDto userDto=new UserDto();
userDto.setFirstName(firstName);
userDto.setLastName(lastName);
userDto.setMobile(mobile);
userDto.setPassword(<PASSWORD>);
userDto.setEmailId(email);
userDto.setAddress(address);
userDto.setCity(city);
userDto.setState(state);
userDto.setCountry(country);
userDto.setProfile(b);
userDto.setLatitude(Double.parseDouble(latitude));
userDto.setLongitude(Double.parseDouble(longitude));
int result=userDao.storeUser(userDto);
if(result==1){
redirectAttributes.addFlashAttribute("message", "Registration successfully");
}else{
redirectAttributes.addFlashAttribute("message", "Registration Failed");
}
return "redirect:/userRegistration";
}
@RequestMapping(value = "/addSp")
public ModelAndView addUser(Model model,HttpServletRequest request) {
HttpSession session = request.getSession(false);
System.out.println("Admin id = "+session.getAttribute("aId"));
Object s1=session.getAttribute("aId");
if(s1==null){
ModelAndView map = new ModelAndView("loginPage");
map.addObject("message", "First You Have to Login..");
return map;
}
model.addAttribute("registration", new Registration());
List<CategoryType> listOfCategory = userDao.fetchType();
ModelAndView map = new ModelAndView("addSp");
map.addObject("listOfType", listOfCategory);
return map;
}
@RequestMapping(value = "/storeSp", method = RequestMethod.POST )
public String storeSp(RedirectAttributes redirectAttributes,HttpServletRequest request)
throws IOException, ServletException, SerialException, SQLException {
HttpSession session = request.getSession(false);
System.out.println("Admin id = "+session.getAttribute("aId"));
Object s1=session.getAttribute("aId");
if(s1==null){
redirectAttributes.addFlashAttribute("message", "First You have to login..");
return "redirect:/adminHome";
}
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multiRequest.getFile("profile");
byte []b=file.getBytes();
String latitude=request.getParameter("latitude");
String longitude=request.getParameter("longitude");
System.out.println(latitude+" ... "+longitude);
String businessName=request.getParameter("businessName");
String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String mobileNumber=request.getParameter("mobileNumber");
String password=request.getParameter("password");
String email=request.getParameter("email");
String address=request.getParameter("address");
Integer categoryId=Integer.parseInt(request.getParameter("categoryId"));
String subCategory=request.getParameter("subCategory");
String state=request.getParameter("state1").trim();
System.out.println("state = "+state);
String city=request.getParameter("city").trim();
String homeService=request.getParameter("homeService").trim();
Registration user=new Registration();
if(lastName.equals("")){
user.setLastName("Not specified");
}else{
user.setLastName(lastName);
}
if(email.equals("")){
user.setEmail("Not specified");
}else{
user.setEmail(email);
}
user.setBusinessName(businessName);
user.setFirstName(firstName);
user.setMobileNumber(mobileNumber);
user.setPassword(<PASSWORD>);
System.out.println(user.getPassword()+" ........");
user.setAddress(address);
user.setCategoryId(categoryId);
user.setSubCategory(subCategory);
user.setState(state);
user.setCity(city);
user.setProfile(b);
user.setHomeService(homeService);
user.setLatitude(latitude);
user.setLongitude(longitude);
String str = user.getSubCategory();
String[] obj = str.split("\\-");
user.setSubCategory(obj[0].trim());
user.setType(obj[1].trim());
userDao.storeSp(user);
redirectAttributes.addFlashAttribute("message", "SP added successfully");
return "redirect:/addSp";
}
@RequestMapping(value = "/loginVerify", method = RequestMethod.POST)
public String loginVerify(HttpServletRequest servletRequest, RedirectAttributes redirectAttributes) {
String userId = servletRequest.getParameter("userName");
String pass = servletRequest.getParameter("password");
if (userId.equals("admin") && pass.equals("<PASSWORD>")) {
HttpSession session = servletRequest.getSession(true);
session.setAttribute("aId",userId);
return "adminHomePage";
}
redirectAttributes.addFlashAttribute("message", "Invalid username and password");
return "redirect:/adminHome";
}
@RequestMapping(value = "/deshboard")
public String deshboard() {
return "adminHomePage";
}
@RequestMapping(value = "/addCategory")
public ModelAndView addCategory(HttpServletRequest request) {
HttpSession session = request.getSession(false);
System.out.println("Admin id = "+session.getAttribute("aId"));
Object s1=session.getAttribute("aId");
if(s1==null){
ModelAndView map = new ModelAndView("loginPage");
map.addObject("message", "First You Have to Login..");
return map;
}
List<CategoryType> listOfCategory = userDao.fetchType();
ModelAndView map = new ModelAndView("addCategory");
map.addObject("listOfType", listOfCategory);
return map;
}
@RequestMapping(value = "/storeCategory")
public String storeCategory(HttpServletRequest request, RedirectAttributes redirectAttributes) {
HttpSession session = request.getSession(false);
System.out.println("Admin id = "+session.getAttribute("aId"));
Object s1=session.getAttribute("aId");
if(s1==null){
redirectAttributes.addFlashAttribute("message", "First You have to login..");
return "redirect:/adminHome";
}
String categoryType = request.getParameter("type");
userDao.storeCategoryType(categoryType);
redirectAttributes.addFlashAttribute("message", "Type Added successfully");
return "redirect:/addCategory";
}
@RequestMapping(value = "/addSubCategory")
public ModelAndView addSubCategory(HttpServletRequest request) {
HttpSession session = request.getSession(false);
System.out.println("Admin id = "+session.getAttribute("aId"));
Object s1=session.getAttribute("aId");
if(s1==null){
ModelAndView map = new ModelAndView("loginPage");
map.addObject("message", "First You Have to Login..");
return map;
}
List<CategoryType> listOfCategory = userDao.fetchType();
ModelAndView map = new ModelAndView("addSubCategory");
map.addObject("listOfType", listOfCategory);
return map;
}
@RequestMapping(value = "/storeSubCategory")
public String storeSubCategory(HttpServletRequest request, RedirectAttributes redirectAttributes) {
HttpSession session = request.getSession(false);
System.out.println("Admin id = "+session.getAttribute("aId"));
Object s1=session.getAttribute("aId");
if(s1==null){
redirectAttributes.addFlashAttribute("message", "First You have to login..");
return "redirect:/adminHome";
}
String categoryType = request.getParameter("categorytype");
String subCategoryType = request.getParameter("subType");
String type = request.getParameter("type");
userDao.storeSubCategoryType(categoryType, subCategoryType, type);
redirectAttributes.addFlashAttribute("message", "Subcategory Added successfully");
return "redirect:/addSubCategory";
}
@RequestMapping(value = "/user")
public ModelAndView userHome() {
List<CategoryType> listOfCategory = userDao.fetchType();
ModelAndView map = new ModelAndView("userHome");
map.addObject("listOfType", listOfCategory);
return map;
}
@RequestMapping(value = "/searchSp")
public ModelAndView searchSp() {
List<CategoryType> listOfCategory = userDao.fetchType();
ModelAndView map = new ModelAndView("searchSp");
map.addObject("listOfType", listOfCategory);
return map;
}
@RequestMapping(value = "/searchProvider",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ServiceProvider>> searchProvider(HttpServletRequest request) throws SQLException {
String area = request.getParameter("area");
String city = request.getParameter("city");
String subCategory = request.getParameter("subCategory");
List<ServiceProvider> Services = userDao.fetchSearchProvider(city,area, subCategory);
for(ServiceProvider s:Services){
s.setService(subCategory);
Blob blob = s.getProfile();
int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);
s.setImg(blobAsBytes);
s.setProfile(null);
}
return new ResponseEntity<List<ServiceProvider>>(Services,HttpStatus.OK);
}
@RequestMapping(value = "/fetchReview",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ReviewDto>> fetchReview(HttpServletRequest request){
String spId = request.getParameter("id");
List<ReviewDto> reviews=userDao.fetchReview(spId);
return new ResponseEntity<List<ReviewDto>>(reviews,HttpStatus.OK);
}
@RequestMapping(value = "/fetchUser",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserDto> fetchUser(HttpServletRequest request){
String userId = request.getParameter("userId");
UserDto user=userDao.fetchUser(userId);
return new ResponseEntity<UserDto>(user,HttpStatus.OK);
}
}
<file_sep>/nearbySystem/nearbySystem-dal/src/main/resources/dbDump/nearby_dump.sql
/*
SQLyog Enterprise - MySQL GUI v8.14
MySQL - 5.1.30-community : Database - nearby_db
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!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 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`nearby_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `nearby_db`;
/*Table structure for table `category_master` */
DROP TABLE IF EXISTS `category_master`;
CREATE TABLE `category_master` (
`categoryId` int(11) NOT NULL AUTO_INCREMENT,
`categoryType` varchar(50) DEFAULT NULL,
PRIMARY KEY (`categoryId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `category_master` */
insert into `category_master`(`categoryId`,`categoryType`) values (1,'Food'),(2,'Electronics'),(3,'Footwear'),(4,'Fashion'),(5,'Stationary '),(6,'Doctor');
/*Table structure for table `employee_registration_master` */
DROP TABLE IF EXISTS `employee_registration_master`;
CREATE TABLE `employee_registration_master` (
`employeeId` int(11) NOT NULL AUTO_INCREMENT,
`firstName` varchar(20) DEFAULT NULL,
`lastName` varchar(20) DEFAULT NULL,
`fatherName` varchar(50) DEFAULT NULL,
`gender` varchar(50) DEFAULT NULL,
`mobileNumber` varchar(20) DEFAULT NULL,
`email` varchar(200) DEFAULT NULL,
`contactAddress` varchar(500) DEFAULT NULL,
`permanentAddress` varchar(500) DEFAULT NULL,
`dob` date DEFAULT NULL,
`maritalStatus` varchar(20) DEFAULT NULL,
`numberOfChild` int(5) DEFAULT NULL,
`age` double DEFAULT NULL,
`salaryExpectation` varchar(50) DEFAULT NULL,
`jobNeeded` varchar(500) DEFAULT NULL,
`educationDetails` varchar(500) DEFAULT NULL,
`identityProof` varchar(100) DEFAULT NULL,
`created_date` timestamp NULL DEFAULT NULL,
`updated_date` timestamp NULL DEFAULT NULL,
`isDeleted` int(2) DEFAULT NULL,
`isActive` int(2) DEFAULT NULL,
PRIMARY KEY (`employeeId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*Data for the table `employee_registration_master` */
insert into `employee_registration_master`(`employeeId`,`firstName`,`lastName`,`fatherName`,`gender`,`mobileNumber`,`email`,`contactAddress`,`permanentAddress`,`dob`,`maritalStatus`,`numberOfChild`,`age`,`salaryExpectation`,`jobNeeded`,`educationDetails`,`identityProof`,`created_date`,`updated_date`,`isDeleted`,`isActive`) values (1,'Aman','choukse','<NAME>','male','9755552578','<EMAIL>','78 Sanskrati Nagar ','78 Sanskrati Nagar ','2018-05-02','UnMarried',0,0,'30000.0','Java Developer','Graduation',NULL,'2018-05-19 15:37:15','2018-05-19 15:37:15',0,0),(2,'Navin','jain','<NAME>','male','9713950147','<EMAIL>','265 anoop nagar','265 anoop nagar','1990-08-06','Married',1,0,'30000.0','IT ','Graduation',NULL,'2018-05-19 17:48:57','2018-05-19 17:48:57',0,0);
/*Table structure for table `employer_registration_master` */
DROP TABLE IF EXISTS `employer_registration_master`;
CREATE TABLE `employer_registration_master` (
`employerId` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) DEFAULT NULL,
`mobileNumber` varchar(12) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`address` varchar(500) DEFAULT NULL,
`state` varchar(200) DEFAULT NULL,
`city` varchar(200) DEFAULT NULL,
`type` varchar(200) DEFAULT NULL,
`dob` date DEFAULT NULL,
`createdDate` timestamp NULL DEFAULT NULL,
`isactive` int(2) DEFAULT NULL,
`isdeleted` int(2) DEFAULT NULL,
`updatedDate` timestamp NULL DEFAULT NULL,
`password` varchar(250) DEFAULT NULL,
PRIMARY KEY (`employerId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
/*Data for the table `employer_registration_master` */
insert into `employer_registration_master`(`employerId`,`name`,`mobileNumber`,`email`,`address`,`state`,`city`,`type`,`dob`,`createdDate`,`isactive`,`isdeleted`,`updatedDate`,`password`) values (1,'Aman ','<PASSWORD>','<EMAIL>','78 <NAME> ','MadhyaPradesh','Indore','Employer','1993-05-02','2018-05-18 15:30:41',0,0,'2018-05-18 15:30:41','123');
/*Table structure for table `job_category` */
DROP TABLE IF EXISTS `job_category`;
CREATE TABLE `job_category` (
`jobCategoryId` int(11) NOT NULL AUTO_INCREMENT,
`job` varchar(200) DEFAULT NULL,
PRIMARY KEY (`jobCategoryId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*Data for the table `job_category` */
insert into `job_category`(`jobCategoryId`,`job`) values (1,'House Hold Service');
/*Table structure for table `job_master` */
DROP TABLE IF EXISTS `job_master`;
CREATE TABLE `job_master` (
`jobId` int(11) NOT NULL AUTO_INCREMENT,
`employerId` int(11) DEFAULT NULL,
`job_title` varchar(250) DEFAULT NULL,
`age` varchar(200) DEFAULT NULL,
`gender` varchar(11) DEFAULT NULL,
`salary` double DEFAULT NULL,
`address` varchar(250) DEFAULT NULL,
`type` varchar(200) DEFAULT NULL,
`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`created_by` int(11) DEFAULT NULL,
`isdeleted` int(2) DEFAULT NULL,
`isActive` int(2) DEFAULT NULL,
`jobDescription` varchar(500) DEFAULT NULL,
PRIMARY KEY (`jobId`),
KEY `FK_job_master` (`employerId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
/*Data for the table `job_master` */
insert into `job_master`(`jobId`,`employerId`,`job_title`,`age`,`gender`,`salary`,`address`,`type`,`created_date`,`updated_date`,`created_by`,`isdeleted`,`isActive`,`jobDescription`) values (1,1,'Java Trainer','25-30','male',25000,'Indore','monthly','2018-05-18 15:32:44','2018-05-18 15:32:44',1,0,0,'I want a trainer who have depth knowledge of java ');
/*Table structure for table `job_subcategory` */
DROP TABLE IF EXISTS `job_subcategory`;
CREATE TABLE `job_subcategory` (
`jobSubCategoryId` int(11) NOT NULL AUTO_INCREMENT,
`jobCategoryId` int(20) DEFAULT NULL,
`subCategory` varchar(200) DEFAULT NULL,
PRIMARY KEY (`jobSubCategoryId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*Data for the table `job_subcategory` */
insert into `job_subcategory`(`jobSubCategoryId`,`jobCategoryId`,`subCategory`) values (1,1,'Gardening'),(2,1,'Maid');
/*Table structure for table `registration_master` */
DROP TABLE IF EXISTS `registration_master`;
CREATE TABLE `registration_master` (
`spId` int(11) NOT NULL AUTO_INCREMENT,
`firstName` varchar(30) DEFAULT NULL,
`lastName` varchar(30) DEFAULT NULL,
`mobileNumber` varchar(15) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`address` varchar(250) DEFAULT NULL,
`isdeleted` int(1) DEFAULT NULL,
`isactive` int(1) DEFAULT NULL,
`createdDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updatedDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`subcategoryId` int(11) DEFAULT NULL,
PRIMARY KEY (`spId`),
KEY `FK_registration_master` (`subcategoryId`),
CONSTRAINT `FK_registration_master` FOREIGN KEY (`serviceId`) REFERENCES `service_category` (`sno`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `registration_master` */
insert into `registration_master`(`spId`,`firstName`,`lastName`,`mobileNumber`,`email`,`address`,`isdeleted`,`isactive`,`createdDate`,`updatedDate`,`subcategoryId`) values (1,'Aman','Choukse','9755552578','<EMAIL>','78 Sanskrati nagar',0,0,'2018-05-07 13:17:24','2018-05-07 13:17:24',3),(2,'Ashish','Birle','9826895389','<EMAIL>','28 A krishi Vihar Tilak Nagar',0,0,'2018-05-07 13:17:53','2018-05-07 13:17:53',6),(3,'navin','jain','8814757845','<EMAIL>','265 Anoop Nagar',0,0,'2018-05-07 13:18:21','2018-05-07 13:18:21',4),(4,'Mahesh','muramkar','1481515','<EMAIL>','129 Pardeshipura ',0,0,'2018-05-07 13:23:58','2018-05-07 13:23:58',4),(5,'Dr Sangita ','Thankur','9713950148','<EMAIL>','253 Anoop Nagar',0,0,'2018-05-07 18:36:47','2018-05-07 18:36:47',7),(6,'Dr rani','manchanda','8881234567','<EMAIL>','240 Anoop Nagar',0,0,'2018-05-07 18:38:17','2018-05-07 18:38:17',7),(7,'Dr.Pawan ','Thankur','66874512365','<EMAIL>','150 Tilak nagar',0,0,'2018-05-07 18:53:34','2018-05-07 18:53:34',7);
/*Table structure for table `service_category` */
DROP TABLE IF EXISTS `service_category`;
CREATE TABLE `service_category` (
`subcategoryId` int(11) NOT NULL AUTO_INCREMENT,
`categoryId` int(11) DEFAULT NULL,
`service` varchar(50) DEFAULT NULL,
`type` varchar(50) DEFAULT NULL,
PRIMARY KEY (`subcategoryId`),
KEY `FK_service_category` (`categoryId`),
CONSTRAINT `FK_service_category` FOREIGN KEY (`categoryId`) REFERENCES `category_master` (`sno`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `service_category` */
insert into `service_category`(`subcategoryId`,`categoryId`,`service`,`type`) values (1,1,'vegetable','static'),(2,1,'vegetable','mobile'),(3,2,'Mobile Phones','static'),(4,3,'Bata','static'),(5,3,'Woodland','static'),(6,5,'Book Shop','static'),(7,6,'Dentist','static');
/*Table structure for table `sp_master` */
DROP TABLE IF EXISTS `sp_master`;
CREATE TABLE `sp_master` (
`sno` int(6) NOT NULL AUTO_INCREMENT,
`spId` int(6) DEFAULT NULL,
`latitude` double DEFAULT NULL,
`longitude` double DEFAULT NULL,
PRIMARY KEY (`sno`),
KEY `FK_sp_master` (`spId`),
CONSTRAINT `FK_sp_master` FOREIGN KEY (`userId`) REFERENCES `registration_master` (`sno`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;
/*Data for the table `sp_master` */
insert into `sp_master`(`sno`,`spId`,`latitude`,`longitude`) values (1,1,22.7628003,75.8824259),(2,2,22.7156564,75.8966003),(3,3,22.7326607,75.8907418),(4,4,22.7453955,75.8717054),(5,5,22.7318948,75.890792),(6,6,22.7318948,75.890792),(7,7,22.714865,75.899353);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
<file_sep>/nearbySystem/nearbySystem-jobPortal/src/main/java/org/nearby/controller/PortalRestController.java
package org.nearby.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.nearby.dao.UserDao;
import org.nearby.dto.EmployeeRegistration;
import org.nearby.dto.JobMaster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PortalRestController {
@Autowired
private UserDao userDao;
@RequestMapping(value = "/fetchJobCategory", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<String>> fetchServicesForUser(HttpServletRequest request) {
String cid = request.getParameter("cid");
List<String> allJobs = userDao.fetchAllSubCategory(Integer.parseInt(cid));
return new ResponseEntity<List<String>>(allJobs, HttpStatus.OK);
}
@RequestMapping(value = "/fetchAvailableEmployee", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<EmployeeRegistration>> fetchAvailableEmployee(HttpServletRequest request) {
String subCatValue = request.getParameter("subCatValue");
List<EmployeeRegistration> availableEmp = userDao.fetchAvailableEmployee(subCatValue);
return new ResponseEntity<List<EmployeeRegistration>>(availableEmp, HttpStatus.OK);
}
}
<file_sep>/README.md
# Java-Solution-NearBySystem<file_sep>/nearbySystem/nearbySystem-jobPortal/src/main/java/org/nearby/utils/TilesIConstant.java
package org.nearby.utils;
public class TilesIConstant {
/**
* User header and footer
*/
public static final String DEFAULT_LAYOUT = "/WEB-INF/layout/defaultLayout.jsp";
public static final String HEADER = "/WEB-INF/layout/header.jsp";
public static final String BODY = "/WEB-INF/jsp/portalHome.jsp";
public static final String PORTAL_LOGIN = "/WEB-INF/jsp/portalLoginPage.jsp";
public static final String EMPLOYER_REGISTRATION = "/WEB-INF/jsp/registerEmployer.jsp";
public static final String EMPLOYEE_REGISTRATION= "/WEB-INF/jsp/registerEmployee.jsp";
public static final String POST_JOB = "/WEB-INF/jsp/postJob.jsp";
public static final String SEARCH_JOB = "/WEB-INF/jsp/searchJob.jsp";
public static final String EDIT_POSTED_JOB= "/WEB-INF/jsp/editPostedJob.jsp";
public static final String FOOTER = "/WEB-INF/layout/footer.jsp";
public static final String EMPLOYEE_BODY = "/WEB-INF/jsp/portalHomeEmployee.jsp";
public static final String EMPLOYEE_HEADER = "/WEB-INF/jsp/EmployeeHeader.jsp";
public static final String AVAILABLE_JOB = "/WEB-INF/jsp/availableJob.jsp";
public static final String VIEWAVAILABLE_EMPLOYEE = "/WEB-INF/jsp/viewAvailableEmployee.jsp";
}
<file_sep>/nearbySystem/nearbySystem-nearby/src/main/resources/message.properties
registration.lastName.empty=Last Name not be null okay.
registration.firstName.empty=First name should be bt 3 to 20 character.
<file_sep>/nearbySystem/nearbySystem-dal/src/main/java/org/nearby/dto/EmployeeRegistration.java
package org.nearby.dto;
import java.sql.Date;
public class EmployeeRegistration {
private Integer employeeId;
private String firstName;
private String lastName;
private String fatherName;
private String gender;
private String mobileNumber;
private String ContactAddress;
private String permanentAddress;
private String password;
private String maritalStatus;
private Integer noOfChild;
private Date dob;
private Integer age;
private String email;
private String jobNeeded;
private String educationDetails;
private String identity;
private Integer isActive;
private Integer isDeleted;
private Double salaryExpectation;
private String identityProof;
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getContactAddress() {
return ContactAddress;
}
public void setContactAddress(String contactAddress) {
ContactAddress = contactAddress;
}
public String getPermanentAddress() {
return permanentAddress;
}
public void setPermanentAddress(String permanentAddress) {
this.permanentAddress = permanentAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public Integer getNoOfChild() {
return noOfChild;
}
public void setNoOfChild(Integer noOfChild) {
this.noOfChild = noOfChild;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getJobNeeded() {
return jobNeeded;
}
public void setJobNeeded(String jobNeeded) {
this.jobNeeded = jobNeeded;
}
public String getEducationDetails() {
return educationDetails;
}
public void setEducationDetails(String educationDetails) {
this.educationDetails = educationDetails;
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public Integer getIsActive() {
return isActive;
}
public void setIsActive(Integer isActive) {
this.isActive = isActive;
}
public Integer getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Integer isDeleted) {
this.isDeleted = isDeleted;
}
public Double getSalaryExpectation() {
return salaryExpectation;
}
public void setSalaryExpectation(Double salaryExpectation) {
this.salaryExpectation = salaryExpectation;
}
public String getIdentityProof() {
return identityProof;
}
public void setIdentityProof(String identityProof) {
this.identityProof = identityProof;
}
}
<file_sep>/nearbySystem/nearbySystem-nearby/src/main/webapp/resources/js/userhome.js
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
var lati;
var longi;
function showPosition(position) {
lati = position.coords.latitude;
longi = position.coords.longitude;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: lati, lng: longi}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
geocodeLatLng(geocoder, map, infowindow,lati,longi);
// alert(x+" "+y);
myMap(position.coords.latitude, position.coords.longitude);
}
function geocodeLatLng(geocoder, map, infowindow,lat,longi) {
var latlng = {lat: parseFloat(lat), lng: parseFloat(longi)};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
x.innerHTML = "Your Location is : " + results[0].formatted_address;
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
function myMap(lat, longi) {
var myCenter = new google.maps.LatLng(lat, longi);
var mapCanvas = document.getElementById("map");
var mapOptions = {
center : myCenter,
zoom : 20
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position : myCenter
});
marker.setMap(map);
google.maps.event.addListener(marker,'click',function() {
var infowindow = new google.maps.InfoWindow({
content:"You"
});
infowindow.open(map,marker);
});
}
var countryStateInfo = {
"Madhya Pradesh": {
"Indore": {
"Aanand bazar": [],
"Anoop Nagar": [],
"Bangali": [],
"Palasiya": [],
"Regal": [],
"Rajwada": [],
"vijay nagar": []
},
"Dewas": {
"rto" : []
},
"Ujjain": {
"Ujjain":[]
}
}
}
function func() {
//Get html elements
var stateSel = document.getElementById("state");
var citySel = document.getElementById("city");
//Load state
for (var country in countryStateInfo) {
stateSel.options[stateSel.options.length] = new Option(country, country);
}
//state Changed
stateSel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var city in countryStateInfo[this.value]) {
citySel.options[citySel.options.length] = new Option(city, city);
}
}
}
function fetchlocat(){
var locat = document.getElementById("locat").value;
if(locat=="yes"){
document.getElementById("t1").innerHTML ="";
document.getElementById("t2").innerHTML ="";
document.getElementById("t3").innerHTML ="";
document.getElementById("t4").innerHTML ="";
document.getElementById("t5").innerHTML ="";
document.getElementById("t6").innerHTML ="";
document.getElementById("t7").innerHTML ="";
document.getElementById("fsearch").innerHTML ="<td style='padding:8px;'>"+
"<input type='button' class='form-submit' value='Search' onclick='fetchPoint()'></td>";
}
if(locat=="no"){
document.getElementById("t1").innerHTML ="State";
document.getElementById("t2").innerHTML ="<select id='state' name='state' class='form-control' required='required'>"+
"<option value='' selected='selected'>-- Select State --</option>"+
"</select>";
document.getElementById("t3").innerHTML ="City";
document.getElementById("t4").innerHTML ="<select id='city' name='city' class='form-control' required='required'>"+
"<option value='' selected='selected'>-- Select City --</option>"+
" </select>";
document.getElementById("t5").innerHTML ="Area";
document.getElementById("t6").innerHTML ="<input type='text' id='area' name='area' class='form-control' required='required'>";
document.getElementById("t7").innerHTML ="<input type='button' class='form-submit' value='Search' onclick='fetchPointbyarea()'>";
func();
document.getElementById("fsearch").innerHTML ="";
}
}
function fetchServices(cid) {
$('#existingServices').find("option").remove();
$.ajax({
url : "fetchServicesForUser?cid=" + cid,
async : false,
type : "GET",
dataType : "json",
success : function(data) {
document.getElementById("existingServices").innerHTML = "<option value=''>Select</option>";
$.each(data, function(key, value) {
$('#existingServices').append(
$(
"<option ></option>").attr('value',
value).text(value));
});
}
});
}
var locationsPointSpName = [];
var locationsPointLati = [];
var locationsPointLongi = [];
var locationsPointSpMobile = [];
var spId=[];
var spfname=[];
var splname=[];
var spemail=[];
var spmobile=[];
var spaddress=[];
var spservice=[];
var spimg=[];
var spstatus=-1;
function fetchPoint() {
locationsPointSpName = [];
locationsPointLati = [];
locationsPointLongi = [];
locationsPointSpMobile = [];
var e = document.getElementById("existingServices");
var service = e.options[e.selectedIndex].text;
alert("fetch Start in home js");
$.ajax({
url : "fetchLocationOfsp?service=" + service + "&latitude="
+ lati + "&longitude=" + longi,
async : false,
type : "GET",
dataType : "json",
success : function(data) {
var sp="<h2>    Available Service Providers</h2><table><thead><tr></tr></thead>";
$.each(data, function(key, value) {
// myMap(value.latitude, value.longitude);
locationsPointSpName.push(value.firstName);
locationsPointLati.push(value.latitude);
locationsPointLongi.push(value.longitude);
locationsPointSpMobile.push(value.mobileNumber);
showPoint(service);
spstatus=spstatus+1;
spId.push(value.spId);
spfname.push(value.firstName);
splname.push(value.lastName);
spemail.push(value.email);
spmobile.push(value.mobileNumber);
spaddress.push(value.address);
spservice.push(service);
spimg.push(value.img);
sp=sp+"<tr id='myProfileBtn' onclick=onrowclick("+spstatus+")><td><img height='100' width='100' src='data:image/jpg;base64,"+value.img+"'/></td><td><h3 style='color: blue'>Service Provider for "+service+"</h3>";
var s=0;
for(var r=1;r<=5;r++){
if(r<=value.avgrating){
sp=sp+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}else{
if((r-1)==value.avgrating){
s=1;
}
if(s==1){
sp=sp+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}
if(s==0){
if((value.avgrating>=((r-1)+.3))&&(value.avgrating<=((r-1)+.8))){
sp=sp+"<i class='fa fa-star-half-full' style='font-size:20px;color:orange'></i>";
}if(value.avgrating<((r-1)+.3)){
sp=sp+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}if(value.avgrating>((r-1)+.8)){
sp=sp+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}
s=1;
}
}
}
sp=sp+"  Average Rating: "+value.avgrating+",<br>              <button id='myReviewBtn' onclick=onReview("+value.spId+","+spstatus+")>Reviews</button>           <button id='myBtn' onclick=onbtn("+value.latitude+","+value.longitude+",'"+String(value.firstName)+"','"+String(value.mobileNumber)+"')>Show on Map</button><br>"+
value.firstName+" "+value.lastName+" <br> Email Id : "+value.email+"<br>"+value.address+" - "+value.mobileNumber+"<br>Open time 10Am and Closed time 8Pm </td></tr>";
});
sp=sp+"</table>";
document.getElementById("spdetails").innerHTML = sp;
if(data==""){
getLocation();
document.getElementById("spdetails").innerHTML = "<h2 style='margin-left: 6%;'>Service Prvoiders Are Not Available</h2>";
}
}
});
}
function fetchPointbyarea(){
locationsPointSpName = [];
locationsPointLati = [];
locationsPointLongi = [];
locationsPointSpMobile = [];
document.getElementById("spdetails").innerHTML = "";
alert("fetchPointbyarea");
var e = document.getElementById("existingServices");
var service = e.options[e.selectedIndex].text;
var a = document.getElementById("state");
var state = a.options[a.selectedIndex].text;
var b = document.getElementById("city");
var city = b.options[b.selectedIndex].text;
var area=document.getElementById("area").value;
$.ajax({
url : "fetchLocationOfsp?service=" + service + "&state="
+ state + "&city=" + city+"&area="+area,
async : false,
type : "GET",
dataType : "json",
success : function(data) {
var sp="<h2>    Available Service Providers</h2><table><thead><tr></tr></thead>";
$.each(data, function(key, value) {
// myMap(value.latitude, value.longitude);
locationsPointSpName.push(value.firstName);
locationsPointLati.push(value.latitude);
locationsPointLongi.push(value.longitude);
locationsPointSpMobile.push(value.mobileNumber);
showPoint(service);
spstatus=spstatus+1;
spId.push(value.spId);
spfname.push(value.firstName);
splname.push(value.lastName);
spemail.push(value.email);
spmobile.push(value.mobileNumber);
spaddress.push(value.address);
spservice.push(service);
spimg.push(value.img);
sp=sp+"<tr><td><img height='100' width='100' src='data:image/jpg;base64,"+value.img+"'/></td><td><h3 style='color: blue'>Service Provider for "+service+"</h3>";
var s=0;
for(var r=1;r<=5;r++){
if(r<=value.avgrating){
sp=sp+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}else{
if((r-1)==value.avgrating){
s=1;
}
if(s==1){
sp=sp+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}
if(s==0){
if((value.avgrating>=((r-1)+.3))&&(value.avgrating<=((r-1)+.8))){
sp=sp+"<i class='fa fa-star-half-full' style='font-size:20px;color:orange'></i>";
}if(value.avgrating<((r-1)+.3)){
sp=sp+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}if(value.avgrating>((r-1)+.8)){
sp=sp+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}
s=1;
}
}
}
sp=sp+"  Average Rating: "+value.avgrating+",<br>              <button id='myReviewBtn' onclick=onReview("+value.spId+","+spstatus+")>Reviews</button>           <button id='myBtn' onclick=onbtn("+value.latitude+","+value.longitude+",'"+String(value.firstName)+"','"+String(value.mobileNumber)+"')>Show on Map</button><br>"+
value.firstName+" "+value.lastName+" <br> Email Id : "+value.email+"<br>"+value.address+" - "+value.mobileNumber+"<br>Open time 10Am and Closed time 8Pm </td></tr>";
});
sp=sp+"</table>";
document.getElementById("spdetails").innerHTML = sp;
if(data==""){
getLocation();
document.getElementById("spdetails").innerHTML = "<h2 style='margin-left: 6%;'>Service Prvoiders Are Not Available</h2>";
}
}
});
}
function showPoint(service)
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(lati, longi),
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var icon1;
var servicen = document.getElementById("servicename").value;
for (i = -1; i < locationsPointLati.length; i++) {
if(servicen=="Mobile Phones"){
alert(match);
icon1 = {url: "resources/images/locationlogo/mobilelogo.png",
scaledSize: new google.maps.Size(40, 40)
};
}
if(servicen=="Bata"){
icon1 = {url: "resources/images/locationlogo/batalogo.jpg",
scaledSize: new google.maps.Size(40, 40)
};
}
if(servicen=="vegetable"){
icon1 = {url: "resources/images/locationlogo/vegetable.jpg",
scaledSize: new google.maps.Size(40, 40)
};
}
if(servicen=="Dentist"){
icon1 = {url: "resources/images/locationlogo/Dentist.png",
scaledSize: new google.maps.Size(40, 40)
};
}
if(i==-1){
locationsPointLati[i]=lati;
locationsPointLongi[i]=longi;
icon1=null;
}
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationsPointLati[i], locationsPointLongi[i]),
map: map,
icon:icon1
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
if(i==-1){
infowindow.setContent("<b>You</b>");
}else{
infowindow.setContent("Name: <b>"+locationsPointSpName[i]+"</b> \n Mob No: <b>"+locationsPointSpMobile[i]+"</b><input type='hidden' id='a"+i+"' name='b"+i+"' value='"+locationsPointLati[i]+"'><input type='hidden' id='c"+i+"' name='d"+i+"' value='"+locationsPointLongi[i]+"'>");
}infowindow.open(map, marker);
}
})(marker, i));
//google.maps.event.addDomListener(document.getElementById('routebtn'), 'click', calcRoute(locationsPointLati[i],locationsPointLongi[i]));
}
}
function onReview(id,status){
//alert(spfname[status]+" "+spemail[status]+" "+splname[status]+" "+spmobile[status]+" "+spaddress[status]+" "+spservice[status]+" "+spimg[status]);
var e = document.getElementById("categoryId");
var Category = e.options[e.selectedIndex].text;
rmodal.style.display = "block";
$.ajax({
url : "fetchReview?id=" + id,
async : false,
type : "POST",
dataType : "json",
success : function(data) {
var i=0;
var content="<h3 style='color: blue;margin-left:36px;'>Category >> "+Category+" >> "+spservice[status]+"</h3>"+
"<table style=' width: 50%;border: 1px solid black;'><thead><tr></tr></thead><tr><td><img height='110' width='110' src='data:image/jpg;base64,"+spimg[status]+"'/></td><td>Category is : "+spservice[status]+"<br>"+
"Service Provider is : "+spfname[status]+" "+splname[status]+"<br>"+
"Contact Number : "+spmobile[status]+"<br>"+
"Email Address : "+spemail[status]+"<br>"+
"Address : "+spaddress[status]+"</td></tr></table>";
var addreview="<div>"+
"<input type='button' value='Add Review' id='addReviewBtn' onclick='Review("+id+","+status+")'><span id='linkoflogger'></span>"+
"</div>";
var maincontent=content;
content=content+"<br>"+addreview+"<table style=' width: 60%;border: 1px solid black;'><tr><th>User</th><th>Comment</th><th>Rating</th></tr>";
$.each(data, function(key, value) {
//for user Details
$.ajax({
url : "fetchUser?userId="+value.userId,
async : false,
type : "POST",
dataType : "json",
success : function(user){
content=content+"<tr><td> "+user.firstName+" "+user.lastName+" </td></h4><br>";
content=content+"<h4><td>"+value.review+"</td><td>";
var s=0;
for(var r=1;r<=5;r++){
if(r<=value.rating){
content=content+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}else{
if((r-1)==value.rating){
s=1;
}
if(s==1){
content=content+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}
if(s==0){
if((value.rating>=((r-1)+.3))&&(value.rating<=((r-1)+.8))){
content=content+"<i class='fa fa-star-half-full' style='font-size:20px;color:orange'></i>";
}if(value.rating<((r-1)+.3)){
content=content+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}if(value.rating>((r-1)+.8)){
content=content+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}
s=1;
}
}
}
content=content+"</tr>";
}
});
});
document.getElementById("modal-body2").innerHTML =""+content+"</table><br><br><br><br><br><br><br><br><br><br><br><br><br><br>";
if(data.length==0){
document.getElementById("modal-body2").innerHTML =maincontent+"<h3>"+addreview+"<br>No Review</h3><br><br><br><br><br><br><br><br><br><br><br><br>";
}
}
});
}
var v1=0;var v2=0;var v3=0,v4=0,v5=0;
function ratingcheck(){
var v=v1+v2+v3+v4+v5;
return v;
}
function c1(){
if(v1==1){
v1=0;v2=0;v3=0;v4=0;v5=0;
document.getElementById("1").innerHTML="<span class='fa fa-star' onclick=c1()></span>";
document.getElementById("2").innerHTML="<span class='fa fa-star' onclick=c2()></span>";
document.getElementById("3").innerHTML="<span class='fa fa-star' onclick=c3()></span>";
document.getElementById("4").innerHTML="<span class='fa fa-star' onclick=c4()></span>";
document.getElementById("5").innerHTML="<span class='fa fa-star' onclick=c5()></span>";
}
else{
v1=1;
document.getElementById("1").innerHTML="<span class='fa fa-star checked' onclick=c1()></span>";
}
}
function c2(){
if(v2==1){
v2=0;v3=0;v4=0;v5=0;
document.getElementById("2").innerHTML="<span class='fa fa-star' onclick=c2()></span>";
document.getElementById("3").innerHTML="<span class='fa fa-star' onclick=c3()></span>";
document.getElementById("4").innerHTML="<span class='fa fa-star' onclick=c4()></span>";
document.getElementById("5").innerHTML="<span class='fa fa-star' onclick=c5()></span>";
}
else{
v1=1;v2=1;
document.getElementById("1").innerHTML="<span class='fa fa-star checked' onclick=c1()></span>";
document.getElementById("2").innerHTML="<span class='fa fa-star checked' onclick=c2()></span>";
}
}
function c3(){
if(v3==1){
v3=0;v4=0;v5=0;
document.getElementById("3").innerHTML="<span class='fa fa-star' onclick=c3()></span>";
document.getElementById("4").innerHTML="<span class='fa fa-star' onclick=c4()></span>";
document.getElementById("5").innerHTML="<span class='fa fa-star' onclick=c5()></span>";
}
else{
v3=1;v1=1;v2=1;
document.getElementById("1").innerHTML="<span class='fa fa-star checked' onclick=c1()></span>";
document.getElementById("2").innerHTML="<span class='fa fa-star checked' onclick=c2()></span>";
document.getElementById("3").innerHTML="<span class='fa fa-star checked' onclick=c3()></span>";
}
}
function c4(){
if(v4==1){
v4=0;v5=0;
document.getElementById("4").innerHTML="<span class='fa fa-star' onclick=c4()></span>";
document.getElementById("5").innerHTML="<span class='fa fa-star' onclick=c5()></span>";
}
else{
v4=1;v3=1;v1=1;v2=1;
document.getElementById("1").innerHTML="<span class='fa fa-star checked' onclick=c1()></span>";
document.getElementById("2").innerHTML="<span class='fa fa-star checked' onclick=c2()></span>";
document.getElementById("3").innerHTML="<span class='fa fa-star checked' onclick=c3()></span>";
document.getElementById("4").innerHTML="<span class='fa fa-star checked' onclick=c4()></span>";
}
}
function c5(){
if(v5==1){
v5=0;
document.getElementById("5").innerHTML="<span class='fa fa-star' onclick=c5()></span>";
}
else{
v5=1;v4=1;v3=1;v1=1;v2=1;
document.getElementById("1").innerHTML="<span class='fa fa-star checked' onclick=c1()></span>";
document.getElementById("2").innerHTML="<span class='fa fa-star checked' onclick=c2()></span>";
document.getElementById("3").innerHTML="<span class='fa fa-star checked' onclick=c3()></span>";
document.getElementById("4").innerHTML="<span class='fa fa-star checked' onclick=c4()></span>";
document.getElementById("5").innerHTML="<span class='fa fa-star checked' onclick=c5()></span>";
}
}
function Review(id,status){
addrevmodal.style.display = "block";
$.ajax({
url : "checkUserLogin",
async : false,
type : "POST",
dataType : "json",
success : function(data){
if(data!=0){
var ratingcontent="<div style='margin-left:2%;'><div id='1' style='float: left;'>"+
"<span class='fa fa-star' onclick=c1()></span></div>"+
"<div id='2' style='float: left;'>"+
"<span class='fa fa-star' onclick=c2()></span></div>"+
"<div id='3' style='float: left;'>"+
"<span class='fa fa-star' onclick=c3()></span></div>"+
"<div id='4' style='float: left;'>"+
"<span class='fa fa-star' onclick=c4()></span></div>"+
"<div id='5' style='float: left;'>"+
"<span class='fa fa-star' onclick=c5()></span></div></div><br>"+
"<br>";
var addreview="<div> "+
"<textarea rows='3' cols='30' name='rev' id='rev'>"+
"</textarea><br><br>"+ratingcontent+
"<br> <input type='button' value='Add Review' onclick='addReview("+id+","+data+","+status+")'></div>";
document.getElementById("modal-body3").innerHTML = addreview+"<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>";
}
if(data==0){
alert("first you have to login....");
addrevmodal.style.display = "none";
var addreview=" For Login <a class='logout' onclick='loginModal(this.id)' id='logininrev'>click here..</a>"+
" For Registration <a href='userRegistration'>click here..</a><br>";
document.getElementById("linkoflogger").innerHTML = addreview;
}
}
});
}
function addReview(spid,userid,status,ff){
var rating=ratingcheck();
var rev=document.getElementById("rev").value;
$.ajax({
url : "addReview?review="+rev+"&spId="+spid+"&userId="+userid+"&rating="+rating,
async : false,
type : "POST",
dataType : "json",
success : function(data){
alert(data+" with f "+ff);
addrevmodal.style.display = "none";
onReview(spid,status);
}
});
}
function onbtn(lati,longi,fname,m){
modal.style.display = "block";
var map = new google.maps.Map(document.getElementById('mapinmodal'), {
zoom: 10,
center: {lat: lati, lng: longi}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
geocodeLatLng2(geocoder, map, infowindow,lati,longi);
myMap2(lati,longi,fname,m);
}
function geocodeLatLng2(geocoder, map, infowindow,lat,longi) {
var latlng = {lat: parseFloat(lat), lng: parseFloat(longi)};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
//infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
function myMap2(lat, longii,fname,mobile) {
var myCenter = new google.maps.LatLng(lat, longii);
var mapCanvas = document.getElementById("mapinmodal");
var mapOptions = {
center : myCenter,
zoom : 18
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position : myCenter
});
marker.setMap(map);
google.maps.event.addListener(marker,'click',function() {
var infowindow = new google.maps.InfoWindow({
content:"<h3>Name : "+fname+", Mobile : "+mobile+"</h3>"
});
infowindow.open(map,marker);
});
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var start = new google.maps.LatLng(lati, longi);
var end = new google.maps.LatLng(lat, longii);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
} else {
alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
}
});
}
<file_sep>/nearbySystem/nearbySystem-nearby/src/main/webapp/resources/js/jsfunction.js
var countryStateInfo = {
"India": {
"Assam": {
"Dispur": [],
"Guwahati" : []
},
"Gujarat": {
"Vadodara" : [],
"Surat" : []
},
"Madhya Pradesh": {
"Indore" : [],
"Dewas" : [],
"Ujjain":[]
}
}
}
function func() {
//Get html elements
var stateSel = document.getElementById("state");
var citySel = document.getElementById("city");
//Load state
for (var country in countryStateInfo) {
stateSel.options[stateSel.options.length] = new Option(country, country);
}
//state Changed
stateSel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var city in countryStateInfo[this.value]) {
citySel.options[citySel.options.length] = new Option(city, city);
}
}
}
var countr = document.getElementById("country");
function fun() {
//Get html elements
var countySel = document.getElementById("country");
var stateSel = document.getElementById("state");
var citySel = document.getElementById("city");
//Load countries
for (var country in countryStateInfo) {
countySel.options[countySel.options.length] = new Option(country, country);
}
//County Changed
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var state in countryStateInfo[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
//State Changed
stateSel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var city in countryStateInfo[countySel.value][this.value]) {
citySel.options[citySel.options.length] = new Option(city, city);
}
}
}
function fetchServices(cid) {
$('#existingServices').find("option").remove();
$.ajax({
url : "fetchServicesForUser?cid=" + cid,
async : false,
type : "GET",
dataType : "json",
success : function(data) {
$('#existingServices').append("<option></option>");
$.each(data, function(key, value) {
$('#existingServices').append(
$(
"<option ></option>").attr('value',
value).text(value));
});
}
});
}
function getAddress() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
}
}
function showPosition(position) {
var lati = position.coords.latitude;
var longi = position.coords.longitude;
var latlng = new google.maps.LatLng(lati, longi);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
}
}
});
}
function fetchPoint() {
locationsPointSpName = [];
locationsPointLati = [];
locationsPointLongi = [];
locationsPointSpMobile = [];
var e = document.getElementById("existingServices");
var service = e.options[e.selectedIndex].text;
alert("fetch Start in js fun");
$.ajax({
url : "fetchLocationOfsp?service=" + service + "&latitude="
+ lati + "&longitude=" + longi,
async : false,
type : "GET",
dataType : "json",
success : function(data) {
var sp="<h2>    Available Service Providers</h2><table><thead><tr></tr></thead>";
$.each(data, function(key, value) {
// myMap(value.latitude, value.longitude);
locationsPointSpName.push(value.firstName);
locationsPointLati.push(value.latitude);
locationsPointLongi.push(value.longitude);
locationsPointSpMobile.push(value.mobileNumber);
showPoint(service);
sp=sp+"<tr><td><img height='100' width='100' src='data:image/jpg;base64,"+value.img+"'/></td><td><h3 style='color: blue'>Service Provider for "+service+"</h3>";
var s=0;
for(var r=1;r<=5;r++){
if(r<=value.avgrating){
sp=sp+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}else{
if((r-1)==value.avgrating){
s=1;
}
if(s==1){
sp=sp+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}
if(s==0){
if((value.avgrating>=((r-1)+.3))&&(value.avgrating<=((r-1)+.8))){
sp=sp+"<i class='fa fa-star-half-full' style='font-size:20px;color:orange'></i>";
}if(value.avgrating<((r-1)+.3)){
sp=sp+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}if(value.avgrating>((r-1)+.8)){
sp=sp+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}
s=1;
}
}
}
sp=sp+"Average Rating: "+value.avgrating+",<button id='myReviewBtn'>Reviews</button><br>"+
value.firstName+" "+value.lastName+" <br> Email Id : "+value.email+"<br>"+value.address+" - "+value.mobileNumber+"<br>Open time 10Am and Closed time 8Pm </td><td><button id='myBtn'>Show on Map</button></td</tr>";
});
sp=sp+"</table>";
document.getElementById("spdetails").innerHTML = sp;
if(data==""){
document.getElementById("spdetails").innerHTML = "<h2 style='margin-left: 6%;'>Service Prvoiders Are Not Available</h2>";
}
}
});
}
function fetchPointbyarea(){
alert("fetchPointbyarea");
locationsPointSpName = [];
locationsPointLati = [];
locationsPointLongi = [];
locationsPointSpMobile = [];
var e = document.getElementById("existingServices");
var service = e.options[e.selectedIndex].text;
var a = document.getElementById("state");
var state = a.options[a.selectedIndex].text;
var b = document.getElementById("city");
var city = b.options[b.selectedIndex].text;
var area=document.getElementById("area").value;
alert("fetch Start ");
$.ajax({
url : "fetchLocationOfsp?service=" + service + "&state="
+ state + "&city=" + city+"&area="+area,
async : false,
type : "GET",
dataType : "json",
success : function(data) {
var sp="<h2>    Available Service Providers</h2><table><thead><tr></tr></thead>";
$.each(data, function(key, value) {
// myMap(value.latitude, value.longitude);
locationsPointSpName.push(value.firstName);
locationsPointLati.push(value.latitude);
locationsPointLongi.push(value.longitude);
locationsPointSpMobile.push(value.mobileNumber);
showPoint(service);
sp=sp+"<tr><td><img height='100' width='100' src='data:image/jpg;base64,"+value.img+"'/></td><td><h3 style='color: blue'>Service Provider for "+service+"</h3>";
var s=0;
for(var r=1;r<=5;r++){
if(r<=value.avgrating){
sp=sp+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}else{
if((r-1)==value.avgrating){
s=1;
}
if(s==1){
sp=sp+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}
if(s==0){
if((value.avgrating>=((r-1)+.3))&&(value.avgrating<=((r-1)+.8))){
sp=sp+"<i class='fa fa-star-half-full' style='font-size:20px;color:orange'></i>";
}if(value.avgrating<((r-1)+.3)){
sp=sp+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}if(value.avgrating>((r-1)+.8)){
sp=sp+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}
s=1;
}
}
}
sp=sp+"Average Rating: "+value.avgrating+",<button id='myReviewBtn'>Reviews</button><br>"+
value.firstName+" "+value.lastName+" <br> Email Id : "+value.email+"<br>"+value.address+" - "+value.mobileNumber+"<br>Open time 10Am and Closed time 8Pm </td><td><button id='myBtn'>Show on Map</button></td</tr>";
});
sp=sp+"</table>";
document.getElementById("spdetails").innerHTML = sp;
if(data==""){
document.getElementById("spdetails").innerHTML = "<h2 style='margin-left: 6%;'>Service Prvoiders Are Not Available</h2>";
}
}
});
}
function onReview(id,status){
alert("on review invoked");
//alert(spfname[status]+" "+spemail[status]+" "+splname[status]+" "+spmobile[status]+" "+spaddress[status]+" "+spservice[status]+" "+spimg[status]);
var e = document.getElementById("cid");
var Category = e.options[e.selectedIndex].text;
rmodal.style.display = "block";
$.ajax({
url : "fetchReview?id=" + id,
async : false,
type : "POST",
dataType : "json",
success : function(data) {
var i=0;
var content="<h3 style='color: blue;margin-left:36px;'>Category >> "+Category+" >> "+spservice[status]+"</h3>"+
"<table style=' width: 50%;border: 1px solid black;'><thead><tr></tr></thead><tr><td><img height='110' width='110' src='data:image/jpg;base64,"+spimg[status]+"'/></td><td>Category is : "+spservice[status]+"<br>"+
"Service Provider is : "+spfname[status]+" "+splname[status]+"<br>"+
"Contact Number : "+spmobile[status]+"<br>"+
"Email Address : "+spemail[status]+"<br>"+
"Address : "+spaddress[status]+"</td></tr></table>";
var maincontent=content;
content=content+"<table style=' width: 60%;border: 1px solid black;'><tr><th style='border: 1px solid black;'>Comment No.</th><th style='border: 1px solid black;'>Comment</th><th style='border: 1px solid black;'>Rating</th></tr>";
$.each(data, function(key, value) {
i++;
content=content+"<tr><h4><td style='border: 1px solid black;'> "+i+". </td><td style='border: 1px solid black;'>"+value.review+" </td><td style='border: 1px solid black;'>";
var s=0;
for(var r=1;r<=5;r++){
if(r<=value.rating){
content=content+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}else{
if((r-1)==value.rating){
s=1;
}
if(s==1){
content=content+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}
if(s==0){
if((value.rating>=((r-1)+.3))&&(value.rating<=((r-1)+.8))){
content=content+"<i class='fa fa-star-half-full' style='font-size:20px;color:orange'></i>";
}if(value.rating<((r-1)+.3)){
content=content+"<span class='fa fa-star' style='font-size:20px;color:Gainsboro'></span>";
}if(value.rating>((r-1)+.8)){
content=content+"<span class='fa fa-star checked' style='font-size:20px;color:orange'></span>";
}
s=1;
}
}
}
content=content+"   "+value.rating+"</td></h4></tr><br>";
});
document.getElementById("modal-body2").innerHTML =""+content+"</table><br><br><br><br><br><br><br><br><br><br><br><br><br><br>";
if(data.length==0){
document.getElementById("modal-body2").innerHTML =maincontent+"<h3><br>No Review</h3><br><br><br><br><br><br><br><br><br><br><br><br>";
}
}
});
}
<file_sep>/nearbySystem/nearbySystem-dal/src/main/java/org/nearby/dto/JobCategory.java
package org.nearby.dto;
public class JobCategory {
private Integer jobCategoryId;
private String subCategory;
private String job;
public Integer getJobCategoryId() {
return jobCategoryId;
}
public void setJobCategoryId(Integer jobCategoryId) {
this.jobCategoryId = jobCategoryId;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getSubCategory() {
return subCategory;
}
public void setSubCategory(String subCategory) {
this.subCategory = subCategory;
}
}
<file_sep>/nearbySystem/nearbySystem-dal/src/main/java/org/nearby/dto/EmployerRegistration.java
package org.nearby.dto;
import java.sql.Date;
public class EmployerRegistration {
private String name;
private String password;
private String mobileNumber;
private Date dob;
private String address;
private String state;
private String city;
private String type;
private String email;
private Integer isActive;
private Integer isDeleted;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getIsActive() {
return isActive;
}
public void setIsActive(Integer isActive) {
this.isActive = isActive;
}
public Integer getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Integer isDeleted) {
this.isDeleted = isDeleted;
}
}
<file_sep>/nearbySystem/nearbySystem-dal/src/main/java/org/nearby/dto/ServiceDto.java
package org.nearby.dto;
public class ServiceDto {
private Integer subcategoryId;
private Integer categoryId;
private String service;
private String type;
public Integer getSubcategoryId() {
return subcategoryId;
}
public void setSubcategoryId(Integer subcategoryId) {
this.subcategoryId = subcategoryId;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
<file_sep>/nearbySystem/nearbySystem-dal/src/main/java/org/nearby/dao/Main.java
package org.nearby.dao;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import org.nearby.dto.GoogleResponse;
import org.nearby.dto.Result;
public class Main {
private static final String URL = "http://maps.googleapis.com/maps/api/geocode/json";
public GoogleResponse convertToLatLong(String fullAddress) throws IOException {
URL url = new URL(URL + "?address=" + URLEncoder.encode(fullAddress, "UTF-8") + "&sensor=false");
// Open the Connection
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
ObjectMapper mapper = new ObjectMapper();
GoogleResponse response=null;
try{
response = (GoogleResponse) mapper.readValue(in, GoogleResponse.class);
}catch(Exception e){
}
in.close();
return response;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
List<String> list= new ArrayList<String>();
String address="vijay nagar"+",Indore"+",Madhya Pradesh 452010,"+"India";
GoogleResponse res = new AddressConverter().convertToLatLong(address);
if (res.getStatus().equals("OK")) {
for (Result result : res.getResults()) {
System.out.println("Lattitude of address is :" + result.getGeometry().getLocation().getLat());
System.out.println("Longitude of address is :" + result.getGeometry().getLocation().getLng());
System.out.println("Location is " + result.getGeometry().getLocation_type());
list.add(result.getGeometry().getLocation().getLat());
list.add(result.getGeometry().getLocation().getLng());
}
}
System.out.println(list);
}
}
| d09f00cbe977b42f944dd7a6fe42347cbdbf2dbe | [
"SQL",
"Markdown",
"JavaScript",
"Maven POM",
"INI",
"Java"
]
| 18 | Java | Vipin77/Java-Solution-NearBySystem | 0346475fd32c475aca4145c678cf5de3bbff0951 | b6d90c94c94b7670164a1b7d73a7b19f6351dec8 |
refs/heads/master | <file_sep>
public class Queue<E> {
private CLinkedListCore<E> list;
public Queue() {
list = new CLinkedListCore<E>();
}
public void enqueue(E e) {
list.add(e);
}
public E dequeue() {
return list.remove(0);
}
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
}
<file_sep>
public class BinaryTree {
private BinaryTreeNode root;
public void inOrder(BinaryTreeNode ref) {
if (ref != null) {
inOrder(ref.getLeft());
System.out.println(ref.getData());
inOrder(ref.getRigth());
}
}
}
| 61592ff59fdfdb7dd59bad1cef90201732da42af | [
"Java"
]
| 2 | Java | TheBell/RandomClasses | 083630f550b802c043ecaa9676ff8b10734457f8 | 75e2205a4d4963515ea06c03e878131a957798b4 |
refs/heads/master | <repo_name>PhilChodrow/largest_submatrix<file_sep>/algs/algorithms.py
import numpy as np
from scipy.optimize import minimize, Bounds
def submatrix(A, ix):
'''
Get the submatrix corresponding to a given set of row and column indices.
A: a 2d np.array
ix: dict of the form {'rows' : np.array([1, 2, 3, 4]),
'columns' : np.array([1, 2, 3, 4])}
'''
return A[ix['rows'][:, np.newaxis], ix['columns']]
def value(A, ix):
'''
Get the value (average) of a submatrix corresponding to a given set of row
and column indices.
A: a 2d np.array
ix: dict of the form {'rows' : np.array([1, 2, 3, 4]),
'columns' : np.array([1, 2, 3, 4])}
'''
return np.mean(submatrix(A, ix))
def inclusion_matrix(A, ix):
m, n = A.shape
x = np.zeros(m)
y = np.zeros(n)
x[ix['rows']] = 1
y[ix['columns']] = 1
return np.outer(x,y)
def LAS(A, k):
'''
Algorithm LAS from https://arxiv.org/pdf/1602.08529.pdf
A: a 2d np.array
k: a positive integer
'''
m, n = A.shape
# given a fixed set of row indices, find the k columns whose sums
# in those indices are largest.
def column_update():
sums = A[ix['rows'],:].sum(axis = 0) # restrict to given row indices
new_ix = np.argpartition(-sums, k)[0:k] # find k largest restricted cols
ix['columns'] = new_ix # replace old indices with new
# given a fixed set of column indices, find the k rows whose sums
# in those indices are largest.
def row_update():
sums = A[:, ix['columns']].sum(axis = 1) # restrict to given column indices
new_ix = np.argpartition(-sums, k)[0:k] # find the k largest restricted rows
ix['rows'] = new_ix # replace old indices with new
# randomly initialize indices
ix = {'rows' : np.random.choice(m, k, replace=False),
'columns' : np.random.choice(n, k, replace=False)}
# initialize loop parameters.
prev_val = -10**(8)
val = 0
eps = 10**(-8) # tolerance: when improvement in val is less than this, stop.
# main loop
while np.abs(val - prev_val) > eps:
prev_val = val
row_update()
column_update()
val = value(A, ix)
# return result as dict, including the indices and the value.
return({'ix' : ix, 'val': val})
def IGP(A, k):
'''
Algorithm IGP from https://arxiv.org/pdf/1602.08529.pdf
A: a 2d np.array
k: a positive integer
'''
m, n = A.shape
# partition the row and column indices into k+1 approximately-equal segments
# R_i and C_i for i in 1...k+1
row_part = range(0, m+1, m/k)
col_part = range(0, n+1, n/k)
# fixing current row indices, search through the columns within C_i the the one
# that most increases the value.
def column_update(i):
C_i = np.arange(col_part[i-1], col_part[i]) # grab C_i
A_sub = submatrix(A, # restrict to columns in C_i
{'rows' : ix['rows'], # and rows in ix
'columns': C_i})
new = np.argmax(A_sub.sum(axis = 0)) # index of best addition in C_i
# add best addition to ix
ix['columns'] = np.append(ix['columns'],
C_i[new]).astype('int')
def row_update(i):
R_i = np.arange(row_part[i-1], row_part[i]) # grab R_i
A_sub = submatrix(A, # restrict to rows in R_i
{'rows' : R_i, # and columns in ix
'columns': ix['columns']})
new = np.argmax(A_sub.sum(axis = 1)) # index of best addition in R_i
# add best addition to ix
ix['rows'] = np.append(ix['rows'],
R_i[new]).astype('int')
# initialize
ix = {'rows' : np.random.choice(row_part[1], 1),
'columns' : []}
column_update(1)
i = 2
# main loop
while i <= k:
row_update(i)
column_update(i)
i += 1
# output as dict including indices and value
return {'ix': ix,
'val': value(A, ix)}
def round_off(x, k):
x_ind = np.argpartition(x, -k)[-k:]
x = np.zeros(x.shape)
x[x_ind] = 1
return x
def continuous_SLSQP(A, k, print_obj = False):
m, n = A.shape
# objective function
def f(z):
val = np.dot(np.dot(z[:m], A, ), z[m:]) / (k**2)
if print_obj:
print val
return -val
# objective gradient
def jac(z):
return -np.concatenate((np.dot(A, z[m:]), np.dot(z[:m], A))) / (k**2)
# constraints
e_x = np.concatenate((np.ones(m), np.zeros(n)))
e_y = np.concatenate((np.zeros(m), np.ones(n)))
bnds = Bounds(0, 1)
cons = ({'type': 'ineq', 'fun': lambda z: k - z[:m].sum(), 'jac' : lambda z: -e_x},
{'type': 'ineq', 'fun': lambda z: k - z[m:].sum(), 'jac' : lambda z: -e_y})
# random start
x_0 = np.random.rand(m)
y_0 = np.random.rand(n)
x_0 = k*x_0 / x_0.sum()
y_0 = k*y_0 / y_0.sum()
z_0 = np.concatenate((x_0, y_0))
# perform optimization
res = minimize(f,
z_0,
method='SLSQP',
bounds = bnds,
constraints = cons,
jac = jac,
options = {'disp': True})
z = res['x']
x = z[:m]
y = z[m:]
x = round_off(x, k)
y = round_off(y, k)
return {'x' : x, 'y' : y, 'val' : np.dot(np.dot(x, A), y) / (k**2)}
<file_sep>/algs/int_prog.py
import numpy as np
from docplex.mp.model import Model
import utils
def int_programming(data,k):
m,n = data.shape
print(m,n)
# Create CPLEX model
mdl = Model(name='IP')
# Create m*n + m + n binary decision variables for every matrix entry and every row and column respectively
x = mdl.binary_var_list(m*n,name="X")
R = mdl.binary_var_list(m,name="R")
C = mdl.binary_var_list(n,name="C")
# Add the constaints that only k rows and columns can be selected
s_R = mdl.sum(R)
s_C = mdl.sum(C)
mdl.add_constraint(s_R==k)
mdl.add_constraint(s_C==k)
# Enforce that the selected matrix entries correspond to the selected rows and columns
row_sums = [sum(x[i*n:i*n+n]) for i in range(m)]
col_sums = [sum([x[n*i+j] for i in range(m)]) for j in range(n)]
row_constraints = [row_sums[i] == k*R[i] for i in range(m)]
col_constraints = [col_sums[i] == k*C[i] for i in range(n)]
mdl.add_constraints(row_constraints)
mdl.add_constraints(col_constraints)
# Maximize the size of the submatrix
obj = mdl.sum([x[n*i+j]*data[i,j] for i in range(m) for j in range(n)])
mdl.maximize(obj)
# Solve the integer programming and print results
sol = mdl.solve()
mdl.print_solution()
mdl.report_kpis()
return sol
'''
Example Usage
d = utils.read_data('chr1_chr2.txt')
d = np.asarray(d)
sol = int_programming(d,9)
'''
<file_sep>/README.md
# Largest Submatrix
Course project on largest submatrix problems.
<file_sep>/algs/utils.py
import numpy as np
def read_data(path, clean_nan = False):
m = np.loadtxt(path)
m[:,0:2] = m[:,0:2] / (2.5*10**5)
ix = m[:,0:2].astype('int')
container = np.zeros((max(ix[:,0])+1,
max(ix[:,1])+1))
for i in range(ix.shape[0]):
ix_i = ix[i,:]
container[ix_i[0], ix_i[1]] = m[i,2]
if clean_nan:
container = np.nan_to_num(container)
return container
| b1f8271cabc4df04a09348a14f9811aeb23bfd9c | [
"Markdown",
"Python"
]
| 4 | Python | PhilChodrow/largest_submatrix | 53c3a8289fd71538de003df652d6f29dfc8857b1 | c8d8eedbe7dbe772e968d8295a7a0055caa42380 |
refs/heads/master | <repo_name>rogcolaco/backend-nodejs-tc2<file_sep>/app/controller/car.controller.js
const db = require("../model");
const Car = db.car;
exports.add = (req, res) => {
if(!req.body.plate){
res.status(400).send({msg: "Informar a placa do carro."});
return;
}
const car = new Car( {
model: req.body.model,
color: req.body.color,
plate: req.body.plate,
km: req.body.km,
});
car.save(car).then(data => {
res.status(200).send({msg: "Novo Veículo cadastrado."});
/* res.send(data); */
})
};
exports.findAll = (req, res) => {
var condition = {};
Car.find(condition).then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({ msg: "Erro ao obter lista de veículos." })
});
};
exports.find = (req, res) => {
const id = req.params.id;
Car.findById(id).then(data => {
if (!data) {
res.status(404).send({ msg: "Veículo não cadastrado." });
} else {
res.send(data);
}
}).catch(err => {
res.status(500).send({ msg: "Erro ao obter dados do veículo com id = " + id })
});
};
exports.delete = (req, res) => {
const id = req.params.id;
Car.findByIdAndRemove(id).then(data => {
if (!data) {
res.status(400).send({ msg: "Não foi possível remover o Veículo" })
} else {
res.send({ msg: "Veículo deletado com sucesso" });
}
}).catch(err => {
res.status(500).send({ msg: "Erro ao deletar o Veículo" });
});
};
exports.update = (req, res) => {
if (!req.body) {
res.status(400).send({ msg: "Dados inválidos" });
return;
}
const id = req.params.id;
Car.findByIdAndUpdate(id, req.body).then(data => {
if (!data) {
res.status(400).send({ msg: "Não foi possível atualizar os dados do Veículo" })
} else {
res.send({ msg: "Veículo atualizado com sucesso" });
}
}).catch(err => {
res.status(500).send({ msg: "Erro ao atualizar os dados do veículo" });
});
}; <file_sep>/app/model/car.model.js
module.exports = mongoose => {
const Car = mongoose.model(
"car",
mongoose.Schema({
model: String,
color: String,
plate: String,
km: Number
},
{ timestamps: true }
));
return Car;
};<file_sep>/app/routes/car.routes.js
module.exports = app => {
const car = require("../controller/car.controller.js");
var router = require("express").Router();
router.post("/", car.add);
router.get("/", car.findAll);
router.get("/:id", car.find);
router.put("/:id", car.update);
router.delete("/:id", car.delete);
app.use('/api/cars', router);
};<file_sep>/README.md
# Definições gerais do projeto
Esse repositório foi criado como parte dos estudos da disciplina de Tópicos de Computação 2 (TC2) do curso de análise e desenvolvimento de sistemas
do Instituto Federa de Ciência e Tecnologia de São Paulo Campus São Carlos.
Trata-se de um backend simples feito utilizando NodeJS e o framework express e tem como objetivo realizar as operções de CRUD para cadastro de veículos.
## Rotas disponívels
/api/cars
- GET: Retorna todos os veículos cadastrados
- POST: Cadastra um novo veículo
-- itens requeridos:
--- model: string contendo o modelo do veículo
--- plate: string com a placa do veículo
--- color: string com a cor do veículo
--- km: numero de kilometros rodados do veículo
/api/cars/:id
- GET: Busca o veículo com o ID informado
- PUT: Altera o veículo com o ID informado
- DELETE: Deleta o veículo com o ID informado
<file_sep>/index.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
var corsOptions = {
origin:"*",
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get("/", (req, res) => {
res.json({
msg: "O backend está funcionando!!!!"
})
});
const db = require("./app/model");
db.mongoose.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Conectado ao banco de dados");
}).catch(err => {
console.log ("houve um erro: " + err);
process.exit();
});
require("./app/routes/car.routes")(app);
app.listen(8080, () => {
console.log("O servidor está funcionando");
}); | 865046ec4982126f190613f957c970c92ee034ed | [
"JavaScript",
"Markdown"
]
| 5 | JavaScript | rogcolaco/backend-nodejs-tc2 | 69d492e74c60dffcd282038789d2542e5399b47f | f11933f6016eabc66543e0cf4443f439ac49a78a |
refs/heads/master | <repo_name>zhangwei5095/JavaDocManager<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/fixes/GenerateFromClass.java
package com.perniciouspenguins.ideaz.javadoc.fixes;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElementFactory;
import com.intellij.util.IncorrectOperationException;
import com.perniciouspenguins.ideaz.javadoc.templates.JavaDocGenerator;
import com.perniciouspenguins.ideaz.javadoc.util.PsiUtils;
import org.jetbrains.annotations.NotNull;
/**
* Class GenerateFromClass offers the ability to generate a plain JavaDoc declaration for a class that does not already
* declare one.
*
* author: <NAME> date: Sat Jan 20 22:08:09 CET 2007
*/
public class GenerateFromClass extends LocalQuickFixBase
{
/**
* Method LocalQuickFixBase creates a new instance of a Quick fix for a class that does not have JavaDoc.
*
* @param psiClass the class to which the quick fix applies.
*/
public GenerateFromClass( PsiClass psiClass )
{
super( psiClass );
}
/**
* Returns the name of the quick fix.
*
* @return the name of the quick fix.
*/
@NotNull
public String getName()
{
if( psiClass != null )
{
if( psiClass.isInterface() )
{
return FIX_GENERATE_FROM_INTERFACE;
}
else if( psiClass.isEnum() )
{
return FIX_GENERATE_FROM_ENUM;
}
}
return FIX_GENERATE_FROM_CLASS;
}
/**
* Method doFix returns the actual fix that needs to be executed to solve the detected problem.
*/
public void doFix()
{
try
{
PsiElementFactory factory =
JavaPsiFacade.getInstance( psiClass.getProject() ).getElementFactory();
String javaDocTemplateText = JavaDocGenerator.generateJavaDoc( psiClass );
if( !psiClass.isEnum() )
{
PsiUtils.setPsiDocComment(
factory.createDocCommentFromText( javaDocTemplateText ),
psiClass );
}
else
{
PsiUtils.setPsiDocComment( factory.createDocCommentFromText( javaDocTemplateText ),
psiClass );
}
}
catch( IncorrectOperationException e )
{
e.printStackTrace();
}
}
}
<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/fixes/GenerateForAllMethods.java
package com.perniciouspenguins.ideaz.javadoc.fixes;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiMethod;
import com.intellij.util.IncorrectOperationException;
import com.perniciouspenguins.ideaz.javadoc.templates.JavaDocGenerator;
import com.perniciouspenguins.ideaz.javadoc.util.PsiUtils;
import org.jetbrains.annotations.NotNull;
/**
* The GenerateForAllMethods class offers the ability to generate
* a JavaDoc declaration for all methods that don't specify JavaDoc.
*
* Author: <NAME>
* Date: May 14, 2007 10:00:23 PM
*/
public class GenerateForAllMethods extends LocalQuickFixBase
{
/**
* Method LocalQuickFixBase creates a new instance of a Quick fix for a method that does not
* have a parent method.
*
* @param psiClass the psiClass to which the quick fix applies.
*/
public GenerateForAllMethods( PsiClass psiClass )
{
super( psiClass );
}
/**
* Returns the name of the quick fix.
*
* @return the name of the quick fix.
*/
@NotNull
public String getName()
{
return FIX_GENERATE_FOR_ALL_METHODS;
}
/**
* Method doFix returns the actual fix that needs to be executed to solve the
* detected problem.
*/
public void doFix()
{
PsiMethod[] psiMethods = psiClass.getMethods();
for(PsiMethod psiMethod : psiMethods )
{
try
{
if( null == psiMethod.getDocComment() )
{
fixMethod( psiMethod );
}
}
catch( IncorrectOperationException e )
{
e.printStackTrace();
}
}
}
/**
* Method fixMethod applies the defined JavaDoc template to the specified method.
* @param psiMethod the method that does not define JavaDoc
* @throws IncorrectOperationException when creating the JavaDoc fails
*/
private void fixMethod( PsiMethod psiMethod ) throws IncorrectOperationException
{
//PsiElementFactory factory = psiClass.getManager().getElementFactory();
PsiElementFactory factory =
JavaPsiFacade.getInstance( psiMethod.getProject() ).getElementFactory();
String javaDocTemplateText = JavaDocGenerator.generateJavaDoc( psiMethod );
PsiUtils.setPsiDocComment( factory.createDocCommentFromText( javaDocTemplateText ), psiMethod );
}
}
<file_sep>/test/p1/p2/ClassContainingEnum.java
package p1.p2;
enum MyColorEnum { Red, Green, Blue}
public class ClassContainingEnum {
private MyColorEnum myColorEnum;
public static void main(String[] args) {
MyColorEnum myRedColorEnum = MyColorEnum.Red;
MyColorEnum myGreenColorEnum = MyColorEnum.Green;
MyColorEnum myBlueColorEnum = MyColorEnum.Blue;
}
}
<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/inspections/ui/JavaDocSyncMethodOptionsPanel.java
package com.perniciouspenguins.ideaz.javadoc.inspections.ui;
import com.perniciouspenguins.ideaz.javadoc.inspections.MissingMethodJavaDocInspection;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Class JavaDocSyncMethodOptionsPanel
*
* @author <NAME>
* @version $id:$
* Created on Jul 4, 2007
*/
public class JavaDocSyncMethodOptionsPanel extends JPanel {
public static final String METHOD_ACCESS_PUBLIC = "public";
public static final String METHOD_ACCESS_PROTECTED = "protected";
public static final String METHOD_ACCESS_DEFAULT = "default";
public static final String METHOD_ACCESS_PRIVATE = "private";
public static final String[] detectionLevels = new String[]{
METHOD_ACCESS_PUBLIC,
METHOD_ACCESS_PROTECTED,
METHOD_ACCESS_DEFAULT,
METHOD_ACCESS_PRIVATE};
private MissingMethodJavaDocInspection owner = null;
/**
* Constructor JavaDocSyncMethodOptionsPanel creates a new JavaDocSyncMethodOptionsPanel instance.
* @param owner of type JavaDocBaseInspection
*/
public JavaDocSyncMethodOptionsPanel(MissingMethodJavaDocInspection owner) {
super();
this.owner = owner;
initComponents();
}
/**
* Method initComponents initializes the UI components
*/
private void initComponents() {
setLayout(new GridBagLayout());
Border lineBorder = BorderFactory.createLineBorder(Color.black);
setBorder(BorderFactory.createTitledBorder(lineBorder, "Detection level settings"));
JLabel methodDetectionLabel = new JLabel("Method detection level");
JComboBox methodDetectionLevel = new JComboBox(detectionLevels);
methodDetectionLevel.addActionListener(new ActionListener() {
/**
* @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
*/
public void actionPerformed(ActionEvent actionEvent) {
JComboBox source = (JComboBox) actionEvent.getSource();
if (source.getSelectedIndex() > -1) {
owner.methodDetectionLevel = (String) source.getSelectedItem();
}
}
});
JTextArea textArea = new JTextArea(
"Selected value includes methods with " +
"a wider access modifier, so 'public' " +
"is only 'public', 'protected' is " +
"'public' and 'protected', default is " +
"'public', 'protected' and methods " +
"with 'default' scope etc.");
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setRows(6);
textArea.setBackground(getBackground());
textArea.setFont(methodDetectionLabel.getFont());
JCheckBox checkAnonymousClasses = new JCheckBox("Inspect methods of anonymous classes");
checkAnonymousClasses.addChangeListener(new ChangeListener() {
/**
* @see javax.swing.event.ChangeListener
*/
public void stateChanged(ChangeEvent changeEvent) {
JCheckBox source = (JCheckBox) changeEvent.getSource();
owner.checkAnonymousClasses = source.isSelected();
}
});
JCheckBox useSingleLineReferences = new JCheckBox("Generate single line JavaDoc references");
useSingleLineReferences.addChangeListener(new ChangeListener() {
/**
* @see javax.swing.event.ChangeListener
*/
public void stateChanged(ChangeEvent changeEvent) {
JCheckBox source = (JCheckBox) changeEvent.getSource();
owner.useSingleLineReferences = source.isSelected();
}
});
GridBagConstraints gridBagConstraints;
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.anchor = GridBagConstraints.WEST;
gridBagConstraints.insets = new Insets(0, 10, 0, 0);
add(methodDetectionLabel, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.anchor = GridBagConstraints.WEST;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new Insets(0, 0, 0, 10);
add(methodDetectionLevel, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.anchor = GridBagConstraints.WEST;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.insets = new Insets(10, 10, 10, 10);
add(textArea, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new Insets(0, 10, 10, 10);
add(checkAnonymousClasses, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new Insets(0, 10, 10, 10);
add(useSingleLineReferences, gridBagConstraints);
checkAnonymousClasses.setSelected(owner.checkAnonymousClasses);
useSingleLineReferences.setSelected(owner.useSingleLineReferences);
String detectionLevel = owner.methodDetectionLevel;
if (null == detectionLevel) {
detectionLevel = METHOD_ACCESS_PRIVATE; // Everything, including private methods
}
methodDetectionLevel.setSelectedItem(detectionLevel);
}
}
<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/templates/TemplateManager.java
package com.perniciouspenguins.ideaz.javadoc.templates;
import com.intellij.ide.fileTemplates.FileTemplateUtil;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.DefaultLogger;
import com.intellij.openapi.diagnostic.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* Created by IntelliJ IDEA.
* User: <NAME>
* Date: Feb 24, 2007
* Time: 11:50:56 PM
*/
public class TemplateManager
{
public static final String TEMPLATE_CLASS = "Class";
public static final String TEMPLATE_ENUM = "Enum";
public static final String TEMPLATE_CONSTRUCTOR = "Constructor";
public static final String TEMPLATE_GETTER_METHOD = "Getter method";
public static final String TEMPLATE_FIELD = "Field";
public static final String TEMPLATE_INTERFACE = "Interface";
// public static final String TEMPLATE_OVERRIDDEN_METHOD = "Overridden method";
public static final String TEMPLATE_PLAIN_METHOD = "Plain method";
public static final String TEMPLATE_METHOD_PARAM = "Method parameter";
public static final String TEMPLATE_METHOD_THROWS = "Method throws clause";
public static final String TEMPLATE_METHOD_RETURN_TYPE = "Method return type";
public static final String TEMPLATE_SETTER_METHOD = "Setter method";
private static final String TEMPLATE_CLASS_JAVADOC = "Class JavaDoc";
private static final String TEMPLATE_ENUM_JAVADOC = "Enum JavaDoc";
private static final String TEMPLATE_INTERFACE_JAVADOC = "Interface JavaDoc";
private static final String TEMPLATE_FIELD_JAVADOC = "Field JavaDoc";
private static final String TEMPLATE_CONSTRUCTOR_JAVADOC = "Constructor JavaDoc";
private static final String TEMPLATE_METHOD_JAVADOC = "Method JavaDoc";
private static final String TEMPLATE_PARAMETER_JAVADOC = "Parameter JavaDoc";
private static final String TEMPLATE_RETURN_TYPE_JAVADOC = "Return type JavaDoc";
private static final String TEMPLATE_THROWS_CLAUSE_JAVADOC = "Throws clause JavaDoc";
private static final String TEMPLATE_GET_METHOD_JAVADOC = "Get Method JavaDoc";
private static final String TEMPLATE_SET_METHOD_JAVADOC = "Set Method JavaDoc";
private static final String TEMPLATE_DEFINITION_EXTENSION = ".tpl";
private static final String TEMPLATE_DESCRIPTION_EXTENSION = ".html";
private static final String TEMPLATE_LOCATION = "fileTemplates/jds/";
private final Logger log = new DefaultLogger( "JavaDocManager" );
private static TemplateManager instance = null;
/**
* Returns the singleton instance of this class
* @return the singleton instance of this class.
*/
public static TemplateManager getInstance()
{
if( null == instance )
{
instance = new TemplateManager();
}
return instance;
}
/**
* Method loadTemplate loads the template data based on the type name.
* @param type the type of template to load
* @return an intialized template object representing the specified type.
*/
public Template loadTemplate( String type )
{
Template template = null;
if( TEMPLATE_INTERFACE.equals( type ) )
{
log.debug( "docCommentOwner is an interface" );
template = readTemplateAndDocumentation( TEMPLATE_INTERFACE, TEMPLATE_INTERFACE_JAVADOC );
}
else if( TEMPLATE_CLASS.equals( type ) )
{
log.debug( "docCommentOwner is a class" );
template = readTemplateAndDocumentation( TEMPLATE_CLASS, TEMPLATE_CLASS_JAVADOC );
}
else if( TEMPLATE_ENUM.equals( type ) )
{
log.debug( "docCommentOwner is an enum" );
template = readTemplateAndDocumentation( TEMPLATE_ENUM, TEMPLATE_ENUM_JAVADOC );
}
else if( TEMPLATE_FIELD.equals( type ) )
{
log.debug( "docCommentOwner is a field" );
template = readTemplateAndDocumentation( TEMPLATE_FIELD, TEMPLATE_FIELD_JAVADOC );
}
else if( TEMPLATE_CONSTRUCTOR.equals( type ) )
{
log.debug( " - method is a constuctor" );
template = readTemplateAndDocumentation( TEMPLATE_CONSTRUCTOR, TEMPLATE_CONSTRUCTOR_JAVADOC );
}
else if( TEMPLATE_GETTER_METHOD.equals( type ) )
{
log.debug( " - method is a getter" );
template = readTemplateAndDocumentation( TEMPLATE_GETTER_METHOD, TEMPLATE_GET_METHOD_JAVADOC );
}
else if( TEMPLATE_SETTER_METHOD.equals( type ) )
{
log.debug( " - method is a setter" );
template = readTemplateAndDocumentation( TEMPLATE_SETTER_METHOD, TEMPLATE_SET_METHOD_JAVADOC );
}
else if( TEMPLATE_METHOD_PARAM.equals( type ) )
{
log.debug( " - method parameter template" );
template = readTemplateAndDocumentation( TEMPLATE_METHOD_PARAM, TEMPLATE_PARAMETER_JAVADOC );
}
else if( TEMPLATE_METHOD_RETURN_TYPE.equals( type ) )
{
log.debug( " - method return type template" );
template = readTemplateAndDocumentation( TEMPLATE_METHOD_RETURN_TYPE, TEMPLATE_RETURN_TYPE_JAVADOC );
}
else if( TEMPLATE_METHOD_THROWS.equals( type ) )
{
log.debug( " - method throws clause template" );
template = readTemplateAndDocumentation( TEMPLATE_METHOD_THROWS, TEMPLATE_THROWS_CLAUSE_JAVADOC );
}
else if( TEMPLATE_PLAIN_METHOD.equals( type ) )
{
log.debug( " - method is not a getter/setter/constructor" );
template = readTemplateAndDocumentation( TEMPLATE_PLAIN_METHOD, TEMPLATE_METHOD_JAVADOC );
}
if( null != template )
{
template.setProperties( extractTokensFromTemplate( template ) );
}
return template;
}
/**
* Method extractTokensFromTemplate scans for template tokens in the text of the specified
* template.
*
* @param template of type Template
* @return Properties a collection of tokens that were found in the template.
*/
private Properties extractTokensFromTemplate( Template template )
{
Properties properties = new Properties();
String templateText = template.getText();
int tokenStart = 0;
while( tokenStart > -1 && tokenStart < templateText.length() )
{
tokenStart = templateText.indexOf( "${", tokenStart );
if( tokenStart != -1 )
{
String token = templateText.substring( tokenStart + 2, templateText.indexOf( "}", tokenStart ) );
properties.put( token, "" );
tokenStart = tokenStart + token.length();
}
}
return properties;
}
/**
* Method readTemplateAndDocumentation loads the template data from disk or, if not present, from the jar file.
* @param type template type
* @param name template name
* @return the template representing the specified type and name.
*/
private Template readTemplateAndDocumentation( String type, String name )
{
Template template = new Template( type, name );
log.info( "Retrieving template " + name );
File configFolder = new File( PathManager.getConfigPath() );
File templateFolder = new File( configFolder, TEMPLATE_LOCATION );
File tpl = new File( templateFolder, name + TEMPLATE_DEFINITION_EXTENSION );
InputStream inputStream = null;
ClassLoader loader = getClass().getClassLoader();
if( tpl.exists() )
{
log.info( "Template " + name + " already exists at " + templateFolder.getPath() );
try
{
template.setText( readTemplate( new FileInputStream( tpl ) ) );
}
catch( FileNotFoundException e )
{
log.error( e.getMessage() );
}
}
else
{
log.info( "Template " + name + " not found at " + templateFolder.getPath() + ", reading from jar..." );
try
{
inputStream = loader.getResourceAsStream( TEMPLATE_LOCATION + name + TEMPLATE_DEFINITION_EXTENSION );
template.setText( extractAndReadTemplate( inputStream, tpl ) );
}
finally
{
if( null != inputStream )
{
try
{
inputStream.close();
}
catch( IOException e )
{
}
}
}
}
try
{
inputStream = loader.getResourceAsStream( TEMPLATE_LOCATION + name + TEMPLATE_DESCRIPTION_EXTENSION );
template.setDocumentation( readTemplate( inputStream ) );
}
finally
{
if( null != inputStream )
{
try
{
inputStream.close();
}
catch( IOException e ){/*Nothing we can do*/}
}
}
return template;
}
/**
* Method extractAndReadTemplate reads the template data from the jar and saves a local disk copy.
*
* @param template the stream to read the template
* @param outputFile the file to write to on disk
* @return String the template text
*/
private String extractAndReadTemplate( InputStream template, File outputFile )
{
FileOutputStream fileOutputStream = null;
String tpl = null;
try
{
tpl = readTemplate( template );
if( !outputFile.getParentFile().exists() )
{
//noinspection ResultOfMethodCallIgnored
outputFile.getParentFile().mkdirs();
}
fileOutputStream = new FileOutputStream( outputFile );
fileOutputStream.write( tpl.getBytes() );
fileOutputStream.flush();
}
catch( FileNotFoundException e )
{
log.error( e.getMessage() );
}
catch( IOException e )
{
log.error( e.getMessage() );
}
finally
{
if( null != fileOutputStream )
{
try
{
fileOutputStream.close();
}
catch( IOException e )
{
}
}
}
return tpl;
}
/**
* Method readTemplate reads the text of a template from the specified stream.
*
* @param template the stream to read from.
* @return String the text of the template.
*/
private String readTemplate( InputStream template )
{
String tpl = null;
BufferedReader reader = null;
try
{
reader = new BufferedReader( new InputStreamReader( template ) );
tpl = readTemplateFromReader( reader );
}
catch( Exception e )
{
log.error( e.getMessage() );
}
finally
{
if( null != reader )
{
try
{
reader.close();
}
catch( IOException e )
{
}
}
}
return tpl;
}
/**
* Method saveTemplate writes the new template text to disk.
*
* @param template the template to save
*/
public void saveTemplate( Template template )
{
if( null != template )
{
String templateLocation = TEMPLATE_LOCATION;
File configFolder = new File( PathManager.getConfigPath() );
File templateFolder = new File( configFolder, templateLocation );
File tpl = new File( templateFolder, template.getName() + TEMPLATE_DEFINITION_EXTENSION );
FileOutputStream fileOutputStream = null;
try
{
fileOutputStream = new FileOutputStream( tpl );
fileOutputStream.write( template.getText().getBytes() );
fileOutputStream.flush();
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
if( null != fileOutputStream )
{
try
{
fileOutputStream.close();
}
catch( IOException e )
{
}
}
}
}
}
/**
* Method readTemplateFromReader reads the template text from the specified reader and appends new line feed
* characters.
*
* @param reader the stream to read from.
* @return String the template text including line feeds.
* @throws IOException when reading from the stream fails.
*/
private String readTemplateFromReader( BufferedReader reader ) throws IOException
{
StringBuffer sb = new StringBuffer();
String line = reader.readLine();
while( null != line )
{
sb.append( line );
line = reader.readLine();
if( null != line )
{
sb.append( "\n" );
}
}
return sb.toString();
}
/**
* Singleton
*/
private TemplateManager()
{
}
/**
* Method merge ...
*
* @param template of type Template
* @return String
*/
public String merge( Template template )
{
String mergedText = null;
try
{
mergedText = FileTemplateUtil.mergeTemplate(
template.getProperties(), template.getText().replaceAll( "\n\n", "\n" ), true );
}
catch( IOException e )
{
log.error( "Caught exception while merging " + template.getName() + " with properties: " + e.getMessage() );
}
return mergedText;
}
}
<file_sep>/README.markdown
# JavaDoc Manager #
The JavaDoc Manager plugin will help maintain your JavaDocs by providing template based creation of JavaDocs,
as well as syncing of JavaDocs from parent classes/interfaces, overridden methods, etc.
---
The JavaDoc Sync Plugin was originally written by <NAME> but was updated for IntelliJ 8, 9, and 10 by <NAME>. Open Sourced for IntelliJ 10.5.<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/JavaDocManager.java
package com.perniciouspenguins.ideaz.javadoc;
import com.intellij.codeInspection.InspectionToolProvider;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.xmlb.XmlSerializationException;
import com.intellij.util.xmlb.XmlSerializer;
import com.perniciouspenguins.ideaz.javadoc.inspections.InconsistentJavaDocInspection;
import com.perniciouspenguins.ideaz.javadoc.inspections.MissingClassJavaDocInspection;
import com.perniciouspenguins.ideaz.javadoc.inspections.MissingFieldJavaDocInspection;
import com.perniciouspenguins.ideaz.javadoc.inspections.MissingMethodJavaDocInspection;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
/**
* JavaDoc Sync plugin to provide inspections that detect missing or inconsistent JavaDoc declarations.
*
* Author: <NAME> Date: Dec 23, 2005 9:45:54 PM
*/
@State(
name = JavaDocManager.COMPONENT_NAME,
storages = {@Storage(
id = "JavaDoc",
file = "$APP_CONFIG$/JavaDocManager.xml"
)}
)
public class JavaDocManager
implements ApplicationComponent, InspectionToolProvider, PersistentStateComponent<Element>
{
private static final Logger log = Logger.getInstance( "JavaDocManager" );
public static final String COMPONENT_NAME = "JavaDocManager";
/**
* Method JavaDocManager creates a new instance of the plugin.
*/
public JavaDocManager()
{
}
/**
* Unique name of this component. If there is another component with the same name or name is null internal
* assertion will occur.
*
* @return the name of this component
*/
@NonNls
@NotNull
public String getComponentName()
{
return COMPONENT_NAME;
}
/**
* Component should do initialization and communication with another components in this method.
*/
public void initComponent()
{
}
/**
* Component should dispose system resources or perform another cleanup in this method.
*/
public void disposeComponent()
{
}
/**
* Query method for inspection tools provided by a plugin.
*
* @return classes that extend {@link com.intellij.codeInspection.LocalInspectionTool}
*/
public Class[] getInspectionClasses()
{
return new Class[] {MissingClassJavaDocInspection.class,
MissingFieldJavaDocInspection.class,
MissingMethodJavaDocInspection.class,
InconsistentJavaDocInspection.class};
}
public Element getState()
{
try
{
final Element e = new Element( "state" );
XmlSerializer.serializeInto( this, e );
return e;
}
catch( XmlSerializationException e1 )
{
log.error( e1 );
return null;
}
}
public void loadState( final Element state )
{
try
{
XmlSerializer.deserializeInto( this, state );
}
catch( XmlSerializationException e )
{
log.error( e );
}
}
}<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/inspections/JavaDocBaseInspection.java
package com.perniciouspenguins.ideaz.javadoc.inspections;
import com.intellij.codeInspection.BaseJavaLocalInspectionTool;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.PsiAnonymousClass;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.javadoc.PsiDocComment;
import com.perniciouspenguins.ideaz.javadoc.fixes.LocalQuickFixBase;
import com.perniciouspenguins.ideaz.javadoc.inspections.ui.JavaDocSyncMethodOptionsPanel;
import com.perniciouspenguins.ideaz.javadoc.util.PsiUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* Base class offering shared functionality for all inspection options.
*
* Author: <NAME> Date: Dec 23, 2005 9:37:26 PM
*/
@SuppressWarnings( {"UnusedParameters"} )
public abstract class JavaDocBaseInspection extends BaseJavaLocalInspectionTool
{
public String methodDetectionLevel = JavaDocSyncMethodOptionsPanel.METHOD_ACCESS_PRIVATE;
public static boolean checkInnerClasses = true;
public boolean checkAnonymousClasses = true;
public boolean useSingleLineReferences = true;
/**
* Method getGroupDisplayName defines the name of the group of the inspections under which all sub classes of this
* class are ordered.
*
* @return String
*/
@NonNls
@NotNull
public final String getGroupDisplayName()
{
return "JavaDoc Issues";
}
/**
* Defines the name of the inspection under the group display name.
*
* @return the name of this inspection
*/
@NonNls
@NotNull
public abstract String getDisplayName();
/**
* Defines the short name of the inspection.
*
* @return the short name of this inspection
*/
@NonNls
@NotNull
public abstract String getShortName();
/**
* Override this to report problems at class level.
*
* @param psiClass to check.
* @param manager InspectionManager to ask for ProblemDescriptor's from.
* @param isOnTheFly true if called during on the fly editor highlighting. Called from Inspect Code action otherwise.
*
* @return <code>null</code> if no problems found or not applicable at class level.
*/
@Nullable
public ProblemDescriptor[] checkClass( @NotNull final PsiClass psiClass,
@NotNull final InspectionManager manager,
final boolean isOnTheFly )
{
final List<ProblemDescriptor> descriptors = new ArrayList<ProblemDescriptor>();
ApplicationManager.getApplication().runReadAction( new Runnable()
{
/**
* Method run contains the action that needs to be executed when the dispatch thread
* allows write actions.
*/
public void run()
{
boolean isInnerClass = PsiUtils.isInnerClass( psiClass );
boolean isAnonymous = PsiUtils.isAnonymous( psiClass );
if( (isInnerClass && !checkInnerClasses) || (isAnonymous && !checkAnonymousClasses) )
{
return;
}
descriptors.addAll( determineIntroduceDocOptions( psiClass, manager, isOnTheFly ) );
}
} );
if( descriptors.isEmpty() )
{
return super.checkClass( psiClass, manager, isOnTheFly );
}
else
{
return descriptors.toArray( new ProblemDescriptor[descriptors.size()] );
}
}
/**
* Override this to report problems at method level.
*
* @param method to check.
* @param manager InspectionManager to ask for ProblemDescriptor's from.
* @param isOnTheFly true if called during on the fly editor highlighting. Called from Inspect Code action otherwise.
*
* @return <code>null</code> if no problems found or not applicable at method level.
*/
@Nullable
public ProblemDescriptor[] checkMethod( @NotNull final PsiMethod method,
@NotNull final InspectionManager manager,
final boolean isOnTheFly )
{
final List<ProblemDescriptor> descriptors = new ArrayList<ProblemDescriptor>();
ApplicationManager.getApplication().runReadAction( new Runnable()
{
/**
* Method run contains the action that needs to be executed when the dispatch thread
* allows write actions.
*/
public void run()
{
boolean isAnonymous = PsiUtils.isAnonymous( method.getContainingClass() );
boolean isInnerClass = PsiUtils.isInnerClass( method.getContainingClass() );
if( !PsiUtils.accessModifierLevelInRange( method.getModifierList(), methodDetectionLevel ) ||
( isAnonymous && !checkAnonymousClasses ) ||
( isInnerClass && !checkInnerClasses ) )
{
return;
}
PsiDocComment docComment = method.getDocComment();
if( docComment == null )
{
descriptors.addAll( determineIntroduceDocOptions( method, manager, isOnTheFly ) );
}
else
{
descriptors.addAll( determineDocDifferences( method, manager, isOnTheFly ) );
}
}
} );
if( descriptors.isEmpty() )
{
return super.checkMethod( method, manager, isOnTheFly );
}
else
{
return descriptors.toArray( new ProblemDescriptor[descriptors.size()] );
}
}
/**
* Override this to report problems at field level.
*
* @param field to check.
* @param manager InspectionManager to ask for ProblemDescriptor's from.
* @param isOnTheFly true if called during on the fly editor highlighting. Called from Inspect Code action otherwise.
*
* @return <code>null</code> if no problems found or not applicable at field level.
*/
@Nullable
public ProblemDescriptor[] checkField( @NotNull final PsiField field,
@NotNull final InspectionManager manager,
final boolean isOnTheFly )
{
final List<ProblemDescriptor> descriptors = new ArrayList<ProblemDescriptor>();
ApplicationManager.getApplication().runReadAction( new Runnable()
{
/**
* Method run contains the action that needs to be executed when the dispatch thread
* allows write actions.
*/
public void run()
{
boolean isAnonymous = PsiUtils.isAnonymous( field.getContainingClass() );
boolean isInnerClass = PsiUtils.isInnerClass( field.getContainingClass() );
if( ( isAnonymous && !checkAnonymousClasses ) || ( isInnerClass && !checkInnerClasses ) )
{
return;
}
PsiDocComment docComment = field.getDocComment();
if( docComment == null )
{
descriptors.addAll( determineIntroduceDocOptions( field, manager, isOnTheFly ) );
}
}
} );
if( descriptors.isEmpty() )
{
return super.checkField( field, manager, isOnTheFly );
}
else
{
return descriptors.toArray( new ProblemDescriptor[descriptors.size()] );
}
}
/**
* The currently scanned class does not have JavaDoc.
*
* @param psiClass the class to check
* @param manager the inspection manager to use
* @param onTheFly if this is on the fly or not
*
* @return a collection of ProblemDescriptors or an empty collection.
*/
protected List<ProblemDescriptor> determineIntroduceDocOptions( PsiClass psiClass,
InspectionManager manager,
boolean onTheFly )
{
return new ArrayList<ProblemDescriptor>();
}
/**
* The currently scanned method does not have JavaDoc. if method is impl/override and interface/base has javadoc -
* offer introduce reference - offer copy from parent else - offer to generate
*
* @param method the method to check
* @param manager the inspection manager to use
* @param onTheFly if this is on the fly or not
*
* @return a collection of ProblemDescriptors or an empty collection.
*/
protected List<ProblemDescriptor> determineIntroduceDocOptions( PsiMethod method,
InspectionManager manager,
boolean onTheFly )
{
return new ArrayList<ProblemDescriptor>();
}
/**
* if Method has superMethod if superMethod has JavaDoc if JavaDoc superMethod equals method JavaDoc OK else if
* JavaDoc superMethod doesn't equals method JavaDoc if method JavaDoc has reference to superMethod OK else if method
* doesn't have reference WARN "Method JavaDoc differences from super method JavaDoc" - offer introduce reference -
* offer copy from parent else if superMethod has no JavaDoc WARN "Method definition does not have any JavaDoc" -
* offer to copy to parent - offer to move doc to parent and introduce reference else WARN "Method definition does not
* have any JavaDoc" - offer to generate JavaDoc based on method sigmature
*
* @param method the method to check
* @param manager the inspection manager to use
* @param onTheFly if this is on the fly or not
*
* @return a collection of ProblemDescriptors or an empty collection.
*/
protected List<ProblemDescriptor> determineDocDifferences( PsiMethod method,
InspectionManager manager,
boolean onTheFly )
{
return new ArrayList<ProblemDescriptor>();
}
/**
* The currently scanned field does not have JavaDoc.
*
* @param field the field to check
* @param manager the inspection manager to use
* @param onTheFly if this is on the fly or not
*
* @return a collection of ProblemDescriptors or an empty collection.
*/
protected List<ProblemDescriptor> determineIntroduceDocOptions( PsiField field,
InspectionManager manager,
boolean onTheFly )
{
return new ArrayList<ProblemDescriptor>();
}
/**
* Method to find the specified psiMethod in the parent class/interface
*
* @param psiMethod the method of which the super implementation/definition is requested
*
* @return the superMethod or null if the direct super class/interface (if available) does not define the specified
* method or is the containing class of the method does not extend or implement another class/interface.
*/
@Nullable
protected PsiMethod getSuperMethod( PsiMethod psiMethod )
{
if( null != psiMethod )
{
PsiClass containingClass = psiMethod.getContainingClass();
if( null != containingClass )
{
return PsiUtils.checkParents( containingClass.getSuperClass(), psiMethod );
}
}
return null;
}
/**
* Method to determine the correct description template based on the definition of the specified parameters.
*
* @param method the PsiMethod being checked
* @param superMethod the super PsiMethod or null if this method has no super method
*
* @return the description template or null if none could be determined.
*/
@SuppressWarnings( {"ConstantConditions"} )
protected String determineDescriptionTemplate( PsiMethod method, PsiMethod superMethod )
{
boolean isInterfaceMethod = method != null && method.getContainingClass().isInterface();
boolean superIsInterface = superMethod != null && superMethod.getContainingClass().isInterface();
boolean superIsObject = superMethod != null && PsiUtils.isFromObjectClass( superMethod );
String descriptionTemplate = null;
if( null != method )
{
if( null != superMethod )
{
if( isInterfaceMethod )
{
// Interface extending other interface, overriding declared method
descriptionTemplate = LocalQuickFixBase.OVERRIDDEN_METHOD_NO_JAVADOC;
}
else
{
if( superIsInterface )
{
// Class implementing interface method
descriptionTemplate = LocalQuickFixBase.IMPLEMENTATION_NO_JAVADOC;
}
else if( superIsObject )
{
// Base class declaring method
descriptionTemplate = LocalQuickFixBase.BASE_METHOD_NO_JAVADOC;
}
else
{
// Class extending other class, overriding declared method
descriptionTemplate = LocalQuickFixBase.OVERRIDDEN_METHOD_NO_JAVADOC;
}
}
}
else
{
if( isInterfaceMethod )
{
// Base interface declaring method
descriptionTemplate = LocalQuickFixBase.INTERFACE_METHOD_NO_JAVADOC;
}
else if( method.getContainingClass() instanceof PsiAnonymousClass )
{
// Method is an anonymous override
descriptionTemplate = LocalQuickFixBase.OVERRIDDEN_METHOD_ANONYMOUS_CLASS_NO_JAVADOC;
}
else
{
// Base class declaring method
descriptionTemplate = LocalQuickFixBase.BASE_METHOD_NO_JAVADOC;
}
}
}
return descriptionTemplate;
}
}
<file_sep>/test/p1/p2/ClassImplementingInterface.java
package p1.p2;
import java.util.List;
public class ClassImplementingInterface implements ExtendingSomeInterface {
private boolean myMockField;
// Should say: method implementation does not have JavaDoc
public int aMethodWithoutJavaDoc(String s) {
// Class without JavaDoc implements interface definition
return 0;
}
/**
* The JavaDoc
*
* @param system the system
* @return byte array
*/
// Should say nothing
public byte[] aMethodWithJavaDoc(System system) {
return new byte[0];
}
/**
* @see p1.p2.SomeInterface#anAbstractMethodWithoutJavaDoc()
*/
// Should say nothing
public void anAbstractMethodWithoutJavaDoc() {
Object o = new Object() {
public String toString() {
return super.toString();
}
};
System.out.println(o);
}
/**
* Some different JavaDoc here
*
* @param one One
* @param two Two
* @return String
*
* @see SomeInterface#anAbstractMethodWithJavaDoc(int,long)
*/
// Should say: JavaDoc differs from JavaDoc in parent method
public String anAbstractMethodWithJavaDoc(int one, long two) {
return null;
}
// Should say: method implementation does not have Javadoc
public List aDifferentMethodWithJavaDoc(List objects) {
return null;
}
/**
* Method overrideMe
*/
// Should say: JavaDoc differs from JavaDoc in parent method
public void overrideMe() {
}
}
<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/fixes/AddReference.java
package com.perniciouspenguins.ideaz.javadoc.fixes;
import com.intellij.psi.PsiMethod;
import com.perniciouspenguins.ideaz.javadoc.util.PsiUtils;
import org.jetbrains.annotations.NotNull;
/**
* The AddReference offers the ability to add a JavaDoc
* reference to the existing JavaDoc which references to
* the parent method. This fix will preserve the existing
* JavaDoc which differs with the JavaDoc in the parent
* method and will add a JavaDoc reference.
*
* Author: <NAME>
* Date: Jan 7, 2007 5:06:57 PM
*/
public class AddReference extends LocalQuickFixBase {
private boolean useSingleLineReferences;
/**
* Method LocalQuickFixBase creates a new instance of a Quick fix for a method that has a parent
* method.
*
* @param method the method to which the quick fix applies.
* @param superMethod the super method of which the JavaDoc is taken into account when offering
* quick fixes.
* @param useSingleLineReferences indicates whether the plugin is configured to use single
* line references or three lines
*/
public AddReference(PsiMethod method, PsiMethod superMethod, boolean useSingleLineReferences) {
super(method, superMethod);
this.useSingleLineReferences = useSingleLineReferences;
}
/**
* Returns the name of the quick fix.
*
* @return the name of the quick fix.
*/
@NotNull
public String getName () {
return FIX_ADD_REFERENCE;
}
/**
* Method doFix returns the actual fix that needs to be executed to solve the
* detected problem.
*/
public void doFix() {
PsiUtils.addReference(method, superMethod, true, useSingleLineReferences);
}
}
<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/inspections/ui/JavaDocSyncClassOptionsPanel.java
package com.perniciouspenguins.ideaz.javadoc.inspections.ui;
import com.perniciouspenguins.ideaz.javadoc.inspections.MissingClassJavaDocInspection;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Class JavaDocSyncMethodOptionsPanel
*
* @author <NAME>
* @version $id:$
* Created on Jul 4, 2007
*/
public class JavaDocSyncClassOptionsPanel extends JPanel {
/**
* Constructor JavaDocSyncMethodOptionsPanel creates a new JavaDocSyncMethodOptionsPanel instance.
*/
public JavaDocSyncClassOptionsPanel() {
super();
initComponents();
}
/**
* Method initComponents initializes the UI components
*/
private void initComponents() {
setLayout(new GridBagLayout());
Border lineBorder = BorderFactory.createLineBorder(Color.black);
setBorder(BorderFactory.createTitledBorder(lineBorder, "Detection level settings"));
JCheckBox checkInnerClasses = new JCheckBox("Inspect inner classes");
checkInnerClasses.addChangeListener(new ChangeListener() {
/**
* @inheritDoc javax.swing.event.ChangeListener(ChangeEvent)
*/
public void stateChanged(ChangeEvent changeEvent) {
JCheckBox source = (JCheckBox) changeEvent.getSource();
MissingClassJavaDocInspection.checkInnerClasses = source.isSelected();
}
});
checkInnerClasses.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
JCheckBox source = (JCheckBox) propertyChangeEvent.getSource();
if (!source.isEnabled()) {
MissingClassJavaDocInspection.checkInnerClasses = false;
}
}
});
GridBagConstraints gridBagConstraints;
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new Insets(0, 10, 0, 10);
add(checkInnerClasses, gridBagConstraints);
checkInnerClasses.setSelected(MissingClassJavaDocInspection.checkInnerClasses);
}
}
<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/fixes/IntroduceReference.java
package com.perniciouspenguins.ideaz.javadoc.fixes;
import com.intellij.psi.PsiMethod;
import com.perniciouspenguins.ideaz.javadoc.util.PsiUtils;
import org.jetbrains.annotations.NotNull;
/**
* The IntroduceReference offers the ability to replace the existing JavaDoc
* with a reference to the parent method.
*
* Author: <NAME>
* Date: Dec 24, 2005 6:29:36 PM
*/
public class IntroduceReference extends LocalQuickFixBase {
private boolean useSingleLineReferences;
/**
* Method LocalQuickFixBase creates a new instance of a Quick fix for a method that has a parent
* method.
*
* @param method the method to which the quick fix applies.
* @param superMethod the super method of which the JavaDoc is taken into account when offering
* @param useSingleLineReferences indicates whether the plugin is configured to use single
* line references or three lines
*/
public IntroduceReference(PsiMethod method, PsiMethod superMethod, boolean useSingleLineReferences) {
super(method, superMethod);
this.useSingleLineReferences = useSingleLineReferences;
}
/**
* Returns the name of the quick fix.
*
* @return the name of the quick fix.
*/
@NotNull
public String getName() {
return FIX_INTRODUCE_REFERENCE;
}
/**
* Method doFix returns the actual fix that needs to be executed to solve the
* detected problem.
*/
public void doFix() {
PsiUtils.addReference(method, superMethod, false, useSingleLineReferences);
}
}
<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/inspections/MissingClassJavaDocInspection.java
package com.perniciouspenguins.ideaz.javadoc.inspections;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiIdentifier;
import com.intellij.psi.PsiMethod;
import com.perniciouspenguins.ideaz.javadoc.fixes.GenerateForAllMethods;
import com.perniciouspenguins.ideaz.javadoc.fixes.GenerateFromClass;
import com.perniciouspenguins.ideaz.javadoc.fixes.LocalQuickFixBase;
import com.perniciouspenguins.ideaz.javadoc.inspections.ui.JavaDocSyncClassOptionsPanel;
import com.perniciouspenguins.ideaz.javadoc.util.PsiUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
/**
* The MissingClassJavaDocInspection highlights class declarations that are not preceeded by a JavaDoc declaration.
*
* Author: <NAME> Date: Dec 30, 2005 9:06:50 PM
*/
public class MissingClassJavaDocInspection extends JavaDocBaseInspection
{
/**
* Defines the name of the inspection under the group display name.
*
* @return the name of this inspection
*/
@NotNull
public String getDisplayName()
{
return "Missing Class JavaDoc declaration";
}
/**
* Defines the short name of the inspection.
*
* @return the short name of this inspection
*/
@NotNull
public String getShortName()
{
return "MissingClassJavaDoc";
}
/**
* @return null if no UI options required
*/
@Nullable
public JComponent createOptionsPanel()
{
return new JavaDocSyncClassOptionsPanel();
}
/**
* The currently scanned class does not have JavaDoc.
*
* @param psiClass the class to check
* @param manager the inspection manager to use
*
* @return a collection of ProblemDescriptors or an empty collection.
*/
protected List<ProblemDescriptor> determineIntroduceDocOptions( PsiClass psiClass,
InspectionManager manager,
boolean onTheFLy )
{
List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
List<LocalQuickFixBase> fixes = new ArrayList<LocalQuickFixBase>();
ProblemDescriptor problemDescriptor;
String descriptionTemplate = null;
if( PsiUtils.isInnerClass( psiClass ) && !checkInnerClasses )
{
return problems;
}
// Check all methods and allow generation of JavaDoc for all methods at once
PsiMethod[] psiMethods = psiClass.getMethods();
boolean foundMethodsWithoutJavaDoc = false;
for( int i = 0; !foundMethodsWithoutJavaDoc && i < psiMethods.length; i++ )
{
PsiMethod psiMethod = psiMethods[i];
if( null == psiMethod.getDocComment() )
{
foundMethodsWithoutJavaDoc = true;
}
}
PsiIdentifier psiIdentifier = psiClass.getNameIdentifier();
if( psiClass.getDocComment() == null )
{
if( psiClass.isInterface() )
{
descriptionTemplate = LocalQuickFixBase.INTERFACE_DEFINITION_NO_JAVADOC;
}
else if( psiClass.isEnum() )
{
descriptionTemplate = LocalQuickFixBase.ENUM_DEFINITION_NO_JAVADOC;
}
else if( psiClass.getName() != null )
{
descriptionTemplate = LocalQuickFixBase.CLASS_DEFINITION_NO_JAVADOC;
}
fixes.add( new GenerateFromClass( psiClass ) );
if( null != psiIdentifier && null != descriptionTemplate )
{
problemDescriptor = manager.createProblemDescriptor( psiIdentifier,
descriptionTemplate,
onTheFLy,
fixes.toArray( new LocalQuickFix[fixes.size()] ),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING );
problems.add( problemDescriptor );
}
}
if( foundMethodsWithoutJavaDoc && !PsiUtils.isAnonymous( psiClass ) )
{
descriptionTemplate = LocalQuickFixBase.ONE_OR_MORE_METHODS_DO_NOT_DEFINE_JAVADOC;
fixes.clear();
fixes.add( new GenerateForAllMethods( psiClass ) );
if( null != psiIdentifier )
{
problemDescriptor = manager.createProblemDescriptor( psiIdentifier,
descriptionTemplate,
onTheFLy,
fixes.toArray( new LocalQuickFix[fixes.size()] ),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING );
problems.add( problemDescriptor );
}
}
return problems;
}
}
<file_sep>/src/com/perniciouspenguins/ideaz/javadoc/inspections/InconsistentJavaDocInspection.java
package com.perniciouspenguins.ideaz.javadoc.inspections;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.psi.PsiIdentifier;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.javadoc.PsiDocComment;
import com.perniciouspenguins.ideaz.javadoc.fixes.AddReference;
import com.perniciouspenguins.ideaz.javadoc.fixes.CopyFromParent;
import com.perniciouspenguins.ideaz.javadoc.fixes.LocalQuickFixBase;
import com.perniciouspenguins.ideaz.javadoc.fixes.MoveToParentAndIntroduceReference;
import com.perniciouspenguins.ideaz.javadoc.fixes.ReplaceParentDoc;
import com.perniciouspenguins.ideaz.javadoc.util.PsiUtils;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* The InconsistentJavaDocInspection reports differences between the JavaDoc of the scanned method and the JavaDoc in
* the parent method or interface method declaration. <p/> Author: <NAME> Date: Dec 26, 2005 1:53:04 PM
*/
public class InconsistentJavaDocInspection extends JavaDocBaseInspection
{
/**
* Defines the name of the inspection under the group display name.
*
* @return the name of this inspection
*/
@NotNull
public String getDisplayName()
{
return "Inconsistent JavaDoc";
}
/**
* Defines the short name of the inspection.
*
* @return the short name of this inspection
*/
@NotNull
public String getShortName()
{
return "InconsistentJavaDoc";
}
/**
* if Method has superMethod if superMethod has JavaDoc if JavaDoc superMethod equals method JavaDoc OK else if
* JavaDoc superMethod doesn't equals method JavaDoc if method JavaDoc has reference to superMethod OK else if method
* doesn't have reference WARN "Method JavaDoc differences from super method JavaDoc" - offer introduce reference -
* offer copy from parent else if superMethod has no JavaDoc WARN "Method definition does not have any JavaDoc" -
* offer to copy to parent - offer to move doc to parent and introduce reference else WARN "Method definition does not
* have any JavaDoc" - offer to generate JavaDoc based on method sigmature
*
* @param method the method to check
* @param manager the inspection manager to use
* @param onTheFly if this is on the fly or not
*
* @return a collection of ProblemDescriptors or an empty collection.
*/
protected List<ProblemDescriptor> determineDocDifferences( @NotNull PsiMethod method,
@NotNull InspectionManager manager,
boolean onTheFly )
{
List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
List<LocalQuickFix> fixes = new ArrayList<LocalQuickFix>();
String descriptionTemplate = findFixesForInconsistency( getSuperMethod( method ), method, fixes );
if( descriptionTemplate != null )
{
PsiIdentifier psiIdentifier = method.getNameIdentifier();
if( null != psiIdentifier )
{
ProblemDescriptor problemDescriptor = manager.createProblemDescriptor( psiIdentifier,
descriptionTemplate,
onTheFly,
fixes.toArray(
new LocalQuickFix[fixes
.size()] ),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING );
problems.add( problemDescriptor );
}
}
return problems;
}
/**
* Method findFixesForInconsistency determines which fixes are valid for the code inconsistency described by the
* JavaDoc of the method and optionally that of its super method.
*
* @param superMethod the super method, optionally describing JavaDoc
* @param method the method with JavaDoc
* @param fixes the collection of quick fixes that can be applied
*
* @return String the description template of the inconsistency that was detected or null if the inconsistency could
* not be determined.
*/
private String findFixesForInconsistency( PsiMethod superMethod, PsiMethod method, List<LocalQuickFix> fixes )
{
String descriptionTemplate = null;
PsiDocComment docComment = method.getDocComment();
if( !method.isConstructor() && null != docComment )
{
if( null == superMethod && PsiUtils.definesInheritDocTag( method ) && !PsiUtils.isAnonymous( method ) )
{
descriptionTemplate = LocalQuickFixBase.NO_SUPER_METHOD_TO_INHERIT_DOC_FROM;
}
else if( null != superMethod && !PsiUtils.isFromObjectClass( superMethod ) )
{
PsiDocComment superDocComment = superMethod.getDocComment();
if( null != superDocComment &&
!PsiUtils.docsAreEqual( docComment, superDocComment ) &&
!PsiUtils.hasReferenceToParentMethod( method, superMethod ) &&
!PsiUtils.hasInheritedJavaDoc( method, superMethod ) )
{
descriptionTemplate = LocalQuickFixBase.JAVADOC_DIFFERS_FROM_PARENT;
fixes.add( new AddReference( method, superMethod, useSingleLineReferences ) );
fixes.add( new CopyFromParent( method, superMethod ) );
}
else if( null == superDocComment && PsiUtils.definesInheritDocTag( method ) )
{
descriptionTemplate = LocalQuickFixBase.NO_JAVADOC_IN_SUPER_METHOD_TO_INHERIT_FROM;
}
// If we cannot write to the parent there's no sense in
// allowing options to change the parent
else if( null == superDocComment && superMethod.getContainingFile().isWritable() )
{
descriptionTemplate = LocalQuickFixBase.JAVADOC_DIFFERS_FROM_PARENT;
fixes.add( new MoveToParentAndIntroduceReference( method, superMethod, useSingleLineReferences ) );
fixes.add( new ReplaceParentDoc( method, superMethod ) );
}
}
}
return descriptionTemplate;
}
}
| 660c5f2f84ea5cd2d1ce149e3489a141ce367ad3 | [
"Markdown",
"Java"
]
| 14 | Java | zhangwei5095/JavaDocManager | 48b85707039d09cb063b871a23897762d945bc8f | 14b5557de7df436e7f3dd29769e4026b3119b504 |
refs/heads/main | <file_sep>import { useState, useEffect } from 'react';
import Head from "next/head";
import Link from "next/link";
import Date from "../components/date";
import Layout, { siteTitle } from "../components/layout";
import utilStyles from "../styles/utils.module.css";
import fire from "../config/fire-config";
export default function Home({ allPostsData }) {
return (
<Layout home>
<Head>
<title>{siteTitle}</title>
</Head>
<section className={utilStyles.headingMd}>
<p>Poetry | Thoughts | Ideas</p>
</section>
<section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}>
<h2 className={utilStyles.headingLg}>Blog</h2>
<ul className={utilStyles.list}>
{allPostsData.map((post) => (
<li className={utilStyles.listItem} key={post.id}>
<Link href={`/posts/${post.id}`}>
<a>{post.title}</a>
</Link>
<br />
</li>
))}
</ul>
</section>
</Layout>
);
}
export async function getStaticProps() {
var allPostsData = [];
const blogsRef = fire.firestore().collection('blog')
const snapshot = await blogsRef.get();
snapshot.forEach(doc => {
allPostsData.push({
id: doc.id,
...doc.data()
})
});
return {
props: {
allPostsData,
},
};
}<file_sep>import Head from "next/head";
import Link from "next/link";
import Layout from "../components/layout";
import utilStyles from "../styles/utils.module.css";
export default function APIIndex({allRoutesData}) {
return (
<Layout>
<Head>
<title>API Routes Index</title>
</Head>
<section className={utilStyles.headingMd}>
<p>API Routes</p>
</section>
<section>
<p>Make GET requests at following routes to fetch data</p>
<ul className={utilStyles.list}>
{allRoutesData.map((route) => (
<li className={utilStyles.listItem} key={route.id}>
<Link href={`/api/${route.rUrl}`}>
<a>/api/{route.name}</a>
</Link>
</li>
))}
<li className={utilStyles.listItem}>
<a>/api/posts/:postid </a><span>to retrieve a specific post</span>
</li>
</ul>
</section>
</Layout>
)
}
export async function getStaticProps() {
var allRoutesData = [
{
id: 1,
rUrl: "postsids",
name: "postsids"
},
{
id: 0,
rUrl: "posts",
name: "posts"
},
];
return {
props: {
allRoutesData,
},
};
}<file_sep>import React, { useState } from 'react';
import fire from '../config/fire-config';
import utilStyles from "../styles/utils.module.css";
const CreatePost = () => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [excerpt, setExcerpt] = useState('');
const [notification, setNotification] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
fire.firestore()
.collection('blog')
.add({
title: title,
content: content,
excerpt: excerpt
// created:fire.firestore.FieldValue.serverTimestamp()
});
setTitle('');
setContent('');
setNotification('Blogpost created');
}
return (
<div>
<form onSubmit={handleSubmit}>
<span className={`${utilStyles.textSuccess}`}>{notification}</span> <button type="submit" style={{
float: 'right'
}} className={`${utilStyles.btnPrimary}`}>Publish</button>
<div>
<textarea style={{ width: '100%' }} value={title} className={`${utilStyles.headingLg}`}
onChange={({ target }) => setTitle(target.value)} placeholder="Title" />
</div>
<div>
<textarea style={{ width: '100%', height: '70vh' }} value={content} className={`${utilStyles.headingMd}`}
onChange={({ target }) => setContent(target.value)} placeholder="Content" />
</div>
<div>
<textarea style={{ width: '100%', height: '20vh' }} value={excerpt} className={`${utilStyles.headingMd}`}
onChange={({ target }) => setExcerpt(target.value)} placeholder="Excerpt, write a small description of the blog post" />
</div>
</form>
</div>
)
}
export default CreatePost;<file_sep>import Head from "next/head";
import Image from "next/image";
import styles from "./layout.module.css";
import utilStyles from "../styles/utils.module.css";
import Link from "next/link";
import { useRouter } from "next/router";
import fire from '../config/fire-config';
import { useState } from 'react';
const BLOG_NAME = "Life Via Window";
export const siteTitle = "Life Via Window | Blog";
export default function Layout({ children, home, create }) {
const [LoginStatus, setLoginStatus] = useState(false);
fire.auth()
.onAuthStateChanged((user) => {
if (user) {
setLoginStatus(true)
}
else {
setLoginStatus(false)
}
})
const handleLogout = () => {
fire.auth()
.signOut()
}
return (
<>
<div style={{ width: '100%', backgroundColor: 'black', color: 'white', position: 'fixed', top: 0, zIndex: 2 }} className="flexContainer">
<div style={{fontSize:'0.8em'}}>
<Link href="/"><a style={{ color: 'white' }}> Blog</a>
</Link>
{" | "}
<Link href="/apiinfo"><a style={{ color: 'white' }}>API</a>
</Link></div>
<button onClick={() => document.documentElement.scrollTop = 0} style={{ backgroundColor: 'transparent', color: 'white', paddingLeft: '5px', paddingRight: '5px', paddingTop: '0px', paddingBottom: '0px', fontSize: '24px' }}>
<strong> ᨑ </strong></button>
<div>
{LoginStatus ? (<>
<Link href="/create"><a style={{ color: 'white',fontSize:'0.75em' }}>+ New Post</a>
</Link>{" | "}<button onClick={() => handleLogout()} style={{fontSize:'0.75em'}}>Logout</button>
</>) : (<>
<Link href="/auth/register"><a style={{ color: 'white',fontSize:'0.75em' }}>Register</a></Link>{" | "}<Link href="/auth/login"><a style={{ color: 'white',fontSize:'0.75em' }}>Login</a></Link>
</>)}
</div>
</div>
<div className={styles.container}>
<Head>
<link rel="icon" href="/favicon.ico" />
<meta
name="description"
content="Learn how to build a personal website using Next.js"
/>
<meta
property="og:image"
content={`https://og-image.vercel.app/${encodeURI(
siteTitle
)}.png?theme=light&md=0&fontSize=75px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fnextjs-black-logo.svg`}
/>
<meta name="og:title" content={siteTitle} />
<meta name="twitter:card" content="summary_large_image" />
</Head>
<header className={styles.header}>
{home ? (
<>
<Image
priority
src="/images/profile.jpg"
className={utilStyles.borderCircle}
height={144}
width={144}
alt={BLOG_NAME}
/>
<h1 className={utilStyles.heading2Xl}>{BLOG_NAME}</h1>
</>
) : (
create ? (<></>) :
(<>
<Link href="/">
<a>
<Image
priority
src="/images/profile.jpg"
className={utilStyles.borderCircle}
height={108}
width={108}
alt={BLOG_NAME}
/>
</a>
</Link>
<h2 className={utilStyles.headingLg}>
<Link href="/">
<a className={utilStyles.colorInherit}>{BLOG_NAME}</a>
</Link>
</h2>
</>)
)}
</header>
<main>{children}</main>
{!home && (
<div className={styles.backToHome}>
<Link href="/">
<a>← Back to home</a>
</Link>
</div>
)}
</div>
</>
);
}
| 8156c28d5c802a659e56a66f1c96f7b893769148 | [
"JavaScript"
]
| 4 | JavaScript | vanssign/nextjs-blog | 48a9b7e102e6c1bc4ca02080b899e02c9cb4985a | 974822c57af8eb5b61845b5863a73626bd579b20 |
refs/heads/main | <file_sep># cifar10
CNN aplicada a Cifar10 con monitorización de overfitting y grabación de modelo óptimo.
Se usa la arquitectura VGGNet (light) y dos callbacks muy útiles:
- Monitorización, dibujando después de cada epoch los valores de loss y accuracy de los datasets de entrenamiento y validación. Así, podemos vigilar tras cada epoch si hay divergencia preocupante y detener el proceso si se presenta overfitting.
- Checkpoint, usando el callback ModelCheckpoint de Keras para grabar después de cada epoch solo los pesos cuando la accuracy aumente, descartando los epochs donde no lo haga.
El código se ejecuta desde la terminal con:
python fit_model.py -o output
En la ruta especificada tras el argumento -o se grabarán los archivos con el plot de último epoch, un json con el histórico de loss y accuracy y el modelo óptimo
<file_sep># Monitor - Detección de entrenamiento con overfitting
# Dibuja un gráfico con los valores de loss y accuracy tanto para en dataset de entrenamiento como para el de
# validación después de cada epoch. Si los valores de entrenamiento y validación empiezan a diverger demasiado,
# tendremos una indicación de overfitting.
# Esta clase se puede usar como parte de un callback de Keras.
from tensorflow.keras.callbacks import BaseLogger
import matplotlib.pyplot as plt
import numpy as np
import json
import os
class Monitor(BaseLogger):
def __init__(self, ruta_plot, ruta_json=None, comienzo=0):
# ruta_plot - Ruta donde se graba el plot de resultados de loss/accuracy de entrenamiento y validación
# ruta_json - Ruta donde se graba un json con datos de loss/accuracy
# comienzo - Epoch donde comienza la monitorización
super(Monitor, self).__init__()
self.ruta_plot = ruta_plot
self.ruta_json = ruta_json
self.comienzo = comienzo
def on_train_begin(self, logs={}):
# Diccionario donde se graba el historial con los datos de loss y accuracy
self.H = {}
# Carga el historial si existe el json
if self.ruta_json is not None:
if os.path.exists(self.ruta_json):
self.H = json.loads(open(self.ruta_json).read())
# Si hay variable comienzo suministrada, borra del historial lo que haya grabado después del epoch suministrado
if self.comienzo > 0:
for k in self.H.keys():
self.H[k] = self.H[k][:self.comienzo]
def on_epoch_end(self, epoch, logs={}):
# Actualiza el historial de loss y accuracy al final de cada epoch en el diccionario
for (k, v) in logs.items():
l = self.H.get(k, [])
l.append(v)
self.H[k] = l
# Graba historial a un archivo
if self.ruta_json is not None:
f = open(self.ruta_json, "w")
f.write(json.dumps(self.H))
f.close()
# Crea el plot con los loss y accuracy
if len(self.H["loss"]) > 1:
N = np.arange(0, len(self.H["loss"]))
plt.style.use("ggplot")
plt.figure()
plt.plot(N, self.H["loss"], label="train_loss")
plt.plot(N, self.H["val_loss"], label="val_loss")
plt.plot(N, self.H["accuracy"], label="train_acc")
plt.plot(N, self.H["val_accuracy"], label="val_acc")
plt.title("Training Loss & Accuracy [Epoch {}]".format(
len(self.H["loss"])))
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
# Graba el plot
plt.savefig(self.ruta_plot)
plt.close()
<file_sep>import matplotlib
matplotlib.use("Agg")
from clases.minivggnet import MiniVGGNet
from clases.monitor import Monitor
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.datasets import cifar10
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import ModelCheckpoint
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
import numpy as np
import argparse, os
epochs = 40
batch_size = 64
# Argumentos a indicar en terminal:
# output - Ruta donde se graba el plot de resultados de loss/accuracy de entrenamiento y validación,
# el json con el historial de loss/accuracy y los pesos tras cada epoch
# comienzo - epoch donde comienza la monitorización
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", required=True, help="Ruta al plot de loss/accuracy, json con historial y los pesos")
ap.add_argument("-c", "--comienzo", required=False, help="Epoch donde comienza la monitorización")
args = vars(ap.parse_args())
ruta_plot = os.path.sep.join([args["output"], "{}.png".format(os.getpid())])
ruta_json = os.path.sep.join([args["output"], "{}.json".format(os.getpid())])
ruta_modelo = os.path.sep.join([args["output"], "{}.hdf5".format(os.getpid())])
print("***** Cargando CIFAR-10...")
((trainX, trainY), (testX, testY)) = cifar10.load_data()
# Normaliza las imágenes tanto en el trainset como en el testset
trainX = trainX.astype("float") / 255.0
testX = testX.astype("float") / 255.0
# OneHotEncoding con las etiquetas
le = LabelBinarizer()
trainY = le.fit_transform(trainY)
testY = le.transform(testY)
labels = ["airplane", "car", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
# Definición del modelo, usando la clase MiniVGGNet
opt = SGD(lr=0.01, decay=0.01 / epochs, momentum=0.9, nesterov=True)
model = MiniVGGNet.build(width=32, height=32, depth=3, classes=10)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
# Crea un callback para la monitorización del entrenamiento
monitor = [Monitor(ruta_plot=ruta_plot, ruta_json=ruta_json)]
# Crea otro callback para la grabación del modelo solo cuando se produce una mejora de accuracy en
# el dataset de validación
checkpoint = ModelCheckpoint(ruta_modelo, monitor="val_accuracy", save_best_only=True, mode="max", verbose=1)
callbacks = [monitor, checkpoint]
print("**** Training...")
H = model.fit(trainX, trainY,
validation_data=(testX, testY),
batch_size=batch_size,
epochs=epochs,
callbacks=[callbacks],
verbose=1)
print("**** Evaluating...")
predictions = model.predict(testX, batch_size=batch_size)
print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=labels))
| 092088a91657d6534c092098903a0f214616bcb0 | [
"Markdown",
"Python"
]
| 3 | Markdown | joselquin/cifar10 | 1a23d097b25b8a4d0ae9e27b0addf640348166f7 | 74932a57410f39861e8fa820cfa29631a936a652 |
refs/heads/master | <repo_name>hassan-irshad/CampusRecruitmentSystem<file_sep>/src/components/App.js
import React from 'react';
import Login from './Login';
import StudentHome from './StudentHome'
function App() {
return (
<div>
<StudentHome />
</div>
);
}
export default App;
<file_sep>/src/components/StudentHome.js
import React, { Component } from 'react';
import 'font-awesome/css/font-awesome.min.css';
import '../css/student_home.css'
class StudentHome extends Component {
// openSlideMenu = () => {
// document.getElementById('menu').style.width = '250px';
// document.getElementById('content').style.marginLeft = '250px';
// }
// closeSlideMenu = () => {
// document.getElementById('menu').style.width = '0';
// document.getElementById('content').style.marginLeft = '0';
// }
render() {
return (
<div id='content'>
<div id='menu' className='nav'>
<div className="logo">
<img src={require('../assets/university.png')} width="70px" />
</div>
<a href='#'><i className="fa fa-user-circle"></i>Profile</a>
<a href='#'><i className="fa fa-window-maximize"></i>Noticeboard</a>
<a href='#'><i className="fa fa-users"></i>Companies</a>
<a href="#"><i className="fa fa-sticky-note"></i>Jobs</a>
</div>
<div className="navbar">
<h2>Profile</h2>
<div className="nav-right">
<img src={require('../assets/mathew.png')} width="45px" />
<span>Logout</span>
</div>
</div>
<div className='body'>
<div className="ui card">
<div className="image"><img src={require('../assets/mathew.png')} /></div>
<div className="content">
<div className="header">Matthew</div>
<div className="meta"><span className="date">Joined in 2015</span></div>
<div className="description">Matthew is a musician living in Nashville.</div>
</div>
<div className="extra content">
<a>
<i aria-hidden="true" className="user icon"></i>
22 Friends
</a>
</div>
</div>
<form className="ui form">
<h1>Details</h1>
<div className="two fields">
<div className="field">
<label>Name</label>
<div className="ui fluid input"><input type="text" placeholder="Read only" readonly="" /></div>
</div>
<div className="field">
<label>Department</label>
<div className="ui fluid input"><input type="text" placeholder="Read only" readonly="" /></div>
</div>
<div>
</div>
</div>
<div className="two fields">
<div className="field">
<label>Age</label>
<div className="ui input"><input type="text" placeholder="Address" /></div>
</div>
<div className="field">
<label>Gender</label>
<div className="ui input"><input type="text" placeholder="Phone" /></div>
</div>
</div>
<div className="two fields">
<div className="field">
<label>Measure</label>
<div className="ui input"><input type="text" placeholder="Address" /></div>
</div>
<div className="field">
<label>CGPA</label>
<div className="ui input"><input type="text" placeholder="Phone" /></div>
</div>
</div>
<div className="two fields">
<div className="field">
<label>Skills</label>
<div className="ui input"><input type="text" placeholder="Address" /></div>
</div>
<div className="field">
<label>Hobbies</label>
<div className="ui input"><input type="text" placeholder="Phone" /></div>
</div>
</div>
</form>
</div>
</div>
)
}
}
export default StudentHome;<file_sep>/src/components/Login.js
import React, { Component } from 'react'
import { Header, Image, Button, Checkbox, Form } from 'semantic-ui-react'
import '../css/login.css'
class Login extends Component {
render() {
return (
<div className="custom-form">
<Form>
<div className='logo'>
<Image src={require('../assets/university.png')} size='small' />
<Header as='h3'>Campus Recruitment System</Header>
</div>
<Header as='h2' className='header-login'>Login</Header>
<Form.Field>
<label>Email</label>
<input placeholder='Email' />
</Form.Field>
<Form.Field>
<label>Password</label>
<input placeholder='<PASSWORD>' />
</Form.Field>
<Button type='submit'>Submit</Button>
</Form>
</div>
)
}
}
export default Login | 585c147dea9f2637dadd5a21d6915c030f0b0908 | [
"JavaScript"
]
| 3 | JavaScript | hassan-irshad/CampusRecruitmentSystem | c0169b53c75007ad77faaf500ab0f3b7d42cadd0 | 9baf0f208fb6d0c08054742b43fa806fd781529a |
refs/heads/master | <file_sep># 2.0.0 (2016-07-28)
* Update to Jasmine 2.4
# 1.3.0 (2015-09-17)
* Spec file list is now `glob`-able
* Renamed binary to be consistent with module name
# 1.2.0 (2015-09-03)
* Add a grunt task to support execution of `minijasminenode23` on grunt
# 1.1.0 (2015-08-31)
* [b4b5571](https://github.com/theogravity/minijasminenode23/pull/3) Add custom default reporter
## 1.0.0-beta.1
This change migrates to using Jasmine 2.0, and thus contains any [breaking changes](http://jasmine.github.io/2.0/upgrading.html) from
Jasmine 1.3.1 to Jasmine 2.0.
Notably
- The interface for reporters has completely changed
- The interface for custom matchers has changed
- per-spec timeouts (e.g. `it('does foo', fn, 1000))` no longer work
If you would like to continue using MiniJasmineNode against Jamsmine 1.3.1, please use version 0.4.0. This can be downloaded with `npm install minijasminenode@jasmine1`.
<file_sep>minijasminenode23
======
[`minijasminenode`](https://github.com/juliemr/minijasminenode) with Jasmine version 2.4 under the hood.
*Original fork from [juliemr](https://github.com/juliemr/minijasminenode) with an initial update from [xdissent](https://github.com/xdissent) to use Jasmine 2.1 (which has since been updated to 2.4).*
Based on Jasmine-Node, but minus the fancy stuff.
This node.js module makes Pivotal Lab's Jasmine
(http://github.com/pivotal/jasmine) spec framework available in
node.js or via the command line.
features
--------
MiniJasmineNode23 exports a library which
- places Jasmine in Node's global namespace, similar to how it's run in a browser.
- adds result reporters for the terminal.
- adds the ability to load tests from file.
- adds focused specs with `iit` and `ddescribe`.
- adds `xdescribe`, `fdescribe`, `xit`, `fit`, `beforeEach`, `afterEach`, `beforeAll`, `afterAll`
- specification of spec file locations are `glob`-able
The module also contains a command line wrapper.
installation
------------
Get the library with
npm install minijasminenode23
Or, install globally
npm install -g minijasminenode23
If you install globally, you can use minijasminenode directly from the command line
minijasminenode23 mySpecFolder/mySpec.js
See more options
minijasminenode23 --help
usage
-----
```javascript
// Your test file - mySpecFolder/mySpec.js
describe('foo', function() {
it('should pass', function() {
expect(2 + 2).toEqual(4);
});
});
```
```javascript
var miniJasmineLib = require('minijasminenode23');
// At this point, jasmine is available in the global node context.
// Add your tests by filename.
miniJasmineLib.addSpecs('myTestFolder/mySpec.js');
// If you'd like to add a custom Jasmine reporter, you can do so. Tests will
// be automatically reported to the terminal.
miniJasmineLib.addReporter(myCustomReporter);
// Run those tests!
miniJasmineLib.executeSpecs(options);
```
You can also pass an options object into `executeSpecs`
````javascript
var miniJasmineLib = require('minijasminenode23');
var options = {
// An array of filenames, relative to current dir. These will be
// executed, as well as any tests added with addSpecs()
specs: ['specDir/mySpec1.js', 'specDir/mySpec2.js', 'specDir/**/*.spec.js'],
// A function to call on completion.
// function(passed)
onComplete: function(passed) { console.log('done!'); },
// If true, display suite and spec names.
isVerbose: false,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Time to wait in milliseconds before a test automatically fails
defaultTimeoutInterval: 5000
};
miniJasmineLib.executeSpecs(options);
````
If you want a custom runner instead of the default add it as an option into `executeSpecs`
```javascript
var miniJasmineLib = require('minijasminenode23');
var myCustomReporter = require('myCustomReporter');
// At this point, jasmine is available in the global node context.
// Add your tests by filename.
miniJasmineLib.addSpecs('myTestFolder/mySpec.js');
// Run those tests!
miniJasmineLib.executeSpecs({
reporter: myCustomReporter
});
```
Grunt Task
----------
A `Grunt` task is included, called `jasmine23`:
```javascript
module.exports = function(grunt) {
grunt.loadNpmTasks('minijasminenode23')
grunt.initConfig({
jasmine23: {
dev: {
// Standard options apply here
options: {
// An array of filenames, relative to current dir. These will be
// executed, as well as any tests added with addSpecs()
specs: ['test/unit/**/*.spec.js'],
// A function to call on completion.
// function(passed)
onComplete: function(passed) { console.log('done!') },
// If true, display suite and spec names.
isVerbose: true,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Time to wait in milliseconds before a test automatically fails
defaultTimeoutInterval: 5000
}
}
}
})
grunt.registerTask('default', ['jasmine23:dev'])
```
to run the tests
----------------
`./specs.sh`
This will run passing tests as well as show examples of how failures look. To run only passing tests, use `npm test` or `./bin/minijasminenode23 spec/*_spec.js`
<file_sep>'use strict'
var miniJasmineLib = require('../lib')
module.exports = function(grunt) {
grunt.registerMultiTask('jasmine23', 'Runs Jasmine against unit tests', function () {
var done = this.async()
var conf = this.options({
onComplete: function(passed) { console.log('done!') },
isVerbose: true,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 5000
})
var onComplete = conf.onComplete
conf.onComplete = function(passed) {
onComplete(passed)
if (passed) {
grunt.log.ok('all tests passed!')
done(true)
} else {
throw grunt.task.taskError('jasmine23 failure')
}
}
miniJasmineLib.executeSpecs(conf)
})
}
| 0eb50522da59e8967ff33f4a48a4fa54cb991e7e | [
"Markdown",
"JavaScript"
]
| 3 | Markdown | theogravity/minijasminenode23 | ca055700c2a6a31b81da9664dd191441c7dc8367 | cde7ee683ab13c840e192e33f473c879a7be76eb |
refs/heads/master | <file_sep>#
# 定义 mysql 镜像
#
FROM mysql:5.7
RUN set -x \
# 设置 apt-get包的源
&& echo "deb http://mirrors.163.com/debian/ jessie main non-free contrib \
deb http://mirrors.163.com/debian/ jessie-updates main non-free contrib \
deb http://mirrors.163.com/debian/ jessie-backports main non-free contrib \
deb-src http://mirrors.163.com/debian/ jessie main non-free contrib \
deb-src http://mirrors.163.com/debian/ jessie-updates main non-free contrib \
deb-src http://mirrors.163.com/debian/ jessie-backports main non-free contrib \
deb http://mirrors.163.com/debian-security/ jessie/updates main non-free contrib \
deb-src http://mirrors.163.com/debian-security/ jessie/updates main non-free contrib" > /etc/apt/sources.list \
# 更新 apt-get 包索引
&& apt-get update \
# 安装 常用包\
&& apt-get install -y --allow-remove-essential libtinfo5 \
&& apt-get install -y bash vim libtinfo5 tzdata \
# 设置时区和时间
&& echo 'Asia/Shanghai' > /etc/timezone \
&& cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \<file_sep><?php
header('X-Accel-Buffering: no');
header("Content-Type: text/html; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
try {
if (strtolower($_SERVER['REQUEST_METHOD']) == 'options') {
exit;
}
function debug(){
if(!empty($_REQUEST)){
file_put_contents("./test.log", var_export($_REQUEST, true).PHP_EOL.PHP_EOL.PHP_EOL, FILE_APPEND);
}
}
function mysql(){
try {
$pdo = new PDO('mysql:host=mysql;port=3306;dbname=test', 'root', 'ling520');
$res = $pdo->query("SELECT * FROM `test`")->fetchAll();
var_dump($res);
// $redis = new redis();
// $redis->connect('redis', 6379);
// $redis->select(0);
// $keys = $redis->lrange('maxwell', 0, -1);
// var_dump($keys);
die();
} catch (PDOException $e) {
echo $e->getMessage();
}
}
// mysql();
debug();
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
<script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script type="text/javascript">
$.ajax({
url: "http://dev-api.idaddy.cn/admin4/category:list?caller=3010",
type: "GET",
headers: {
"Authorization": "<KEY>"
},
success: function(d) {
consolo.log(d);
}
});
</script>
<file_sep># Makefile文件的绝对路径
CUR_MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
# docker web network名称
NETWORK_NAME := web-network
docker := docker
# Makefile的所在目录的绝对路径
export CUR_MKFILE_DIR := $(patsubst %/, %, $(dir $(CUR_MKFILE_PATH)))
# export VOLUME_PATH = e:/mywork/lnmp
export VOLUME_PATH = $(CUR_MKFILE_DIR)
test:
echo $(CUR_MKFILE_PATH)
echo $(CUR_MKFILE_DIR)
echo $(VOLUME_PATH)
# 定义忽略错误的tag
.IGNORE:deploy-network
# 部署所有应用容器 注意部署的启动顺序,是按照依赖关系先后
deploy:deploy-network deploy-mysql deploy-redis deploy-php deploy-nginx
# 部署docker web网络系统(目的:将相关容器部署在同一网络下,可直接使用容器名通信)
deploy-network:
$(docker) network create --driver bridge $(NETWORK_NAME)
# 部署mysql容器
deploy-mysql:
$(docker) build -t mysql -f $(CUR_MKFILE_DIR)/Dockerfiles/Dockerfile.mysql .
$(docker) run -d --restart=always -p 3306:3306 --network $(NETWORK_NAME) -e MYSQL_ROOT_PASSWORD=<PASSWORD> \
-v /data/docker_mysql:/var/lib/mysql \
-v $(VOLUME_PATH)/sys_cfg/mysql:/etc/mysql \
--name mysql mysql
# 部署redis容器
deploy-redis:
$(docker) build -t redis -f $(CUR_MKFILE_DIR)/Dockerfiles/Dockerfile.redis .
$(docker) run -d --restart=always -p 6379:6379 --network $(NETWORK_NAME) \
--name redis redis
# 部署php-fpm容器
deploy-php:
$(docker) build -t web-php -f $(CUR_MKFILE_DIR)/Dockerfiles/Dockerfile.php-fpm .
$(docker) run -d --restart=always --network $(NETWORK_NAME) \
-v $(VOLUME_PATH):/home/wwwroot/test \
--name web-php web-php
# 部署nginx容器
deploy-nginx:
$(docker) build -t web-nginx -f $(CUR_MKFILE_DIR)/Dockerfiles/Dockerfile.nginx .
$(docker) run -d --restart=always -p 80:80 --network $(NETWORK_NAME) \
-v $(VOLUME_PATH):/home/wwwroot/test \
--name web-nginx web-nginx
# 部署 Maxwell
deploy-maxwell:
$(docker) run -d --restart=always --network $(NETWORK_NAME) \
--name maxwell zendesk/maxwell \
bin/maxwell --user=root --password=<PASSWORD> --host=mysql --output_ddl=true --producer=redis \
--redis_host=redis --redis_type=lpush --redis_list_key=maxwell
# 重启nginx,php进程
reload:
$(docker) exec web-nginx nginx -s reload
$(docker) exec web-php kill -SIGUSR2 1
# 删除所有部署
undeploy:
-$(docker) rm -f web-php
-$(docker) rm -f web-nginx
-$(docker) rm -f mysql
-$(docker) rm -f redis
-$(docker) rm -f maxwell
| 84d38a3fa0eef5513859953076ad44bf35c8ca7c | [
"SQL",
"Makefile",
"PHP"
]
| 3 | SQL | 1147832740/test | d58cb2cf4bbd8adbcdb55b19195be7e3e1ec3a63 | 73ca434e7589279077dfeefcddf717308b9fced8 |
refs/heads/master | <file_sep>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import argparse
import multiprocessing
import os
import platform
import sys
from collections import defaultdict
from subprocess import run
from typing import Dict, List, NamedTuple, Optional, Tuple
from rich.console import Console
from tabulate import tabulate
from docs.exts.docs_build import dev_index_generator, lint_checks # pylint: disable=no-name-in-module
from docs.exts.docs_build.code_utils import (
CONSOLE_WIDTH,
DOCKER_PROJECT_DIR,
ROOT_PROJECT_DIR,
TEXT_RED,
TEXT_RESET,
)
from docs.exts.docs_build.docs_builder import ( # pylint: disable=no-name-in-module
DOCS_DIR,
AirflowDocsBuilder,
get_available_packages,
)
from docs.exts.docs_build.errors import ( # pylint: disable=no-name-in-module
DocBuildError,
display_errors_summary,
)
from docs.exts.docs_build.fetch_inventories import fetch_inventories # pylint: disable=no-name-in-module
from docs.exts.docs_build.github_action_utils import with_group # pylint: disable=no-name-in-module
from docs.exts.docs_build.package_filter import process_package_filters # pylint: disable=no-name-in-module
from docs.exts.docs_build.spelling_checks import ( # pylint: disable=no-name-in-module
SpellingError,
display_spelling_error_summary,
)
if __name__ != "__main__":
raise SystemExit(
"This file is intended to be executed as an executable program. You cannot use it as a module."
"To run this script, run the ./build_docs.py command"
)
CHANNEL_INVITATION = """\
If you need help, write to #documentation channel on Airflow's Slack.
Channel link: https://apache-airflow.slack.com/archives/CJ1LVREHX
Invitation link: https://s.apache.org/airflow-slack\
"""
ERRORS_ELIGIBLE_TO_REBUILD = [
'failed to reach any of the inventories with the following issues',
'undefined label:',
'unknown document:',
]
ON_GITHUB_ACTIONS = os.environ.get('GITHUB_ACTIONS', 'false') == "true"
console = Console(force_terminal=True, color_system="standard", width=CONSOLE_WIDTH)
def _promote_new_flags():
console.print()
console.print("[yellow]Still tired of waiting for documentation to be built?[/]")
console.print()
if ON_GITHUB_ACTIONS:
console.print("You can quickly build documentation locally with just one command.")
console.print(" [blue]./breeze build-docs[/]")
console.print()
console.print("[yellow]Still too slow?[/]")
console.print()
console.print("You can only build one documentation package:")
console.print(" [blue]./breeze build-docs -- --package-filter <PACKAGE-NAME>[/]")
console.print()
console.print("This usually takes from [yellow]20 seconds[/] to [yellow]2 minutes[/].")
console.print()
console.print("You can also use other extra flags to iterate faster:")
console.print(" [blue]--docs-only - Only build documentation[/]")
console.print(" [blue]--spellcheck-only - Only perform spellchecking[/]")
console.print()
console.print("For more info:")
console.print(" [blue]./breeze build-docs --help[/]")
console.print()
def _get_parser():
available_packages_list = " * " + "\n * ".join(get_available_packages())
parser = argparse.ArgumentParser(
description='Builds documentation and runs spell checking',
epilog=f"List of supported documentation packages:\n{available_packages_list}",
)
parser.formatter_class = argparse.RawTextHelpFormatter
parser.add_argument(
'--disable-checks', dest='disable_checks', action='store_true', help='Disables extra checks'
)
parser.add_argument(
"--package-filter",
action="append",
help=(
"Filter specifying for which packages the documentation is to be built. Wildcard are supported."
),
)
parser.add_argument('--docs-only', dest='docs_only', action='store_true', help='Only build documentation')
parser.add_argument(
'--spellcheck-only', dest='spellcheck_only', action='store_true', help='Only perform spellchecking'
)
parser.add_argument(
'--for-production',
dest='for_production',
action='store_true',
help='Builds documentation for official release i.e. all links point to stable version',
)
parser.add_argument(
"-j",
"--jobs",
dest='jobs',
type=int,
default=1,
help=(
"""
Number of parallel processes that will be spawned to build the docs.
This is usually used in CI system only. Though you can also use it to run complete check
of the documntation locally if you have powerful local machine.
Default is 1 - which means that doc check runs sequentially, This is the default behaviour
because autoapi extension we use is not capable of running parallel builds at the same time using
the same source files.
In parallel builds we are using dockerised version of image built from local sources but the image
has to be prepared locally (similarly as it is in CI) before you run the docs build. Any changes you
have done locally after building the image, will not be checked.
Typically you run parallel build in this way if you want to quickly run complete check for all docs:
./breeze build-image --python 3.6
./docs/build-docs.py -j 0
"""
),
)
parser.add_argument(
"-v",
"--verbose",
dest='verbose',
action='store_true',
help=(
'Increases the verbosity of the script i.e. always displays a full log of '
'the build process, not just when it encounters errors'
),
)
return parser
class BuildSpecification(NamedTuple):
"""Specification of single build."""
package_name: str
for_production: bool
verbose: bool
dockerized: bool
class BuildDocsResult(NamedTuple):
"""Result of building documentation."""
package_name: str
log_file_name: str
errors: List[DocBuildError]
class SpellCheckResult(NamedTuple):
"""Result of spellcheck."""
package_name: str
log_file_name: str
errors: List[SpellingError]
def perform_docs_build_for_single_package(build_specification: BuildSpecification) -> BuildDocsResult:
"""Performs single package docs build."""
builder = AirflowDocsBuilder(
package_name=build_specification.package_name, for_production=build_specification.for_production
)
console.print(f"[blue]{build_specification.package_name:60}:[/] Building documentation")
result = BuildDocsResult(
package_name=build_specification.package_name,
errors=builder.build_sphinx_docs(
dockerized=build_specification.dockerized,
verbose=build_specification.verbose,
),
log_file_name=builder.log_build_filename,
)
return result
def perform_spell_check_for_single_package(build_specification: BuildSpecification) -> SpellCheckResult:
"""Performs single package spell check."""
builder = AirflowDocsBuilder(
package_name=build_specification.package_name, for_production=build_specification.for_production
)
console.print(f"[blue]{build_specification.package_name:60}:[/] Checking spelling started")
result = SpellCheckResult(
package_name=build_specification.package_name,
errors=builder.check_spelling(
dockerized=build_specification.dockerized,
verbose=build_specification.verbose,
),
log_file_name=builder.log_spelling_filename,
)
console.print(f"[blue]{build_specification.package_name:60}:[/] Checking spelling completed")
return result
def build_docs_for_packages(
current_packages: List[str],
docs_only: bool,
spellcheck_only: bool,
for_production: bool,
jobs: int,
verbose: bool,
) -> Tuple[Dict[str, List[DocBuildError]], Dict[str, List[SpellingError]]]:
"""Builds documentation for all packages and combines errors."""
all_build_errors: Dict[str, List[DocBuildError]] = defaultdict(list)
all_spelling_errors: Dict[str, List[SpellingError]] = defaultdict(list)
with with_group("Cleaning documentation files"):
for package_name in current_packages:
console.print(f"[blue]{package_name:60}:[/] Cleaning files")
builder = AirflowDocsBuilder(package_name=package_name, for_production=for_production)
builder.clean_files()
if jobs > 1:
if os.getenv('CI', '') == '':
console.print("[yellow] PARALLEL DOCKERIZED EXECUTION REQUIRES IMAGE TO BE BUILD BEFORE !!!![/]")
console.print("[yellow] Make sure that you've build the image before runnning docs build.[/]")
console.print("[yellow] otherwise local changes you've done will not be used during the check[/]")
console.print()
run_in_parallel(
all_build_errors,
all_spelling_errors,
current_packages,
docs_only,
for_production,
jobs,
spellcheck_only,
verbose,
)
else:
run_sequentially(
all_build_errors,
all_spelling_errors,
current_packages,
docs_only,
for_production,
spellcheck_only,
verbose,
)
return all_build_errors, all_spelling_errors
def run_sequentially(
all_build_errors,
all_spelling_errors,
current_packages,
docs_only,
for_production,
spellcheck_only,
verbose,
):
"""Run both - spellcheck and docs build sequentially without multiprocessing"""
if not spellcheck_only:
for package_name in current_packages:
build_result = perform_docs_build_for_single_package(
build_specification=BuildSpecification(
package_name=package_name,
for_production=for_production,
dockerized=False,
verbose=verbose,
)
)
if build_result.errors:
all_build_errors[package_name].extend(build_result.errors)
print_build_output(build_result)
if not docs_only:
for package_name in current_packages:
spellcheck_result = perform_spell_check_for_single_package(
build_specification=BuildSpecification(
package_name=package_name,
for_production=for_production,
dockerized=False,
verbose=verbose,
)
)
if spellcheck_result.errors:
all_spelling_errors[package_name].extend(spellcheck_result.errors)
print_spelling_output(spellcheck_result)
def run_in_parallel(
all_build_errors,
all_spelling_errors,
current_packages,
docs_only,
for_production,
jobs,
spellcheck_only,
verbose,
):
"""Run both - spellcheck and docs build sequentially without multiprocessing"""
pool = multiprocessing.Pool(processes=jobs)
# until we fix autoapi, we need to run parallel builds as dockerized images
dockerized = True
if not spellcheck_only:
run_docs_build_in_parallel(
all_build_errors=all_build_errors,
for_production=for_production,
current_packages=current_packages,
verbose=verbose,
dockerized=dockerized,
pool=pool,
)
if not docs_only:
run_spell_check_in_parallel(
all_spelling_errors=all_spelling_errors,
for_production=for_production,
current_packages=current_packages,
verbose=verbose,
dockerized=dockerized,
pool=pool,
)
fix_ownership()
def fix_ownership():
"""Fixes ownership for all files created with root user,"""
console.print("Fixing ownership for generated files")
python_version = os.getenv('PYTHON_MAJOR_MINOR_VERSION', "3.6")
fix_cmd = [
"docker",
"run",
"--entrypoint",
"/bin/bash",
"--rm",
"-e",
f"HOST_OS={platform.system()}",
"-e" f"HOST_USER_ID={os.getuid()}",
"-e",
f"HOST_GROUP_ID={os.getgid()}",
"-v",
f"{ROOT_PROJECT_DIR}:{DOCKER_PROJECT_DIR}",
f"apache/airflow:master-python{python_version}-ci",
"-c",
"/opt/airflow/scripts/in_container/run_fix_ownership.sh",
]
run(fix_cmd, check=True)
def print_build_output(result: BuildDocsResult):
"""Prints output of docs build job."""
with with_group(f"{TEXT_RED}Output for documentation build {result.package_name}{TEXT_RESET}"):
console.print()
console.print(f"[blue]{result.package_name:60}: " + "#" * 80)
with open(result.log_file_name) as output:
for line in output.read().splitlines():
console.print(f"{result.package_name:60} {line}")
console.print(f"[blue]{result.package_name:60}: " + "#" * 80)
def run_docs_build_in_parallel(
all_build_errors: Dict[str, List[DocBuildError]],
for_production: bool,
current_packages: List[str],
verbose: bool,
dockerized: bool,
pool,
):
"""Runs documentation building in parallel."""
doc_build_specifications: List[BuildSpecification] = []
with with_group("Scheduling documentation to build"):
for package_name in current_packages:
console.print(f"[blue]{package_name:60}:[/] Scheduling documentation to build")
doc_build_specifications.append(
BuildSpecification(
package_name=package_name,
for_production=for_production,
verbose=verbose,
dockerized=dockerized,
)
)
with with_group("Running docs building"):
console.print()
result_list = pool.map(perform_docs_build_for_single_package, doc_build_specifications)
for result in result_list:
if result.errors:
all_build_errors[result.package_name].extend(result.errors)
print_build_output(result)
def print_spelling_output(result: SpellCheckResult):
"""Prints output of spell check job."""
with with_group(f"{TEXT_RED}Output for spelling check: {result.package_name}{TEXT_RESET}"):
console.print()
console.print(f"[blue]{result.package_name:60}: " + "#" * 80)
with open(result.log_file_name) as output:
for line in output.read().splitlines():
console.print(f"{result.package_name:60} {line}")
console.print(f"[blue]{result.package_name:60}: " + "#" * 80)
console.print()
def run_spell_check_in_parallel(
all_spelling_errors: Dict[str, List[SpellingError]],
for_production: bool,
current_packages: List[str],
verbose: bool,
dockerized: bool,
pool,
):
"""Runs spell check in parallel."""
spell_check_specifications: List[BuildSpecification] = []
with with_group("Scheduling spell checking of documentation"):
for package_name in current_packages:
console.print(f"[blue]{package_name:60}:[/] Scheduling spellchecking")
spell_check_specifications.append(
BuildSpecification(
package_name=package_name,
for_production=for_production,
verbose=verbose,
dockerized=dockerized,
)
)
with with_group("Running spell checking of documentation"):
console.print()
result_list = pool.map(perform_spell_check_for_single_package, spell_check_specifications)
for result in result_list:
if result.errors:
all_spelling_errors[result.package_name].extend(result.errors)
print_spelling_output(result)
def display_packages_summary(
build_errors: Dict[str, List[DocBuildError]], spelling_errors: Dict[str, List[SpellingError]]
):
"""Displays a summary that contains information on the number of errors in each packages"""
packages_names = {*build_errors.keys(), *spelling_errors.keys()}
tabular_data = [
{
"Package name": f"[blue]{package_name}[/]",
"Count of doc build errors": len(build_errors.get(package_name, [])),
"Count of spelling errors": len(spelling_errors.get(package_name, [])),
}
for package_name in sorted(packages_names, key=lambda k: k or '')
]
console.print("#" * 20, " Packages errors summary ", "#" * 20)
console.print(tabulate(tabular_data=tabular_data, headers="keys"))
console.print("#" * 50)
def print_build_errors_and_exit(
build_errors: Dict[str, List[DocBuildError]],
spelling_errors: Dict[str, List[SpellingError]],
) -> None:
"""Prints build errors and exists."""
if build_errors or spelling_errors:
if build_errors:
display_errors_summary(build_errors)
console.print()
if spelling_errors:
display_spelling_error_summary(spelling_errors)
console.print()
console.print("The documentation has errors.")
display_packages_summary(build_errors, spelling_errors)
console.print()
console.print(CHANNEL_INVITATION)
sys.exit(1)
else:
console.print("[green]Documentation build is successful[/]")
def main():
"""Main code"""
args = _get_parser().parse_args()
available_packages = get_available_packages()
docs_only = args.docs_only
spellcheck_only = args.spellcheck_only
disable_checks = args.disable_checks
package_filters = args.package_filter
for_production = args.for_production
with with_group("Available packages"):
for pkg in sorted(available_packages):
console.print(f" - {pkg}")
if package_filters:
console.print("Current package filters: ", package_filters)
current_packages = process_package_filters(available_packages, package_filters)
with with_group("Fetching inventories"):
# Inventories that could not be retrieved should be retrieved first. This may mean this is a
# new package.
priority_packages = fetch_inventories()
current_packages = sorted(current_packages, key=lambda d: -1 if d in priority_packages else 1)
jobs = args.jobs if args.jobs != 0 else os.cpu_count()
with with_group(
f"Documentation will be built for {len(current_packages)} package(s) with {jobs} parallel jobs"
):
for pkg_no, pkg in enumerate(current_packages, start=1):
console.print(f"{pkg_no}. {pkg}")
all_build_errors: Dict[Optional[str], List[DocBuildError]] = {}
all_spelling_errors: Dict[Optional[str], List[SpellingError]] = {}
package_build_errors, package_spelling_errors = build_docs_for_packages(
current_packages=current_packages,
docs_only=docs_only,
spellcheck_only=spellcheck_only,
for_production=for_production,
jobs=jobs,
verbose=args.verbose,
)
if package_build_errors:
all_build_errors.update(package_build_errors)
if package_spelling_errors:
all_spelling_errors.update(package_spelling_errors)
to_retry_packages = [
package_name
for package_name, errors in package_build_errors.items()
if any(any((m in e.message) for m in ERRORS_ELIGIBLE_TO_REBUILD) for e in errors)
]
if to_retry_packages:
for package_name in to_retry_packages:
if package_name in all_build_errors:
del all_build_errors[package_name]
if package_name in all_spelling_errors:
del all_spelling_errors[package_name]
package_build_errors, package_spelling_errors = build_docs_for_packages(
current_packages=to_retry_packages,
docs_only=docs_only,
spellcheck_only=spellcheck_only,
for_production=for_production,
jobs=jobs,
verbose=args.verbose,
)
if package_build_errors:
all_build_errors.update(package_build_errors)
if package_spelling_errors:
all_spelling_errors.update(package_spelling_errors)
if not disable_checks:
general_errors = lint_checks.run_all_check()
if general_errors:
all_build_errors[None] = general_errors
dev_index_generator.generate_index(f"{DOCS_DIR}/_build/index.html")
if not package_filters:
_promote_new_flags()
print_build_errors_and_exit(
all_build_errors,
all_spelling_errors,
)
main()
| d6bb6b4e725fb270834efe7ae4099748c52062a9 | [
"Python"
]
| 1 | Python | RefiPeretz/airflow | 64b00896d905abcf1fbae195a29b81f393319c5f | 001ab21738d081264cc6a4b695888f512fff1d28 |
refs/heads/master | <repo_name>mah-sh-ee/tint<file_sep>/front-develop/gulpfile.js
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
postcss = require('gulp-postcss'),
cssnext = require('postcss-cssnext'),
coffee = require('gulp-coffee'),
plumber = require('gulp-plumber'),
notify = require('gulp-notify'),
uglify = require('gulp-uglify'),
cache = require('gulp-cached'),
browserSync = require("browser-sync");
var proxyRoot = "http://tint.test/";
var paths = {
images: {
src: './assets/images/',
files: './assets/images/**/*.png',
dest: '../assets/img/'
},
styles: {
src: './**/stylesheets/sass',
srcEn: './assets/stylesheets/sass/main/style.scss',
srcJa: './cocoon/stylesheets/sass/main/style.scss',
files: './**/stylesheets/sass/**/*.scss',
filesJa: './cocoon/stylesheets/sass/**/*.scss',
destEn: '../wp-content/themes/simplicity2-child/',
destJa: '../wp-content/themes/cocoon-child-master/'
},
coffee: {
src: './assets/javascripts/coffee/',
files: './assets/javascripts/coffee/*.coffee',
dest: '../assets/js/'
}
};
// var AUTOPREFIXER_BROWSERS = [
// 'last 2 version',
// 'ie >= 9',
// 'iOS >= 7',
// 'Android >= 4.2'
// ];
gulp.task("browserSyncTask", function () {
browserSync.init({
proxy: proxyRoot
});
});
gulp.task('browserSyncReload', function () {
browserSync.reload();
});
gulp.task('sassEn', function() {
var processors = [
cssnext({ browsers: 'last 2 versions' })
];
return gulp.src(paths.styles.srcEn)
// .pipe(cache('sass'))
.pipe(plumber({
errorHandler: notify.onError('Error: <%= error.message %>')
}))
.pipe(sass({outputStyle: 'compressed'}))
.pipe(postcss(processors))
.pipe(gulp.dest(paths.styles.destEn));
});
gulp.task('sassJa', function() {
var processors = [
cssnext({ browsers: 'last 2 versions' })
];
return gulp.src(paths.styles.srcJa)
// .pipe(cache('sass'))
.pipe(plumber({
errorHandler: notify.onError('Error: <%= error.message %>')
}))
.pipe(sass({outputStyle: 'compressed'}))
.pipe(postcss(processors))
.pipe(gulp.dest(paths.styles.destJa));
});
// gulp.task('coffee', function() {
// return gulp.src(paths.coffee.files)
// .pipe(plumber({
// errorHandler: notify.onError("Error: <%= error.message %>")
// }))
// .pipe(coffee())
// .pipe(uglify())
// .pipe(gulp.dest(paths.coffee.dest))
// });
gulp.task('default', ['browserSyncTask'] , function() {
gulp.watch(paths.styles.files, ['sassEn', 'sassJa' , 'browserSyncReload']);
// gulp.watch(paths.coffee.files, ['coffee']);
});
<file_sep>/wp-content/themes/simplicity2-child/functions.php
<?php //子テーマ用関数
//親skins の取得有無の設定
function include_parent_skins(){
return true; //親skinsを含める場合はtrue、含めない場合はfalse
}
//子テーマ用のビジュアルエディタースタイルを適用
add_editor_style();
//以下にSimplicity子テーマ用の関数を書く
//Custom CSS Widget
add_action('admin_menu', 'custom_css_hooks');
add_action('save_post', 'save_custom_css');
add_action('wp_head','insert_custom_css');
function custom_css_hooks() {
add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'post', 'normal', 'high');
add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'page', 'normal', 'high');
}
function custom_css_input() {
global $post;
echo '<input type="hidden" name="custom_css_noncename" id="custom_css_noncename" value="'.wp_create_nonce('custom-css').'" />';
echo '<textarea name="custom_css" id="custom_css" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_custom_css',true).'</textarea>';
}
function save_custom_css($post_id) {
if (!wp_verify_nonce($_POST['custom_css_noncename'], 'custom-css')) return $post_id;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
$custom_css = $_POST['custom_css'];
update_post_meta($post_id, '_custom_css', $custom_css);
}
function insert_custom_css() {
if (is_page() || is_single()) {
if (have_posts()) : while (have_posts()) : the_post();
echo '<style type="text/css">'.get_post_meta(get_the_ID(), '_custom_css', true).'</style>';
endwhile; endif;
rewind_posts();
}
}
//Custom JS Widget
add_action('admin_menu', 'custom_js_hooks');
add_action('save_post', 'save_custom_js');
add_action('wp_head','insert_custom_js');
function custom_js_hooks() {
add_meta_box('custom_js', 'Custom JS', 'custom_js_input', 'post', 'normal', 'high');
add_meta_box('custom_js', 'Custom JS', 'custom_js_input', 'page', 'normal', 'high');
}
function custom_js_input() {
global $post;
echo '<input type="hidden" name="custom_js_noncename" id="custom_js_noncename" value="'.wp_create_nonce('custom-js').'" />';
echo '<textarea name="custom_js" id="custom_js" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_custom_js',true).'</textarea>';
}
function save_custom_js($post_id) {
if (!wp_verify_nonce($_POST['custom_js_noncename'], 'custom-js')) return $post_id;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
$custom_js = $_POST['custom_js'];
update_post_meta($post_id, '_custom_js', $custom_js);
}
function insert_custom_js() {
if (is_page() || is_single()) {
if (have_posts()) : while (have_posts()) : the_post();
echo '<script type="text/javascript">'.get_post_meta(get_the_ID(), '_custom_js', true).'</script>';
endwhile; endif;
rewind_posts();
}
}
//検索ワードのハイライト
function highlight_results($text){
if(is_search()){
$keys = implode('|', explode(' ', get_search_query()));
$text = preg_replace('/(' . $keys .')/iu', '<span class="search-highlight">\0</span>', $text);
}
return $text;
}
add_filter('the_content', 'highlight_results');
add_filter('the_excerpt', 'highlight_results');
add_filter('the_title', 'highlight_results');
<file_sep>/wp-content/themes/simplicity2-child/entry-card-content.php
<?php //エントリーカードのコンテンツ部分のテンプレート
//通常のエントリーカードクラス
$entry_class = 'entry-card-content';
//通常のエントリーカードの場合意外
if ( is_list_style_large_cards() ||
//最初だけ大きなエントリーカードの最初のエントリーだけ
( is_list_style_large_card_just_for_first() && is_list_index_first() )
)
$entry_class = 'entry-card-large-content';
?>
<div class="<?php echo $entry_class; ?>">
<?php if (is_mobile()) :?>
<?php if ( is_create_date_visible() ): //投稿日を表示する場合?>
<span class="post-date-mob"><span class="post-date"><span class="fa fa-clock-o fa-fw"></span><span class="published"><?php the_time( get_theme_text_date_format() ) ;?></span></span></span>
<?php endif; //is_create_date_visible?>
<h2><a href="<?php the_permalink(); ?>" class="entry-title entry-title-link" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
<p class="post-meta">
<?php if ( is_category_visible() && //カテゴリを表示する場合
get_the_category() ): //投稿ページの場合?>
<span class="category"><span class="fa fa-folder fa-fw"></span><?php the_category(', ') ?></span>
<?php endif; //is_category_visible?>
<?php //コメント数を表示するか
if ( is_comments_visible() && is_list_comment_count_visible() ):
$comment_count_anchor = ( get_comments_number() > 0 ) ? '#comments' : '#reply-title'; ?>
<span class="comments">
<span class="fa fa-comment"></span>
<span class="comment-count">
<a href="<?php echo get_the_permalink() . $comment_count_anchor; ?>" class="comment-count-link"><?php echo get_comments_number(); ?></a>
</span>
</span>
<?php endif ?>
</p><!-- /.post-meta -->
<?php else: ?>
<p class="post-meta">
<?php if ( is_create_date_visible() ): //投稿日を表示する場合?>
<span class="post-date"><span class="fa fa-clock-o fa-fw"></span><span class="published"><?php the_time( get_theme_text_date_format() ) ;?></span></span>
<?php endif; //is_create_date_visible?>
<?php if ( is_category_visible() && //カテゴリを表示する場合
get_the_category() ): //投稿ページの場合?>
<span class="category"><span class="fa fa-folder fa-fw"></span><?php the_category(', ') ?></span>
<?php endif; //is_category_visible?>
<h2><a href="<?php the_permalink(); ?>" class="entry-title entry-title-link" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
<?php //コメント数を表示するか
if ( is_comments_visible() && is_list_comment_count_visible() ):
$comment_count_anchor = ( get_comments_number() > 0 ) ? '#comments' : '#reply-title'; ?>
<span class="comments">
<span class="fa fa-comment"></span>
<span class="comment-count">
<a href="<?php echo get_the_permalink() . $comment_count_anchor; ?>" class="comment-count-link"><?php echo get_comments_number(); ?></a>
</span>
</span>
<?php endif ?>
</p><!-- /.post-meta -->
<?php endif; ?>
<?php get_template_part('admin-pv');//管理者のみにPV表示?>
</header>
<p class="entry-snippet"><?php echo get_the_custom_excerpt( get_the_content(''), get_excerpt_length() ); //カスタマイズで指定した文字の長さだけ本文抜粋?></p>
<?php if ( get_theme_text_read_entry() ): //「記事を読む」のようなテキストが設定されている時 ?>
<footer>
<p class="entry-read"><a href="<?php the_permalink(); ?>" class="entry-read-link"><?php echo get_theme_text_read_entry(); //記事を読む ?></a></p>
</footer>
<?php endif; ?>
</div><!-- /.entry-card-content -->
<file_sep>/git_ssh.sh
#!/bin/sh
exec ssh -o IdentityFile=~/.ssh/id_rsa "$@"
<file_sep>/wp-content/themes/cocoon-child-master/tmp-user/head-insert.php
<?php
//ヘッダー部分(<head></head>内)にタグを挿入したいときは、このテンプレートに挿入(ヘッダーに挿入する解析タグなど)
//子テーマのカスタマイズ部分を最小限に抑えたい場合に有効なテンプレートとなります。
//例:<script type="text/javascript">解析コード</script>
?>
<?php if (!is_user_administrator()) :
//管理者以外カウントしたくない場合は
//↓ここに挿入?>
<?php endif; ?>
<?php //ログインユーザーも含めてカウントする場合は以下に挿入 ?>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-4913808048231598",
enable_page_level_ads: true
});
</script>
| 48a6ba47558059f094d79ef45a7eaf0bdc838608 | [
"JavaScript",
"PHP",
"Shell"
]
| 5 | JavaScript | mah-sh-ee/tint | fe55663918b600c097655ebbc1a93495c4f4d87c | 3e8fd2e97779b1348b3bbc94b8cbd8a09ac3b59e |
refs/heads/master | <file_sep>################################################################################
#' @title Convert a phyloseq object to a MicrobiomeSet object
#' @param physeq \code{\link{phyloseq-class}} object
#' @return \code{\link{MicrobiomeSet-class}} object
#' @export
#' @author <NAME>
as_MicrobiomeSet = function(physeq){
if(!requireNamespace("Metabase"))
stop("[ phylox: PackageNotFound ] The Metabase package is not found")
if(!isClass(physeq, Class = "phyloseq"))
stop("[ phylox ] Input object must be phyloseq class")
otu_table = as(physeq@otu_table, "matrix")
otu_table = Metabase::conc_table(otu_table)
sample_data = physeq@sam_data
if(is.null(sample_data)) {
warning("[ phylox ] phyloseq object does not have a sample data")
} else {
sample_data = as(sample_data, "data.frame")
sample_data = Metabase::sample_table(sample_data)
}
tax_table = physeq@tax_table
if(!is.null(tax_table)){
tax_table = as.data.frame(as(tax_table, "matrix"),
stringsAsFactors = FALSE)
tax_table = Metabase::feature_data(tax_table)
}
Metabase::MicrobiomeSet(
conc_table = otu_table,
sample_table = sample_data,
feature_data = tax_table
)
}
################################################################################
#' @title Convert a SummarizedPhyloseq object to a list of MicrobiomeSet
#' @param spy a \code{\link{SummarizedPhyloseq-class}} object
#' @export
#' @seealso \code{\link{phyloseq_to_mSet}} \code{\link{SummarizedPhyloseq-class}}
#' @author <NAME>
as_MicrobiomeSetList = function(spy){
if(!requireNamespace("Metabase"))
stop("[ phylox ] [ Package Not Found ] The Metabase package is not found")
if(!isClass(spy, Class = "SummarizedPhyloseq"))
stop("[ phylox ] Input object must be SummarizedPhyloseq class")
mSet_li = lapply(levels(spy), function(lvl){
ps = phyloseq(spy[[lvl]], spy@sam_data)
if(lvl == "otu_table")
ps@tax_table = spy@tax_table
as_MicrobiomeSet(ps)
})
names(mSet_li) = gsub("_table", "", levels(spy))
return(mSet_li)
}
<file_sep>################################################################################
########## Getter ##########
################################################################################
#' @rdname SummarizedPhyloseq-accessors
#' @export
setMethod(
f = "kingdom_table",
signature = "SummarizedPhyloStats",
definition = function(object){
return(object@kingdom_table)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-accessors
#' @export
setMethod(
f = "phylum_table",
signature = "SummarizedPhyloStats",
definition = function(object){
return(object@phylum_table)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-accessors
#' @export
setMethod(
f = "class_table",
signature = "SummarizedPhyloStats",
definition = function(object){
return(object@class_table)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-accessors
#' @export
setMethod(
f = "order_table",
signature = "SummarizedPhyloStats",
definition = function(object){
return(object@order_table)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-accessors
#' @export
setMethod(
f = "family_table",
signature = "SummarizedPhyloStats",
definition = function(object){
return(object@family_table)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-accessors
#' @export
setMethod(
f = "genus_table",
signature = "SummarizedPhyloStats",
definition = function(object){
return(object@genus_table)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-accessors
#' @export
setMethod(
f = "species_table",
signature = "SummarizedPhyloStats",
definition = function(object){
return(object@species_table)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-accessors
#' @export
setMethod(
f = "otu_table",
signature = "SummarizedPhyloStats",
definition = function(object){
return(object@otu_table)
}
)
################################################################################
########## Setter ##########
################################################################################
#' @rdname SummarizedPhyloseq-assign
#' @aliases kingdom_table<-
#' @export
setReplaceMethod(
f = "kingdom_table",
signature = "SummarizedPhyloStats",
definition = function(object, value){
object@kingdom_table <- value
validObject(object)
return(object)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-assign
#' @aliases phylum_table<-
#' @export
setReplaceMethod(
f = "phylum_table",
signature = "SummarizedPhyloStats",
definition = function(object, value){
object@phylum_table <- value
validObject(object)
return(object)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-assign
#' @aliases calss_table<-
#' @export
setReplaceMethod(
f = "class_table",
signature = "SummarizedPhyloStats",
definition = function(object, value){
object@class_table <- value
validObject(object)
return(object)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-assign
#' @aliases order_table<-
#' @export
setReplaceMethod(
f = "order_table",
signature = "SummarizedPhyloStats",
definition = function(object, value){
object@order_table <- value
validObject(object)
return(object)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-assign
#' @aliases family_table<-
#' @export
setReplaceMethod(
f = "family_table",
signature = "SummarizedPhyloStats",
definition = function(object, value){
object@family_table <- value
validObject(object)
return(object)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-assign
#' @aliases genus_table<-
#' @export
setReplaceMethod(
f = "genus_table",
signature = "SummarizedPhyloStats",
definition = function(object, value){
object@genus_table <- value
validObject(object)
return(object)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-assign
#' @aliases species_table<-
#' @export
setReplaceMethod(
f = "species_table",
signature = "SummarizedPhyloStats",
definition = function(object, value){
object@species_table <- value
validObject(object)
return(object)
}
)
################################################################################
#' @rdname SummarizedPhyloseq-assign
#' @export
setReplaceMethod(
f = "otu_table",
signature = "SummarizedPhyloStats",
definition = function(x, value){
x@otu_table <- value
validObject(x)
return(x)
}
)
################################################################################
########## Extract ##########
################################################################################
#' @rdname Extract
#' @aliases [[
#' @export
setMethod(
f = "[[",
signature = "SummarizedPhyloStats",
definition = function(x, i, j, drop){
if(!is.character(i) | ! i %in% slotNames(x))
stop("[ phylox ] Slot not found", call. = FALSE)
slot(x, i)
}
)
#' @rdname Extract
#' @aliases [[<-
#' @export
setReplaceMethod(
"[[", "SummarizedPhyloStats",
function(x, i, j, ..., value){
if(!is.character(i) | ! i %in% slotNames(x))
stop("[ phylox ] Slot not found", call. = FALSE)
slot(x, i) = value
validObject(x)
return(x)
}
)
#' @rdname Extract
#' @aliases $
#' @export
setMethod(
"$", "SummarizedPhyloStats",
function(x, name){
if(! name %in% slotNames(x))
stop("[ phylox ] Slot not found", call. = FALSE)
slot(x, name)
}
)
#' @rdname Extract
#' @aliases $<-
#' @export
setReplaceMethod(
"$", "SummarizedPhyloStats",
function(x, name, value){
if(! name %in% slotNames(name))
stop("[ phylox ] Slot not found", call. = FALSE)
slot(x, name) = value
validObject(x)
return(x)
}
)
<file_sep><!-- README.md is generated from README.Rmd. Please edit that file -->
About phylox
============
Microbiome data generated by high through-put sequecing methods come with hierachical phylogenic taxonomy informtation. Researches often need to group OTUs/features base on their phylogenic information on different levels in order to find any potential point of interests. Phylox is a R package allows user to look at the phylogenic sequencing data in different phylogenic levels.
This package can be installed from github.
``` r
devtools::install_github("zhuchcn/phylox")
```
Documentations:
---------------
- [basic usage](https://zhuchcn.github.io/softwares/packages/phylox/basic_usage.html)
<file_sep>################################################################################
#' @keywords internal
'%+%' = function(a, b) paste0(a, b)
################################################################################
#' @keywords internal
complete_phylo_levels = function(){
return(c("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species", "OTU"))
}
<file_sep># # load data, data from Giloteaux et al (2016)
# library(stringr);library(Biostrings);library(tibble);library(phyloseq);library(ape);library(devtools)
# otu_table = read.delim(file = "data-raw/feature_table.tsv", skip = 1,
# comment.char = "", stringsAsFactors = F)
# rownames(otu_table) = str_c("OTU", str_pad(rownames(otu_table), width=3, pad="0"))
# refseq = DNAStringSet(otu_table$X.OTU.ID)
# names(refseq) = rownames(otu_table)
# otu_table = otu_table[,-1]
#
# tax_table = read.delim(file = "data-raw/taxonomy.tsv", stringsAsFactors = F)
# tax_table = column_to_rownames(tax_table, "Feature.ID")
# tax_table = tax_table[as.character(refseq),]
# tax_table = str_split(tax_table, ";", n=7, simplify = T)
# tax_table[grepl("^[kpcofgs]{1}__$",tax_table)] = NA
# tax_table[tax_table == ""] = NA
# tax_table = as.data.frame(tax_table)
# rownames(tax_table) = rownames(otu_table)
# colnames(tax_table) = c("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species")
# # writeXStringSet(refseq, "data-raw/refseq.fasta", format = "fasta", width = 1000)
# sam_data = read.delim("data-raw/sample-metadata.tsv", comment.char = "", stringsAsFactors = F) %>% column_to_rownames("X.SampleID")
# sam_data = sam_data[colnames(otu_table),]
# sam_data$age_range = cut(sam_data$Age, breaks = c(19, 40, 55, 71), include.lowest = T)
#
# phy_tree = read.tree("data-raw/tree.nwk")
#
# otu_table = otu_table(otu_table, taxa_are_rows = T)
# tax_table = tax_table(as.matrix(tax_table))
#
# sam_data = sample_data(sam_data)
#
# fatigue = phyloseq(otu_table, tax_table, sam_data, refseq, phy_tree)
# fatigue = fix_duplicate_tax(fatigue)
#
# use_data(fatigue, overwrite = TRUE)
################################################################################
#' @title (Data) Chronic Fatigue Syndrome dataset
#' @description
#' This dataset contains 87 individuals with 48 diseased patients with the
#' chronic fatigue syndrome, and 39 healthy controls. The data were sequenced on
#' an Illumina MiSeq using the Earth Microbiome Project hypervariable region 4
#' (V4) 16S rRNA sequencing protocol. The data processing procedure can be found
#' on the qiime2 documentation website.
#' @references <NAME>., <NAME>., <NAME>., <NAME>.,
#' <NAME>., & <NAME>. (2016).
#' Reduced diversity and altered composition of the gut microbiome in
#' individuals with myalgic encephalomyelitis/chronic fatigue syndrome.
#' Microbiome, 4(1), 30.
#' @name data-fatigue
#' @aliases fatigue
#' @docType data
#' @author <NAME>.
#' @keywords data
NA
<file_sep>## microbiomeViz annotation
#' @title Construct annotation table for microbiomeViz cladogram annotation
#' @description
#' It creats a annotation table base on a SummarizedPhyloStats object with
#' node name and the color to highlight. This table can then be parsed to
#' the \code{\link{clade.anno}} function from the microbiomeViz package. It
#' goes through each slot in thee SummarizedPhyloStats object, and selects the
#' taxa that matches the provided criteria. For example, the default setting
#' selects all the taxa with a unadjusted pvalue small or equal to 0.05, and
#' label the ones with a positive logFC as red, and negative as blue.
#' @param spys (required) A \code{\link{SummarizedPhyloseq-class}} object.
#' @param coef Must be pvalue or padj
#' @param cutoff The coef cutoff for selection. Default is 0.05
#' @param colors It takes a string vector of 2 colors. The first will be
#' positive logFC and the second will be negativ.
#' @param levels The phylogenic levels to annotate, with 1 being kingdom and
#' 7 being species. Default is all levels.
#' @seealso
#' \code{\link{SummarizedPhyloStats}}
#' \code{\link{clade.anno}}
#'
#' @export
create_annodata = function(spys, coef = c("pvalue", "padj"), cutoff = 0.05, colors = c("#00468BFF", "#ED0000FF"), levels = 1:7){
levels = slotNames(spys)[levels]
coef = match.arg(coef)
anno.data = data.frame()
splat_list = splat_phyloseq_objects(spys)
has_prefix = grepl("^[kpcofgs]{1}__",rownames(splat_list[[1]])[1])
for(slot in names(splat_list)){
if(!slot %in% levels) next
if(is.na(splat_list[slot])) next
slot_sub = splat_list[[slot]]%>%
rownames_to_column("node") %>%
filter(!is.na(!!sym(coef)) & !!sym(coef) <= cutoff) %>%
filter(!is.na(node) & node != "NA")
if(!has_prefix){
slot_sub = mutate(
slot_sub,
node = paste0(str_split(slot, "",simplify = T)[1],"__", node))
}
anno.data = rbind(
anno.data,
data.frame(
node = slot_sub$node,
color = ifelse(slot_sub$logFC > 0, colors[1], colors[2]),
stringsAsFactors = FALSE
)
)
}
return(anno.data)
}
<file_sep>################################################################################
########## Slot Assessor ##########
################################################################################
setGeneric("kingdom_table", function(object) standardGeneric("kingdom_table"))
#' @name kingdom_table
#' @rdname SummarizedPhyloseq-accessors
#' @title Accessors for SummarizedPhyloseq class and SummarizedPhyloStats class
#'
#' @description Accessor methods for the \code{\link{SummarizedPhyloseq-class}}
#' and the \code{\link{SummarizedPhyloStats-class}}
#'
#' @details These methods retrieve slots from either a SummarizedPhyloseq or a SummarizedPhyloStats object.
#' \describe{
#' \item{kingdom_table()}{Retrieve the kingdom_table slot}
#' \item{phylum_table()}{Retrieve the phylum_table slot}
#' \item{class_table()}{Retrieve the class_table slot}
#' \item{order_table()}{Retrieve the order_table slot}
#' \item{family_table()}{Retrieve the family_table slot}
#' \item{genus_table()}{Retrieve the genus_table slot}
#' \item{species_table()}{Retrieve the species_table slot}
#' \item{otu_table()}{Retrieve the otu_table slot}
#' }
#'
#' @param object Either a SummarizedPhyloseq or SummarziedPhyloStats object.
#' @return A otu_table-class object.
#' @author <NAME>
#'
#' @seealso
#' \code{\link{SummarizedPhyloseq-class}}
#' \code{\link{SummarizedPhyloStats-class}}
#' \code{\link{summarizeFromPhyloseq}}
#'
#' @export
setMethod(
f = "kingdom_table",
signature = "SummarizedPhyloseq",
definition = function(object){
return(object@kingdom_table)
}
)
################################################################################
setGeneric("phylum_table", function(object) standardGeneric("phylum_table"))
#' @rdname SummarizedPhyloseq-accessors
#' @aliases phylum_table
#' @export
setMethod(
f = "phylum_table",
signature = "SummarizedPhyloseq",
definition = function(object){
return(object@phylum_table)
}
)
################################################################################
setGeneric("class_table", function(object) standardGeneric("class_table"))
#' @rdname SummarizedPhyloseq-accessors
#' @aliases class_table
#' @export
setMethod(
f = "class_table",
signature = "SummarizedPhyloseq",
definition = function(object){
return(object@class_table)
}
)
################################################################################
setGeneric("order_table", function(object) standardGeneric("order_table"))
#' @rdname SummarizedPhyloseq-accessors
#' @aliases order_table
#' @export
setMethod(
f = "order_table",
signature = "SummarizedPhyloseq",
definition = function(object){
return(object@order_table)
}
)
################################################################################
setGeneric("family_table", function(object) standardGeneric("family_table"))
#' @rdname SummarizedPhyloseq-accessors
#' @aliases family_table
#' @export
setMethod(
f = "family_table",
signature = "SummarizedPhyloseq",
definition = function(object){
return(object@family_table)
}
)
################################################################################
setGeneric("genus_table", function(object) standardGeneric("genus_table"))
#' @rdname SummarizedPhyloseq-accessors
#' @aliases genus_table
#' @export
setMethod(
f = "genus_table",
signature = "SummarizedPhyloseq",
definition = function(object){
return(object@genus_table)
}
)
################################################################################
setGeneric("species_table", function(object) standardGeneric("species_table"))
#' @rdname SummarizedPhyloseq-accessors
#' @aliases species_table
#' @export
setMethod(
f = "species_table",
signature = "SummarizedPhyloseq",
definition = function(object){
return(object@species_table)
}
)
################################################################################
########## Slot Assignment ##########
################################################################################
setGeneric("kingdom_table<-", function(object, value) standardGeneric("kingdom_table<-"))
#' @rdname SummarizedPhyloseq-assign
#' @name kingdom_table<-
#' @title Assignment methods for SummarizedPhyloseq and SummarizedPhyloStats
#'
#' @description Assignment methods for the \code{\link{SummarizedPhyloseq-class}}
#' class and the \code{\link{SummarizedPhyloStats-class}} class
#'
#' @details These methods assign an new \code{\link{otu_table-class}} object to either a SummarizedPhyloseq or a SummarizedPhyloStats object.
#'
#' @param object (Required) \code{\link{SummarizedPhyloseq-class}} or \code{\link{SummarizedPhyloStats-class}}
#' @param value (Required) \code{\link{otu_table-class}}
#'
#' @seealso
#' \code{\link{SummarizedPhyloseq-class}}
#' \code{\link{SummarizedPhyloStats-class}}
#' \code{\link{summarizeFromPhyloseq}}
#'
#' @export
setReplaceMethod(
f = "kingdom_table",
signature = "SummarizedPhyloseq",
definition = function(object, value){
object@kingdom_table <- value
validObject(object)
return(object)
}
)
################################################################################
setGeneric("phylum_table<-", function(object, value) standardGeneric("phylum_table<-"))
#' @rdname SummarizedPhyloseq-assign
#' @aliases phylum_table<-
#' @export
setReplaceMethod(
f = "phylum_table",
signature = "SummarizedPhyloseq",
definition = function(object, value){
object@phylum_table <- value
validObject(object)
return(object)
}
)
################################################################################
setGeneric("class_table<-", function(object, value) standardGeneric("class_table<-"))
#' @rdname SummarizedPhyloseq-assign
#' @aliases class_table<-
#' @export
setReplaceMethod(
f = "class_table",
signature = "SummarizedPhyloseq",
definition = function(object, value){
object@class_table <- value
validObject(object)
return(object)
}
)
################################################################################
setGeneric("order_table<-", function(object, value) standardGeneric("order_table<-"))
#' @rdname SummarizedPhyloseq-assign
#' @aliases order_table<-
#' @export
setReplaceMethod(
f = "order_table",
signature = "SummarizedPhyloseq",
definition = function(object, value){
object@order_table <- value
validObject(object)
return(object)
}
)
################################################################################
setGeneric("family_table<-", function(object, value) standardGeneric("family_table<-"))
#' @rdname SummarizedPhyloseq-assign
#' @aliases family_table<-
#' @export
setReplaceMethod(
f = "family_table",
signature = "SummarizedPhyloseq",
definition = function(object, value){
object@family_table <- value
validObject(object)
return(object)
}
)
################################################################################
setGeneric("genus_table<-", function(object, value) standardGeneric("genus_table<-"))
#' @rdname SummarizedPhyloseq-assign
#' @aliases genus_table<-
#' @export
setReplaceMethod(
f = "genus_table",
signature = "SummarizedPhyloseq",
definition = function(object, value){
object@genus_table <- value
validObject(object)
return(object)
}
)
################################################################################
setGeneric("species_table<-", function(object, value) standardGeneric("species_table<-"))
#' @rdname SummarizedPhyloseq-assign
#' @aliases species_table<-
#' @export
setReplaceMethod(
f = "species_table",
signature = "SummarizedPhyloseq",
definition = function(object, value){
object@species_table <- value
validObject(object)
return(object)
}
)
################################################################################
setReplaceMethod(
"otu_table",
signature = "SummarizedPhyloseq",
definition = function(x, value){
x@otu_table <- value
validObject(x)
return(x)
}
)
################################################################################
setGeneric("sample_data<-", function(x, value) standardGeneric("sample_data<-"))
setReplaceMethod(
"sample_data",
signature = "SummarizedPhyloseq",
definition = function(x, value){
x@sam_data <- value
validObject(x)
return(x)
}
)
################################################################################
setReplaceMethod(
"tax_table",
signature = "SummarizedPhyloseq",
definition = function(x, value){
x@tax_table <- value
validObject(x)
return(x)
}
)
################################################################################
########## Extract ##########
################################################################################
#' @rdname Extract
#' @aliases [[
#' @title Extract or replace a slot of an SummarizedPhyloseq or SummarizedPhyloStats object
#' @description Extract or replace the content of a slot of an
#' \code{\link{SummarizedPhyloseq-class}} or an \code{\link{SummarizedPhyloStats-class}} object.
#' @param x An \code{\link{SummarizedPhyloseq-class}} or \code{\link{SummarizedPhyloStats-class}} object.
#' @param name The name of the slot.
#' @export
setMethod(
f = "[[",
signature = "SummarizedPhyloseq",
definition = function(x, i, j, drop){
if(!is.character(i) | ! i %in% slotNames(x))
stop("[ phylox ] Slot not found", call. = FALSE)
slot(x, i)
}
)
#' rdname Extract
#' @aliases [[<-
#' @export
setReplaceMethod(
"[[", "SummarizedPhyloseq",
function(x, i, j, ..., value){
if(!is.character(i) | ! i %in% slotNames(x))
stop("[ phylox ] Slot not found", call. = FALSE)
slot(x, i) = value
validObject(x)
return(x)
}
)
#' @rdname Extract
#' @aliases $
#' @export
setMethod(
"$", "SummarizedPhyloseq",
function(x, name){
if(! name %in% slotNames(x))
stop("[ phylox ] Slot not found", call. = FALSE)
slot(x, name)
}
)
#' @rdname Extract
#' @aliases $<-
#' @export
setReplaceMethod(
"$", "SummarizedPhyloseq",
function(x, name, value){
if(! name %in% slotNames(name))
stop("[ phylox ] Slot not found", call. = FALSE)
slot(x, name) = value
validObject(x)
return(x)
}
)
<file_sep>################################################################################
#' S4 class SummarizedPhyloseq
#'
#' A S4 Object for storing phyloseq data at all phylogenic levels
#'
#' This class inherit from the
#' \code{\link{phyloseq-class}}
#' from the phyloseq package. It contains three data classes:
#' \code{\link{otu_table-class}} ("otu_table" slot),
#' \code{\link{sample_data-class}} ("sample_data" slot), and
#' \code{\link{taxonomyTable-class}} ("tax_table" slot).
#' Besides the three slots inherit from phyloseq-class, the SummarizedPhyloseq
#' also has 7 more slots, "kingdom_table", "phylum_table", "class_table",
#' "order_table", "family_table", "genus_table", and "species_table", all in
#' the class of otu_table-class. This allows you to view the data in different
#' phylogenic levels.
#' \code{\link{summarizeFromPhyloseq}}
#' is the main constructor for this class, directly from a phyloseq object.
#' The phyloseq needs to have the otu_table, tax_table, and sample_data to
#' successfully construct this class.
#'
#' slots:
#' \describe{
#' \item{otu_table}{ a tabular object of the OTU table, class of otu_table-class}
#' \item{sam_data}{ a tabular object of the sample meta-data, class of sample_data.}
#' \item{tax_table}{ a tabular object of the taxonomy table, class of taxonomyTable.}
#' \item{kingdom_table}{ a tabular object of the summarized OTU table into the kingdom level, class of otu_table}
#' \item{phylum_table}{ a tabular object of the summarized OTU table into the phylum level, class of otu_table}
#' \item{class_table}{ a tabular object of the summarized OTU table into the class level, class of otu_table}
#' \item{order_table}{ a tabular object of the summarized OTU table into the order level, class of otu_table}
#' \item{family_table}{ a tabular object of the summarized OTU table into the family level, class of otu_table}
#' \item{genus_table}{ a tabular object of the summarized OTU table into the genus level, class of otu_table}
#' \item{species_table}{ a tabular object of the summarized OTU table into the species level, class of otu_table}
#' }
#'
#' @seealso
#' \code{\link{phyloseq-class}}
#' \code{\link{summarizeFromPhyloseq}}
#' \code{\link{SummarizedPhyloStats-class}}
#' \code{\link{SummarizedPhyloseq-accessors}}
#' \code{\link{SummarizedPhyloseq-assign}}
#'
#' @importClassesFrom phyloseq phyloseq
#' @name SummarizedPhyloseq-class
#' @aliases SummarizedPhyloseq-class
#' @exportClass SummarizedPhyloseq
#' @rdname SummarizedPhyloseq-class
#' @author <NAME>
setClass(
Class = "SummarizedPhyloseq",
representation = representation(
kingdom_table = "otu_tableOrNULL",
phylum_table = "otu_tableOrNULL",
class_table = "otu_tableOrNULL",
order_table = "otu_tableOrNULL",
family_table = "otu_tableOrNULL",
genus_table = "otu_tableOrNULL",
species_table = "otu_tableOrNULL"
),
contains = "phyloseq",
prototype = prototype(
kingdom_table = "NULL",
phylum_table = "NULL",
class_table = "NULL",
order_table = "NULL",
family_table = "NULL",
genus_table = "NULL",
species_table = "NULL"
)
)
################################################################################
#' summarizeFromPhyloseq
#'
#' Construct a
#' \code{\link{SummarizedPhyloseq-class}} object from a
#' \code{\link{phyloseq-class}} object
#'
#' This is the main constructor of the SummarizedPhyloseq class. It takes a
#' phyloseq object and calls the
#' \code{link{summarize_taxa}}() function for each phylogenic level and return
#' a SummarizedPhyloseq object.
#'
#' @usage summarizeFromPhyloseq(physeq, level = "all", keep_full_tax = FALSE)
#'
#' @param physeq An phyloseq object from the phyloseq package. It must contain
#' an otu_table slot, a sam_data slot, and a tax_table slot. The phy_tree slot
#' and refseq slots are not required.
#' @param level The taxonomy level to summarize. It can be one ore more from
#' Kingdom, Phylum, Class, Order, Family, Genus, and Species. If mutiple
#' phylogenic levels are specified, use a string vector. Default is "all" that
#' parses all levels. The slots that are not specified will be NULL.
#'
#' @return A SummarizedPhyloseq object
#'
#' @seealso \code{\link{SummarizedPhyloseq-class}}
#'
#' @author <NAME>
#' @import phyloseq
#' @importFrom magrittr %>%
#' @import dplyr
#' @import tibble
#' @export
#' @examples
#' library(phyloseq)
#' data(GlobalPatterns)
#' spy = summarizedFromPhyloseq(GlobalPatterns)
summarizeFromPhyloseq <- function(physeq, level = "all"){
all_levels = c("Kingdom", "Phylum", "Class", "Order",
"Family", "Genus", "Species")
if( length(level) == 1 & "all" %in% level) level = all_levels
summarizedPhyseq = lapply(level, function(lvl){
otu_table = summarize_taxa(physeq, level = lvl,
keep_full_tax = FALSE) %>%
column_to_rownames("taxonomy")
otu_table(otu_table, taxa_are_rows = TRUE)
})
names(summarizedPhyseq) = level
for(lvl in all_levels){
if(lvl %in% level){
assign(lvl, summarizedPhyseq[[lvl]])
}else{
assign(lvl, NULL)
}
}
new("SummarizedPhyloseq",
kingdom_table = Kingdom,
phylum_table = Phylum,
class_table = Class,
order_table = Order,
family_table = Family,
genus_table = Genus,
species_table = Species,
otu_table = physeq@otu_table,
tax_table = physeq@tax_table,
sam_data = physeq@sam_data,
phy_tree = physeq@phy_tree,
refseq = physeq@refseq)
}
################################################################################
## This validity method checks if the summarized slots have the same sample
## names as the sam_data
setValidity(
"SummarizedPhyloseq",
function(object){
sp_list = splat_phyloseq_objects(object)
otu_tables = c("kingdom_table", "phylum_table", "class_table",
"order_table", "family_table", "genus_table",
"species_table")
object_sample_names = sample_names(object@sam_data)
for(tbl in otu_tables){
table = sp_list[[tbl]]
if(!is.null(table)){
if((length(sample_names(table)) != length(object_sample_names)) |
all.equal(sample_names(table), object_sample_names) != T){
return(paste("in ", tbl, " sample names don't match"))
}
}
}
validObject(as(object, "phyloseq"))
}
)
################################################################################
### This function converts a phyloseq object to an unclassed list, with the
### name of each element being the name of each slot. It actually works for
### other classes not only phyloseq.
#' @keywords internal
splat_phyloseq_objects = function(object){
slot_names = slotNames(object)
slot_list = lapply(slot_names, function(slt){
eval(parse(text = paste0("object@", slt)))
})
names(slot_list) = slot_names
return(slot_list[!is.na(slot_list)])
}
################################################################################
# this funciton converts sample_data to a data.frame
#' @export
setMethod(
f = "as.data.frame",
signature = "sample_data",
definition = function(x){
as(x, "data.frame")
}
)
<file_sep>---
output:
md_document:
variant: markdown_github
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
```{r, echo = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "README-",
message = FALSE, warning = FALSE, error = FALSE,
fig.height = 4, fig.width = 6, fig.align = "center"
)
```
# About phylox
Microbiome data generated by high through-put sequecing methods come with hierachical phylogenic taxonomy informtation. Researches often need to group OTUs/features base on their phylogenic information on different levels in order to find any potential point of interests. Phylox is a R package allows user to look at the phylogenic sequencing data in different phylogenic levels.
This package can be installed from github.
```{r install, eval = FALSE}
devtools::install_github("zhuchcn/phylox")
```
## Documentations:
* [basic usage](https://zhuchcn.github.io/softwares/packages/phylox/basic_usage.html)
<file_sep>################################################################################
setClassUnion("dataframeOrNULL", c("data.frame", "NULL"))
################################################################################
#' @name SummarizedPhyloStats-class
#' @aliases SummarizedPhyloStats-class
#' @author <NAME>
#' @title S4 class SummarizedPhyloStats
#'
#' @description
#' A S4 object to store hypothesis test statistical results of phylogenic
#' sequencing experiment data, at different phylogenic level
#'
#' @details
#' This class has 8 slots and each stores the hypothesis test statistical
#' results of a designated phylogenic level, from otu to kingdom.There are
#' currently two statistical packages supported, limma and DESeq2. There are
#' 2 construction methods \code{\link{spy_to_deseq2}} and
#' \code{\link{spy_to_limma}}. The purpose of this class is to allow users to
#' conduct hypothesis test using DESeq2 or limma at all phylogenic levels and
#' view the results quickly.
#'
#' \describe{
#' This class has 8 slots and each slot is a data.frame with 5 variables as
#' below:
#' \item{baseMean}{The mean value of the baseline group. This corresponds
#' to the AveExpr from the limma result or the baseMean
#' from the DESeq2 result}
#' \item{logFC}{Log transformed fold change from baseline. This corresponds
#' to the logFC from the limma result or the log2FoldChange from the DESeq2
#' result}
#' \item{stat}{The statistic value. This corresponds to the t from the limma
#' result or the stat from the DESeq2 result}
#' \item{pvalue}{The raw p-value. This corresponds to the P.Value from the
#' limma result or the pvalue from the DESeq2 result}
#' \item{padj}{The adjusted p-value. This corresponds to the adj.P.Value
#' from the limma result or the padj from the DESeq2 result}
#' }
#'
#' @slot kingdom_table Summarized statistic result at kingdom level.
#' @slot phylum_table Summarized statistic result at phylum level.
#' @slot class_table Summarized statistic result at class level.
#' @slot order_table Summarized statistic result at order level.
#' @slot family_table Summarized statistic result at family level.
#' @slot genus_table Summarized statistic result at genus level.
#' @slot species_table Summarized statistic result at species level.
#' @slot otu_table Summarized statistic result at otu level.
#'
#' @seealso
#' \code{\link{spy_to_deseq2}}
#' \code{\link{spy_to_limma}}
#' \code{\link{summarizeFromPhyloseq}}
#' \code{\link{SummarizedPhyloseq-accessors}}
#' \code{\link{SummarizedPhyloseq-assign}}
#' \code{\link{phyloseq-class}}
#'
#' @exportClass SummarizedPhyloStats
setClass(
Class = "SummarizedPhyloStats",
representation = representation(
kingdom_table = "dataframeOrNULL",
phylum_table = "dataframeOrNULL",
class_table = "dataframeOrNULL",
order_table = "dataframeOrNULL",
family_table = "dataframeOrNULL",
genus_table = "dataframeOrNULL",
species_table = "dataframeOrNULL",
otu_table = "dataframeOrNULL"
),
prototype = prototype(
kingdom_table = "NULL",
phylum_table = "NULL",
class_table = "NULL",
order_table = "NULL",
family_table = "NULL",
genus_table = "NULL",
species_table = "NULL",
otu_table = "NULL"
)
)
################################################################################
setValidity(
"SummarizedPhyloStats",
function(object){
splat_list = splat_phyloseq_objects(object)
for(slot in names(splat_list)){
if(is.na(splat_list[slot])) next
colNames = colnames(splat_list[[slot]])
shared_column = intersect(colNames,
c("baseMean", "logFC", "stat", "pvalue", "padj"))
if(length(shared_column) < 5){
return("Slot columns must be baseMean, logFC, stat, pvalue, padj")
}
}
}
)
################################################################################
#' @export
#' @inheritParams methods::show
setMethod(
"show", signature = "SummarizedPhyloStats",
definition = function(object){
cat(">>>>>>>>>>>>>>>> SummarizedPhyloStats <<<<<<<<<<<<<<<<<<<\n\n")
splat_list = splat_phyloseq_objects(object)
for(slot in names(splat_list)){
if(!is.na(splat_list[slot])){
cat(paste0(
str_pad(paste0(slot, "()"), width = 18, side = "right"),
" [ ",
str_pad(nrow(splat_list[[slot]]), width = 4, side = "left"),
" taxa, ",
str_pad(sum(splat_list[[slot]]$pvalue < 0.05),
width = 3, side = "left"),
" p<0.05, ",
str_pad(sum(splat_list[[slot]]$padj < 0.05),
width = 2, side = "left"),
" padj<0.05 ]\n"
))
}else{
cat(paste0(
str_pad(paste0(slot, "()"), width = 18, side = "right"),
" [",
paste(rep(" ",16), collapse=""),
"empty",
paste(rep(" ",16), collapse=""), "]\n"
))
}
}
}
)
<file_sep>################################################################################
##' @title summarize_taxa
##'
##' @param physeq a phyloseq object
##' @param level the taxonomy level to summarize. Level must be one from 1 to 7, while 1 is Kingdom and 7 is Species.
##' @param keep_full_tax logistical value whether to use the full tax path. Default is FALSE.
##' @import dplyr
##' @import reshape2
##' @import phyloseq
##' @author <NAME>
##' @description summarize phyloseq object on different taxonomy level.
##'
##' @examples
##' library(phyloseq)
##' data("GlobalPatterns")
##' GP_family = summarize_taxa(GlobalPatterns, level=5)
summarize_taxa = function(physeq, level = "Family", keep_full_tax = TRUE){
all_levels = c("Kingdom", "Phylum", "Class", "Order",
"Family", "Genus", "Species", "Feature")
if(!is.character(level) | !level %in% all_levels){
message(paste(level))
stop("Level must be one of 'Kingdom', 'Phylum', 'Class', 'Order',
'Family', 'Genus', 'Species', 'Feature'")
}
level = which(level == all_levels)
otutab = otu_table(physeq)
taxtab = tax_table(physeq)
if(keep_full_tax){
taxonomy = apply(taxtab[,1:level], 1, function(x)
paste(c("r__Root", x), collapse="|"))
}else{
taxonomy = as.character(taxtab[,level])
}
taxonomy[is.na(taxonomy)] = "NA"
otutab %>%
as.data.frame %>%
mutate(taxonomy = taxonomy) %>%
#filter(!is.na(taxonomy) & !grepl("\\|NA", taxonomy)) %>%
melt(id.var = "taxonomy",
variable.name = "sample_id") %>%
group_by(taxonomy, sample_id) %>%
summarize(value = sum(value)) %>%
dcast(taxonomy~sample_id)
}
################################################################################
##' @title fix_duplicate_tax
##'
##' @param physeq a phyloseq object
##' @import phyloseq
##' @author <NAME>
##' @export
##' @description fix the duplicatae taxonomy names of a phyloseq object
fix_duplicate_tax = function(physeq){
taxtab <- tax_table(physeq)
for(i in 3:ncol(taxtab)){
uniqs = unique(taxtab[,i])
for(j in 1:length(uniqs)){
if(is.na(uniqs[j])) next
ind = which(taxtab[,i]== as.character(uniqs[j]))
if(length(unique(taxtab[ind,i-1]))>1){
taxtab[ind,i] = paste(taxtab[ind,i-1], taxtab[ind,i], sep="_")
}
}
}
tax_table(physeq) = taxtab
return(physeq)
}
################################################################################
#' @export
setMethod(
"levels", "SummarizedPhyloseq",
function(x){
levels = slotNames(x)
levels = levels[sapply(levels, function(lvl) !is.null(slot(x, lvl)))]
levels = levels[levels %in% paste0(tolower(complete_phylo_levels()), "_table")]
return(levels)
}
)
<file_sep>################################################################################
#' @title Stacked bar plot for SummarizedPhyloseq data
#' @description
#' This function uses the ggplot2 package to generate barplot from a given
#' \code{\link{SummarizedPhyloseq-class}} object on a given phylogenic level.
#' The output is a ggplot object so it can be easily styled using additional
#' ggplot functions.
#' @param spy \code{\link{SummarizedPhyloseq-class}}
#' @param level Character. The phyloseq level to use. Must be one of
#' Kingdom, Phylum, Class, Order, Family, Genus, or Species.
#' @param by Character. The sample meta-data variable to plot the
#' abundance data againt to. It must be from the sample data's column names.
#' If multiple variables are givin, facets will be used. The default is
#' sample name. See examples.
#' @param legend.show Logical variable whether to show the legends.
#' @param plotly Logical value. If TRUE, a plotly variable will be returned.
#' @import ggplot2
#' @author <NAME>
#' @export
#' @examples
#' data(fatigue)
#' fatigue = transform_sample_counts(physeq, function(x) x/sum(x))
#' spy = summarizeFromPhyloseq(fatigue)
#' plot_bar(spy)
#' plot_bar(spy, "Phylum", by = "Subject")
#' plot_bar(spy, "Genus", by = c("Subject", "Sex"))
#' plot_bar(spy, "Genus", by = c("Subject", "Sex"), plotly = T)
#' plot_bar(spy, "Phylum", by = c("Subject", "age_range", "Sex"))
plot_bar = function(spy, level="Phylum", by = NULL, show.legend = TRUE){
# check auguments
if(is.null(by)) by = "sample_id"
if(length(by) > 3) stop("Group variable number must be <= 3")
if(!level %in% complete_phylo_levels())
stop(paste0("Invalid level. Must be one from ",
paste(complete_phylo_levels(), collapse = ", ")))
# retrieve data
slot = eval(parse(text = paste0(tolower(level), "_table(spy)"))) %>%
as.data.frame %>%
t %>% as.data.frame %>%
rownames_to_column("sample_id")
sam_data = as(sample_data(spy), "data.frame") %>%
rownames_to_column("sample_id")
# clean data
mdf = merge(slot, sam_data, by = "sample_id") %>%
melt(c(colnames(sam_data)),
variable.name = "OTU", value.name = "Abundance") %>%
group_by_(.dots = c("OTU", by)) %>%
summarize(Abundance = mean(Abundance)) %>%
ungroup() %>%
as.data.frame
colnames(mdf) = c("OTU",
paste0(rep("V", ncol(mdf)-2), 1:(ncol(mdf)-2)),
"Abundance")
# make plot
p = ggplot(mdf) +
geom_bar(aes(x = V1, y = Abundance, fill = OTU),
stat = "identity", position = "stack") +
labs(x = "") +
theme_bw() +
guides(fill = guide_legend(title = level))
if(length(by) == 2){
p = p + facet_grid(.~V2)
}else if(length(by) == 3){
p = p + facet_grid(V2 ~ V3)
}
if(!show.legend){
p = p + theme(legend.position = "none")
}
p
}
################################################################################
#' @title Boxplot for SummarizedPhyloseq data
#' @description
#' This function uses the ggplot2 package to generate a boxplot from a givin
#' \code{\link{SummarizedPhyloseq-class}} object by specifying a taxon name.
#' @param spy \code{\link{SummarizedPhyloseq-class}}
#' @param level character. The phylogenic level.
#' @param taxon character. The taxon name to plot.
#' @param by character. The sample meta-data variable to plot the
#' abundance data againt to. It must be from the sample data's column names.
#' If multiple variables are givin, facets will be used. The default is
#' sample name. See examples.
#' @param line character. A sample meta-data variable. If specified, geom_line
#' will be called to draw lines between 2 points. This is particually usful to
#' deal with repeated measures.
#' @param color.by character. A sample meta-data variable. If specified, points
#' with different levels will be colored diffently. See examples.
#' @param jitter numeric. If specified, points will be jittered. Recommanded
#' value: 0.15. the \code{line} and \code{jitter} can not be specified at the
#' same time.
#' @param point.size numeric. The size of points. Default is 3
#' @param point.alpha numeric. The transparency of points.
#' @param point.color character. If the \code{color.by} is not specified, this
#' value will be given the to the points color.
#' @param whisker.width numeirc. The width of boxplot whisker. Default is 0.5.
#' @param color.pal character. The color panel to use.
#' @param show.legend logical. Whether to show legend. Default is TRUE.
#' @param syle character. The pre-defined style to apply on the plot. "bw" is a
#' empty default style using the \code{\link{theme_bw}}. "academic" is a classic
#' style based on the \code{\link{theme_classic}}.
#' @param plotly logical. If TRUE, a plotly variable will be returned.
#' @author <NAME>
#' @export
#' @examples
#' data(fatigue)
#' fatigue = transform_sample_counts(fatigue, function(x) x/sum(x))
#' spy = summarizeFromPhyloseq(fatigue)
#' plot_box(spy, level = "Genus", taxon = "g__Ruminococcus", by = "Subject", jitter = 0.15)
#' plot_box(spy, level = "Genus", taxon = "g__Ruminococcus", by = c("Subject","Sex"), box.size = 1, whisker.size = 1, show.points = F, style = "academic")
#' plot_box(spy, level = "Genus", taxon = "g__Ruminococcus", by = c("Subject","Sex"), jitter = 0.15, box.size = 1, whisker.size = 1, point.alpha = 0.75, point.color = "steelblue", style = "academic")
plot_boxplot = function(spy, level, taxon, x, rows, cols, line, color, ...){
if(!requireNamespace("ggmetaplots")){
stop("[ phylox: PackageNotFound ] Can't find the ggmetaplot package. Please install it using:\n\n devtools::install_github('zhuchcn/ggmetaplot')",
call. = FALSE)
}
level_list = complete_phylo_levels() %>% tolower()
level = tolower(level)
if(!level %in% level_list)
stop(paste0("[ phylox ]Invalid level. Must be one from ",
paste(level_list, collapse = ", ")))
args = as.list(match.call())[-c(1:3)]
names(args)[names(args) == "taxon"] = "y"
sample_vars = unique(c(args$x, args$rows, args$cols, args$color, args$line))
level_list = paste0(level_list, "_table")
names(level_list) = tolower(complete_phylo_levels())
df = data.frame(
abundance = as.numeric(spy[[level_list[level]]][taxon,])
) %>%
cbind(spy@sam_data[,sample_vars])
colnames(df)[-1] = sample_vars
args$data = df
args$y = "abundance"
do.call(ggmetaplots::ggboxplot, args)
}
################################################################################
#' @title Generate a heatmap with all the taxa the match a given crateria from
#' a given SummarizedPhyloseq Object.
#' @description
#' By specifying the phylogenic level, coeficient, and cutoff, all the taxa with
#' a adjusted or unadjusted p value that is smaller than the cutoff will be
#' selected. Then the summarized OTU table at the specifed level is extracted
#' to generate a heatmap.
#'
#' This function depends on the \code{\link{zheatmap}} package. The package can
#' be installed from the github using \code{devtools::install_github("zhuchcn/zheatmap")}
#' @author <NAME>
#' @param spy SummarizedPhyloseq object
#' @param spys SummarizedPhyloStats object
#' @param level character variable indicates the targeted phylogenic level
#' @param coef character, either "pvalue" or "padj"
#' @param cutoff numeric, the cutoff of coef to use
#' @param anno.var character, indicates the sample metadata variabel to use for
#' annotation as a side bar. It must be one from the colnames of the sample data.
#' @param ... other parameters supported by the \code{\link{zheatmap}} function.
#' @seealso \code{\link{SummarizedPhyloseq-class}}, \code{\link{SummarizedPhyloStats-class}}, \code{\link{zheatmap}}
#' @examples
#' data(fatigue)
#' fatigue = transform_sample_counts(fatigue, function(x) x/sum(x))
#' spy = summarizeFromPhyloseq(fatigue)
#' design = model.matrix(data = as(sample_data(fatigue), "data.frame"), ~Subject + 1)
#' spys_lm = spy_to_limma(spy_prop, design, transform = "log", p.value = 2, coef = 2)
#' plot_heatmap(spy,
#' spys_lm,
#' coef = "pvalue",
#' cutoff = 0.1,
#' anno.var = "Subject")
#' @export
plot_heatmap = function(spy,
spys,
level = "Genus",
coef = "pvalue",
cutoff = 0.05,
anno.var,
...
){
if (!requireNamespace("zheatmap", quietly = TRUE)) {
stop("[ phylox: PackageNotFound ] The \"zheatmap\" package is required for this funciton. Please install it.")
}
if(!level %in% complete_phylo_levels())
stop(paste0("Invalid level. Must be one from ",
paste(complete_phylo_levels(), collapse = ", ")))
otutab = eval(parse(text = paste0(tolower(level), "_table(spy)"))) %>%
as.data.frame
statab = eval(parse(text = paste0(tolower(level), "_table(spys)"))) %>%
as.data.frame
samtab = as(sample_data(spy), "data.frame")
otu.list = statab %>%
rownames_to_column("OTU") %>%
filter_at(vars(coef), any_vars( . <= cutoff)) %>%
filter(OTU != "NA") %>%
select("OTU")
data = as.data.frame(otutab[otu.list$OTU,])
colSideBar = if(!missing(anno.var)) samtab[,anno.var] else NULL
zheatmap::zheatmap(data = data,
colSideBar = colSideBar,
...)
}
<file_sep>################################################################################
#' @inheritParams methods::show
#' @import stringr
#' @export
setMethod(
"show",
signature = "SummarizedPhyloseq",
definition = function(object){
cat(">>>>>>>>>>>>>>>> summarized phyloseq object <<<<<<<<<<<<<<<<\n\n")
show(as(object, "phyloseq"))
levels = c("kingdom_table", "phylum_table", "class_table", "order_table",
"family_table", "genus_table", "species_table")
cat("\nphyloseq extra slots:\n")
for(lvl in levels){
slt = eval(parse(text = paste0("object@", lvl)))
if(!is.null(slt)){
cat(paste(str_pad(paste0(lvl, "()"), width=18, side="right"),
str_pad(paste0(str_to_title(
gsub("\\(\\)","",gsub("\\_"," ", lvl))),":"),
width = 15, side = "right"),
"[ ",
str_pad(ntaxa(slt), width = 3, side="left"),
" taxa and ",
nsamples(slt), " samples ]\n", sep = ""))
}
}
cat("\n>>>>>>>>>>>>>>>> SummarizedPhyloseq-Class <<<<<<<<<<<<<<<<")
}
)
################################################################################
#' @inheritParams methods::show
#' @export
setMethod(
"show",
signature = "otu_table",
definition = function(object){
cat(paste0("OTU Table: [",
ntaxa(object),
" taxa and ",
nsamples(object),
" samples]\n"))
if( taxa_are_rows(object) ){
cat(" taxa are rows", fill=TRUE)
} else {
cat(" taxa are columns", fill=TRUE)
}
nrow2show = min(8, ntaxa(object))
ncol2show = min(8, nsamples(object))
show([email protected][1:nrow2show,1:ncol2show])
nrow_left = ntaxa(object) - nrow2show
ncol_left = nsamples(object) - ncol2show
if( nrow_left > 0 ){
cat(paste0("\n... with ",
str_pad(nrow_left, width=4, side="right"),
" more taxa"))
}
if( ncol2show > 0){
cat(paste0("\n... with ",
str_pad(ncol_left, width=4, side="right"),
" more samples"))
}
}
)
################################################################################
#' @inheritParams methods::show
#' @export
setMethod(
"show",
signature = "sample_data",
definition = function(object){
cat(paste0("Sample Data: [",
dim(sample_data(object))[1],
" samples by ",
dim(sample_data(object))[2],
" sample variables]:\n", sep = ""))
nrow2show = min(10, nrow(object))
ncol2show = min(5, ncol(object))
show(as(object[1:nrow2show, 1:ncol2show], "data.frame"))
nrow_left = nrow(object) - nrow2show
ncol_left = ncol(object) - ncol2show
if( nrow_left > 0 ){
cat(paste0("\n... with ",
str_pad(nrow_left, width=4, side="right"),
" more samples"))
}
if( ncol2show > 0){
col_classes = sapply(object, class)
short_names = c("<chr>", "<int>", "<fct>", "<num>")
names(short_names) = c("character", "integer", "factor", "numeric")
col_classes = short_names[col_classes]
col_left = tail(paste(colnames(object), col_classes), ncol_left)
cat(paste0("\n... with ",
str_pad(ncol_left, width=4, side="right"),
" more variables:\n",
paste(col_left, collapse = ", ")))
}
}
)
################################################################################
#' @inheritParams methods::show
#' @export
setMethod(
"show",
signature = "taxonomyTable",
definition = function(object){
cat(paste0("Taxonomy Table: [", dim(object)[1], " taxa by ",
dim(object)[2],
" taxonomic ranks]:\n"))
nrow2show = min(8, nrow(object))
nrow_left = nrow(object) - nrow2show
show(as(object[1:nrow2show,], "matrix"))
if( nrow_left > 0 ){
cat(paste0("\n... with ",
str_pad(nrow_left, width=4, side="right"),
" more taxa"))
}
}
)
<file_sep>################################################################################
#' phylox
#'
#' This package allows you to store, handle, and analyz high-throughput p
#' hylogenic sequencing data in different phylogenic level. The the core
#' component of this package includes two S4 classes.
#'
#' The SummarizedPhyloseq was built based on the phyloseq class from the
#' phyloseq package. It inherits from the phyloseq class. Not only it contains
#' all the slots in phyloseq, but also it has 7 new slots as the summarized otu
#' table on the level of from species to kingdom. Differential abundance test
#' can then be applied to the SummarizedPhyloseq on each phyloseq level, and
#' the results are stored in the SummarizedPhyloStats class.
#'
#' @import methods
#' @name phylox-package
#' @author <NAME> \email{<EMAIL>}
#' @docType package
#' @keywords package
NA
################################################################################
<file_sep>################################################################################
#' @name spy_to_deseq2
#' @title Conduct DESeq2 analysis on different phylogenic levels
#' @description
#' Conduct differential expression using the DESeq2 package to a
#' SummarizedPhyloseq object. See the \code{\link{DESeq}} for more detail.
#' @note The DESeq2 package needs to be installed in order to successfully run
#' this function.
#' @param spy (required) \code{\link{SummarizedPhyloseq-class}}
#' @param design (required) The design matrix of the experiment, with rows
#' corresponding to sample IDs and columns to coefficients to be estimated.
#' This can be constructed using \code{\link{model.matrix}} function
#' @param resultsName The index or name of the coefficient (variable) for
#' building the results tables. The value provided must be one of the colnames
#' of the design matrix. This argument is corresponding to the \code{name} in
#' the \code{\link{results}} from the DESeq2 package.
#' @param ... (optional) Other parameters to be parsed to the
#' \code{\link{DESeq}} function
#' @author <NAME>
#' @export
spy_to_deseq2 = function(spy, design, resultsName, ...){
if (!requireNamespace("DESeq2", quietly = TRUE)) {
stop("Package \"DESeq2\" needed for this function to work. Please install it.",
call. = FALSE)
}
if(is.character(resultsName)){
resultsName = gsub("\\:","\\.",resultsName)
}
sample_data = sample_data(spy)
splat_list = splat_phyloseq_objects(spy)
splat_list = splat_list[sapply(splat_list, class) == "otu_table" & !is.na(splat_list)]
result_list = lapply(splat_list, function(table){
ps = phyloseq(table, sample_data)
de = phyloseq_to_deseq2(ps, design)
de = DESeq2::DESeq(de, ...)
if(is.numeric(resultsName)){
name = DESeq2::resultsNames(de)[resultsName]
}else{
name = resultsName
}
res = as.data.frame(DESeq2::results(de, name = name))
res = res[,c("baseMean", "log2FoldChange", "stat", "pvalue", "padj")]
names(res) = c("baseMean", "logFC", "stat", "pvalue", "padj")
return(res)
})
do.call(new, c(list(Class="SummarizedPhyloStats"), result_list))
}
################################################################################
#' @name spy_to_limma
#' @title Linear model using limma on different phylogenic levels
#' @description
#' Fit linear models using the limma package to a SummarizedPhyloseq
#' object. See the \code{\link{lmFit}} for more detail.
#' @note the limma package needs to be installed in order to successfully run
#' this function
#' @param spy (required) \code{\link{SummarizedPhyloseq-class}}
#' @param design (required) The design matrix of the experiment, with rows
#' corresponding to sample IDs and columns to coefficients to be estimated.
#' This can be constructed using \code{\link{model.matrix}} function
#' @param transform (required) The method to use to transform the data before fitting
#' linear model. "log" will apply a log transform to the data while "none" won't
#' do anything.
#' @param coef (required) The index number or name of the coefficient (variable) for
#' building the results tables. The value provided must be one of the colnames
#' or indices of the design matrix. This argument is corresponding to the
#' \code{coef} in the \code{\link{topTable}} from the limma package.
#' @param p.value (required) Same as \code{coef}
#' @param ... (optional) Other parameters to be parsed to the
#' \code{\link{topTable}} function
#' @author <NAME>
#' @export
spy_to_limma = function(spy, design, transform = function(x){log2(x+1)}, coef, p.value, ...){
if (!requireNamespace("limma", quietly = TRUE)) {
stop("Package \"limma\" needed for this function to work. Please install it.",
call. = FALSE)
}
sample_data = sample_data(spy)
splat_list = splat_phyloseq_objects(spy)
splat_list = splat_list[sapply(splat_list, class) == "otu_table" & !is.na(splat_list)]
result_list = lapply(splat_list, function(table){
otu = as.data.frame(transform(table))
fit = limma::lmFit(otu, design)
fit_ebayes = limma::eBayes(fit)
res = limma::topTable(fit_ebayes, sort.by = "none", number = nrow(otu),
coef = coef, p.value = p.value,...)
res = res[,c("AveExpr", "logFC", "t", "P.Value", "adj.P.Val")]
names(res) = c("baseMean", "logFC", "stat", "pvalue", "padj")
return(res)
})
do.call(new, c(list(Class="SummarizedPhyloStats"), result_list))
}
| daaebb0cac1535c42cf2d3a04f5467f41a4254bf | [
"Markdown",
"R",
"RMarkdown"
]
| 15 | R | zhuchcn/phylox | bc0393908f027b21a4c745d960b7cfd28ef55dcf | 7738fb9ce6b76a2c34e5721e0f542b3bb02ed53d |
refs/heads/master | <repo_name>someErrorW/dict--<file_sep>/insert_word.py
"""
将单词表插入数据库中
"""
import pymysql
import re
f = open('dict.txt') # 默认读权限
# 链接数据库
db = pymysql.connect(host='localhost',
user='root',
passwd='<PASSWORD>',
database='ele_dict',
charset='utf8')
cur = db.cursor() # 创建游标对象
sql = 'insert into words (word,mean) values(%s,%s);'
for line in f:
# 正则匹配
tup = re.findall(r'(\w+)\s+(.*)', line)[0]
try:
cur.execute(sql, tup)
db.commit()
except Exception:
db.rollback()
# 关闭文件
f.close()
cur.close()
db.close()
| 03ee2895e068bcf6562017e038647a4904e25050 | [
"Python"
]
| 1 | Python | someErrorW/dict-- | 65d8bf9b0632d64bf300d704b5eada6961181990 | ff7e35770f66a38bfd154e4a22e0dbe4d1180775 |
refs/heads/master | <repo_name>wanfeng42/chat<file_sep>/source/protocol_process.c
#include "serv.h"
int get_session(struct bufferevent *bev, char *session)
{
int nread;
char *fptr, *tptr;
char buf[19];
nread = bufferevent_read(bev, buf, SESSLEN + 2);
buf[nread] = '\0';
fptr = memchr(buf, 0x02, nread);
tptr = memchr(fptr, 0x03, nread);
if (fptr == NULL || tptr == NULL)
{
fprintf(stderr, "read_error,line %d\n", __LINE__);
evbuffer_drain(bufferevent_get_input(bev), 1024);
return -1;
}
fptr++;
strncpy(session, fptr, SESSLEN);
session[SESSLEN] = '\0';
return 1;
}
int get_remain(struct bufferevent *bev, int *nremain)
{
unsigned char buf[7];
int nread;
nread = bufferevent_read(bev, buf, 6);
buf[nread] = '\0';
*nremain = buf[1] | buf[2] << 8 | buf[3] << 16 | buf[4] << 24;
if (*nremain <= 0 || *nremain > MAXBUFLEN || buf[0] != '\2' || buf[5] != '\3' || nread != 6)
{
evbuffer_drain(bufferevent_get_input(bev), 1024);
fprintf(stderr, "read remain error,, nread = %d, nremain = %d, %d %d %d %d\n", nread, *nremain, buf[1], buf[2], buf[3], buf[4]);
return -1;
}
return 1;
}
int get_msg(struct bufferevent *bev, int nremain, char *buf)
{
int nread;
if (nremain > MAXBUFLEN)
{
return -1;
}
alarm(1);
while (nremain > 0 && g_IO_time_out == 0)
{
nread = bufferevent_read(bev, buf, nremain);
buf += nread;
nremain -= nread;
}
alarm(0);
g_IO_time_out = 0;
if (nremain)
{
return -1;
}
return 1;
}
int send_length(struct bufferevent *bev, int length)
{
unsigned char sendbuf[6];
//sprintf(sendbuf, "\002\001\001\001\001\003");
sendbuf[0] = '\002';
sendbuf[1] = length & 0xff;
sendbuf[2] = (length >> 8) & 0xff;
sendbuf[3] = (length >> 16) & 0xff;
sendbuf[4] = (length >> 24) & 0xff;
sendbuf[5] = '\003';
bufferevent_write(bev, sendbuf, 6);
return 1;
}
int send_type(struct bufferevent *bev, int type, int status)
{
char sendbuf[7];
sprintf(sendbuf, "\002%d\003\002%d\003", type, status);
bufferevent_write(bev, sendbuf, 6);
return 1;
}<file_sep>/source/Makefile
CC = gcc
PROGS = serv
CFLAGS = -Wall -g
LIBS = -levent -levent_pthreads -lpthread
all: ${PROGS}
serv:chat_serv.o protocol_process.o threadpool.o serv.h
${CC} ${CFLAGS} -o $@ $^ ${INCLUDE} ${LIBS}
chat_serv.o:serv.h
protocol_process.o:serv.h
test:testcli.o
clean:
rm -f serv test chat_serv.o protocol_process.o testcli.o
<file_sep>/README.md
# README
## 说明
### 服务器使用I/O复用处理多个客户的请求,包括:注册、登录、获取服务器时间、向其他客户端发送消息,向其他客户端发送文件,向所有已登录用户发送消息。其中,文件的发送使用了线程池技术。
## 消息结构(对服务器):
### 消息中每一个单独的部分都由字节0x02、0x03包围
### LEN为4字节长,存储接下来的全部或部分消息长度
### session的长度由SESSLEN宏定义,一般为16字节
## SIGNUP
### SIGNUP接收
#### (0x02)0(0x03)(0x02)LEN(0x03)(0x02)name(0x03)(0x02)passwd(0x03)
### SIGNUP发送
#### 出错 (0x02)0(0x03)(0x02)0(0x03)
#### 成功 (0x02)0(0x03)(0x02)1(0x03)
## LOGIN
### LOGIN接收
#### (0x02)1(0x03)(0x02)LEN(0x03)(0x02)name(0x03)(0x02)passwd(0x03)
### LOGIN发送
#### 出错 (0x02)1(0x03)(0x02)0(0x03)
#### 成功 (0x02)1(0x03)(0x02)1(0x03)(0x02)session(0x03)
## TIME
### TIME接收
#### (0x02)2(0x03)(0x02)session(0x03)
### TIME发送
#### 出错 (0x02)2(0x03)(0x02)0(0x03)
#### 成功 (0x02)2(0x03)(0x02)1(0x03)(0x02)LEN(0x03)(0x02)timestring(0x03)
## MESSAGE one to one
### MESSAGE接收
#### (0x02)3(0x03)(0x02)session(0x03)(0x02)LEN(0x03)(0x02)toname(0x03)(0x02)fromname(0x03)(0x02)LEN(0x03)(0x02)message(0x03)
### MESSAGE发送
#### 出错,向发送方 (0x02)3(0x03)(0x02)0(0x03)
#### 出错,向接收方 不发送
#### 成功,向发送方 (0x02)3(0x03)(0x02)1(0x03)
#### 成功,向接收方 (0x02)3(0x03)(0x02)1(0x03)(0x02)LEN(0x03)(0x02)toname(0x03)(0x02)fromname(0x03)(0x02)LEN(0x03)(0x02)message(0x03) 第一个LEN存储直到下一个LEN之间的字节数
## MESSAGE chat room
### 接收
#### (0x02)4(0x03)(0x02)session(0x03)(0x02)LEN(0x03)(0x02)fromname(0x03)(0x02)message(0x03)
### FILE接收
#### (0x02)5(0x03)(0x02)session(0x03)(0x02)LEN(0x03)(0x02)toname(0x03)(0x02)fromname(0x03)(0x02)LEN(0x03)(0x02)filename(0x03)(0x02)LEN(0x03)file
### FILE发送
#### (0x02)5(0x03)(0x02)LEN(0x03)(0x02)toname(0x03)(0x02)fromname(0x03)(0x02)LEN(0x03)(0x02)filename(0x03)(0x02)LEN(0x03)file<file_sep>/source/serv.h
#ifndef _SERV_H_
#define _SERV_H_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/time.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <signal.h>
#include <syslog.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/thread.h>
#include "threadpool.h"
#define MAXBUFLEN 1024 //最大缓冲区长度
#define MAXSTRLEN 128 //用户名和密码最大长度
#define SESSLEN 16 //最大sess长度
#define MAXUSERNUM 100 //最大用户数量
#define DEBUG
/********
* 用户链表结点,存储用户名,密码
*******/
struct user_list
{
char name[MAXSTRLEN];
char passwd[MAXSTRLEN];
struct user_list *next;
};
/********
* 存储从文件读取的配置信息
*******/
struct config_info
{
int portoto;
int portcr;
int portfr;
struct user_list *head;
};
/********
* 存储已连接的用户信息
*******/
struct login_user
{
char name[MAXSTRLEN];
char session[SESSLEN];
evutil_socket_t fd;
struct bufferevent *bev;
int is_loged_in;
struct login_user *prev;
struct login_user *next;
};
struct threadpool_arg
{
struct bufferevent *bev;
struct login_user *self;
};
extern int g_usernum; //用户个数
extern struct config_info *g_info; //配置文件结构体指针
extern struct login_user *g_login_user; //登录用户链表头
extern int g_IO_time_out;
/*enum
{
SIGNUP = 0,
LOGIN,
TIME,
MESSAGE,
LOGOUT
}*/
void Perror(char *str);
int config_init(const char *path);
evutil_socket_t serv_init(int port, int listen_backlog);
void accept_cb(evutil_socket_t listenfd, short events, void *arg);
void buffer_read_cb(struct bufferevent *bev, void *arg);
void event_cb(struct bufferevent *bev, short events, void *arg);
void session_generate(char *str);
int login_confirm(char *name, char *passwd);
int login(struct bufferevent *bev, struct login_user *self);
int get_session(struct bufferevent *bev, char *session);
int get_remain(struct bufferevent *bev, int *nremain);
int get_msg(struct bufferevent *bev, int remain, char *buf);
int send_length(struct bufferevent *bev, int length);
int send_type(struct bufferevent *bev, int type, int status);
/*void login_error(struct bufferevent *bev, struct login_user *self);*/
#endif<file_sep>/source/chat_serv.c
#include "serv.h"
int g_usernum; //用户个数
struct config_info *g_info = NULL; //配置文件结构体指针
struct login_user *g_login_user = NULL; //登录用户链表头
int g_IO_time_out;
thread_pool *pool; //线程池
inline void
Perror(char *str)
{
#ifdef DEBUG
perror(str);
#endif
}
int config_init(const char *path)
{
g_info = malloc(sizeof(struct config_info));
char buf[MAXBUFLEN];
FILE *configfp;
struct user_list *head = NULL, *ptr;
char *idx = 0; //接受find_sign函数返回的下标
if ((configfp = fopen(path, "r")) == NULL)
{
Perror("init: can't open config file");
exit(-1);
}
while (fgets(buf, MAXBUFLEN, configfp) != NULL)
{
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
int temp;
idx = memchr(buf, '=', strlen(buf));
if (idx == NULL)
continue;
if (strncmp(buf, "portoto", idx - buf) == 0)
{
temp = atoi(idx + 1);
if (temp > 1023 && temp < 65535)
g_info->portoto = temp;
else
g_info->portoto = 49152;
}
else if (strncmp(buf, "portcr", idx - buf) == 0)
{
temp = atoi(idx + 1);
if (temp > 1023 && temp < 65535 && temp != g_info->portoto)
g_info->portcr = temp;
else
g_info->portcr = 49153;
}
else if (strncmp(buf, "portfr", idx - buf) == 0)
{
temp = atoi(idx + 1);
if (temp > 1023 && temp < 65535 && temp != g_info->portoto && temp != g_info->portcr)
g_info->portfr = temp;
else
g_info->portfr = 49154;
}
else if (strncmp(buf, "name", idx - buf) == 0)
{
if (g_usernum > MAXUSERNUM)
break;
ptr = (struct user_list *)malloc(sizeof(struct user_list));
strcpy(ptr->name, idx + 1);
fgets(buf, MAXBUFLEN, configfp);
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
idx = memchr(buf, '=', strlen(buf));
if (idx == NULL)
strcpy(ptr->passwd, "");
else
strcpy(ptr->passwd, idx + 1);
ptr->next = head;
head = ptr;
g_usernum++;
}
}
g_info->head = head;
fclose(configfp);
return 0;
}
evutil_socket_t serv_init(int port, int listen_backlog)
{
evutil_socket_t listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == -1)
{
Perror("socket error");
return -1;
}
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1)
{
Perror("bind error");
return -1;
}
if (listen(listenfd, listen_backlog) == -1)
{
Perror("listen error");
return -1;
}
evutil_make_socket_nonblocking(listenfd);
evutil_make_listen_socket_reuseable(listenfd);
return listenfd;
}
void accept_cb(evutil_socket_t listenfd, short events, void *arg)
{
evutil_socket_t fd;
struct sockaddr_in cliaddr;
socklen_t clilen = sizeof(cliaddr);
struct event_base *base = (struct event_base *)arg;
fd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
if (fd == -1)
{
Perror("accept error");
return;
}
evutil_make_socket_nonblocking(fd);
fprintf(stderr, "socket connected\n");
struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
struct login_user *p = malloc(sizeof(struct login_user));
if (p == NULL)
{
Perror("malloc error");
return;
}
p->fd = fd;
p->bev = bev;
p->is_loged_in = 0;
p->next = g_login_user;
p->prev = NULL;
if (g_login_user != NULL)
g_login_user->prev = p;
g_login_user = p;
bufferevent_setcb(bev, buffer_read_cb, NULL, event_cb, (void *)p);
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
int login_confirm(char *name, char *passwd)
{
struct user_list *head;
head = g_info->head;
while (head != NULL)
{
if ((strncmp(name, head->name, strlen(head->name))) == 0)
{
if ((strncmp(passwd, head->passwd, strlen(head->passwd))) == 0) //匹配
{
return 1;
}
return 0;
}
head = head->next;
}
return 0;
}
void session_generate(char *str)
{
int n, c;
int fd = open("/dev/urandom", O_RDONLY);
n = 0;
while (n < SESSLEN)
{
read(fd, &c, sizeof(int));
str[n] = abs(c % 93) + '!';
n++;
}
close(fd);
}
int login(struct bufferevent *bev, struct login_user *self)
{
char buf[MAXBUFLEN];
int nremain = 0;
char *fptr, *tptr;
char name[MAXSTRLEN];
char passwd[MAXSTRLEN];
//获取消息长度
get_remain(bev, &nremain);
//读取消息
if (get_msg(bev, nremain, buf) == -1)
{
send_type(bev, 1, 0);
fprintf(stderr, "get_msg error, line = %d\n", __LINE__);
evbuffer_drain(bufferevent_get_input(bev), 1024);
return -1;
}
//从消息中找出name
fptr = memchr(buf, 0x02, nremain);
tptr = memchr(fptr, 0x03, nremain);
if (fptr == NULL || tptr == NULL)
{
fprintf(stderr, "read_error,line %d\n", __LINE__);
send_type(bev, 1, 0);
return -1;
}
fptr++;
strncpy(name, fptr, tptr - fptr);
name[tptr - fptr] = '\0';
//从消息中找出passwd
fptr = memchr(tptr, 0x02, nremain);
tptr = memchr(fptr, 0x03, nremain);
if (fptr == NULL || tptr == NULL)
{
fprintf(stderr, "read_error,line %d\n", __LINE__);
send_type(bev, 1, 0);
return -1;
}
fptr++;
strncpy(passwd, fptr, tptr - fptr);
passwd[tptr - fptr] = '\0';
if (login_confirm(name, passwd)) //登录认证成功
{
strncpy(self->name, name, strlen(name)); //存储用户name
self->is_loged_in = 1; //设置已登录标记
session_generate(self->session); //生成并存储session
//向登录用户发送反馈。
send_type(bev, 1, 1);
sprintf(buf, "\002%s\003", self->session);
bufferevent_write(bev, buf, SESSLEN + 2);
fprintf(stderr, "login success , name = %s, session = %s\n", self->name, self->session);
}
else //登录认证失败
{
send_type(bev, 1, 0);
fprintf(stderr, "login error , name = %s, passwd = %s\n", name, passwd);
return -1;
}
return 1;
}
int send_time(struct bufferevent *bev, struct login_user *self)
{
char buf[SESSLEN + 4];
int nremain = 0;
char *fptr, *tptr;
//获取全部消息
nremain = SESSLEN + 2;
if (get_msg(bev, nremain, buf) == -1)
{
send_type(bev, 2, 0);
fprintf(stderr, "get_msg error, line = %d\n", __LINE__);
evbuffer_drain(bufferevent_get_input(bev), 1024);
return -1;
}
//从消息中找出session
fptr = memchr(buf, 0x02, nremain);
tptr = memchr(fptr, 0x03, nremain);
if (fptr == NULL || tptr == NULL)
{
fprintf(stderr, "read_error,line %d\n", __LINE__);
send_type(bev, 2, 0);
return -1;
}
fptr++;
if (strncmp(fptr, self->session, SESSLEN) == 0) //session认证成功
{
time_t ticks;
char sendbuf[38]; //固定长度+24字节时间格式
int len = 38 - 12;
ticks = time(NULL);
send_type(bev, 2, 1);
send_length(bev, len);
sprintf(sendbuf, "\002%.24s\003", ctime(&ticks));
bufferevent_write(bev, sendbuf, len);
fprintf(stderr, "send time success , time = %.24s, len = %d\n", ctime(&ticks), len);
}
else //session认证失败
{
fprintf(stderr, "TIME :wrong session, sess = %.16s, self sess = %.16s", fptr, self->session);
send_type(bev, 2, 0);
}
return 1;
}
int send_msg_to_another_one(struct bufferevent *bev, struct login_user *self)
{
char buf[MAXBUFLEN];
int nread = 0;
int nremain = 0;
char *fptr, *tptr;
//获取session
if (get_session(bev, buf) == -1)
{
send_type(bev, 3, 0);
return -1;
}
if (strncmp(buf, self->session, SESSLEN) == 0) //session认证成功
{
//获取消息长度
if (get_remain(bev, &nremain) == -1)
{
send_type(bev, 3, 0);
return -1;
}
//获取目标用户的name
if (get_msg(bev, nremain, buf) == -1)
{
send_type(bev, 3, 0);
fprintf(stderr, "get_msg error, line = %d\n", __LINE__);
evbuffer_drain(bufferevent_get_input(bev), 1024);
return -1;
}
fptr = memchr(buf, 0x02, nremain);
tptr = memchr(fptr, 0x03, nremain);
if (fptr == NULL || tptr == NULL)
{
fprintf(stderr, "read_error,line %d\n", __LINE__);
evbuffer_drain(bufferevent_get_input(bev), 1024);
send_type(bev, 3, 0);
return -1;
}
fptr++;
fprintf(stderr, "message to %.20s\n", fptr);
//寻找登录用户中是否存在目标用户
struct login_user *p = g_login_user;
while (p)
{
if (strncmp(fptr, p->name, tptr - fptr) == 0 && p->is_loged_in == 1)
{
break;
}
p = p->next;
}
if (p) //找到了,将剩余消息转发。
{
//发送消息头
send_type(p->bev, 3, 1);
send_length(p->bev, nremain);
bufferevent_write(p->bev, buf, nremain);
get_remain(bev, &nremain);
send_length(p->bev, nremain);
while (nremain > 0)
{
nread = bufferevent_read(bev, buf, MAXBUFLEN);
nremain -= nread;
bufferevent_write(p->bev, buf, nread);
}
}
else //没找到
{
fprintf(stderr, "user not found OR not online\n");
evbuffer_drain(bufferevent_get_input(bev), 1024);
send_type(bev, 3, 0);
return -1;
}
}
else //session认证失败
{
fprintf(stderr, "MASSAGE: wrong session, sess = %.16s, self sess = %.16s\n", buf, self->session);
evbuffer_drain(bufferevent_get_input(bev), 1024);
send_type(bev, 3, 0);
return -1;
}
return 1;
}
int send_msg_to_chat_room(struct bufferevent *bev, struct login_user *self)
{
char buf[MAXBUFLEN];
int nread = 0;
int nremain = 0;
//获取session
if (get_session(bev, buf) == -1)
{
send_type(bev, 4, 0);
return -1;
}
if (strncmp(buf, self->session, SESSLEN) == 0) //session认证成功
{
//获取消息长度
if (get_remain(bev, &nremain) == -1)
{
send_type(bev, 4, 0);
return -1;
}
struct login_user *p = g_login_user;
//发送消息头
while (p)
{
send_type(p->bev, 4, 1);
send_length(p->bev, nremain);
p = p->next;
}
//发送剩余部分
while (nremain > 0)
{
nread = bufferevent_read(bev, buf, MAXBUFLEN);
nremain -= nread;
p = g_login_user;
while (p)
{
bufferevent_write(p->bev, buf, nread);
p = p->next;
}
fprintf(stderr, "sent! nread = %d, nremain = %d", nread, nremain);
}
}
return 1;
}
void *file_transfer(void *arg) //传给线程池的任务
{
char buf[MAXBUFLEN];
int nread = 0;
int nremain = 0;
char *fptr, *tptr;
struct threadpool_arg *tparg = (struct threadpool_arg *)arg;
struct bufferevent *bev = tparg->bev;
struct login_user *self = tparg->self;
//获取session
if (get_session(bev, buf) == -1)
{
send_type(bev, 5, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
free(tparg);
return NULL;
}
if (strncmp(buf, self->session, SESSLEN) == 0) //session认证成功
{
//获取消息长度
if (get_remain(bev, &nremain) == -1)
{
send_type(bev, 5, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
free(tparg);
return NULL;
}
//获取目标用户的name
if (get_msg(bev, nremain, buf) == -1)
{
send_type(bev, 5, 0);
fprintf(stderr, "get_msg error, line = %d\n", __LINE__);
evbuffer_drain(bufferevent_get_input(bev), 1024);
bufferevent_enable(bev, EV_READ | EV_WRITE);
free(tparg);
return NULL;
}
fptr = memchr(buf, 0x02, nremain);
tptr = memchr(fptr, 0x03, nremain);
if (fptr == NULL || tptr == NULL)
{
fprintf(stderr, "read_error,line %d\n", __LINE__);
evbuffer_drain(bufferevent_get_input(bev), 1024);
send_type(bev, 5, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
free(tparg);
return NULL;
}
fptr++;
fprintf(stderr, "message to %s\n", fptr);
//寻找登录用户中是否存在目标用户
struct login_user *p = g_login_user;
while (p)
{
if (strncmp(fptr, p->name, tptr - fptr) == 0 && p->is_loged_in == 1)
{
break;
}
p = p->next;
}
if (p) //找到了,将剩余消息转发。
{
//发送消息头
send_type(p->bev, 5, 1);
send_length(p->bev, nremain);
bufferevent_write(p->bev, buf, nremain);
if (get_remain(bev, &nremain) == -1)
{
send_type(bev, 5, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
free(tparg);
return NULL;
}
if (get_msg(bev, nremain, buf) == -1)
{
send_type(bev, 5, 0);
fprintf(stderr, "get_msg error, line = %d\n", __LINE__);
evbuffer_drain(bufferevent_get_input(bev), 1024);
bufferevent_enable(bev, EV_READ | EV_WRITE);
free(tparg);
return NULL;
}
send_length(p->bev, nremain);
bufferevent_write(p->bev, buf, nremain);
get_remain(bev, &nremain);
send_length(p->bev, nremain);
while (nremain > 0)
{
nread = bufferevent_read(bev, buf, MAXBUFLEN);
nremain -= nread;
bufferevent_write(p->bev, buf, nread);
}
bufferevent_enable(bev, EV_READ | EV_WRITE);
free(tparg);
}
else //没找到
{
fprintf(stderr, "user not found OR not online\n");
evbuffer_drain(bufferevent_get_input(bev), 1024);
send_type(bev, 5, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
free(tparg);
return NULL;
}
}
else //session认证失败
{
fprintf(stderr, "MASSAGE: wrong session, sess = %.16s, self sess = %.16s\n", buf, self->session);
evbuffer_drain(bufferevent_get_input(bev), 1024);
send_type(bev, 5, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
free(tparg);
return NULL;
}
return NULL;
}
int sign_up(struct bufferevent *bev, struct login_user *self)
{
//
return 1;
}
void buffer_read_cb(struct bufferevent *bev, void *arg)
{
char buf[10];
int nread = 0;
struct login_user *self = (struct login_user *)arg;
nread = bufferevent_read(bev, buf, 3);
if (nread != 3 || buf[0] != 0x02 || buf[2] != 0x03)
{
fprintf(stderr, "read_error,buf[0]=%x,buf[1]=%x,buf[2]=%x, nread = %d\n", buf[0], buf[1], buf[2], nread);
bufferevent_write(bev, "\002\060\003", 3);
evbuffer_drain(bufferevent_get_input(bev), 1024);
return;
}
if (buf[1] == '0')
{
}
else if (buf[1] == '1') //登录
{
login(bev, self);
}
else if (buf[1] == '2') //获取时间
{
send_time(bev, self);
}
else if (buf[1] == '3') //消息转发
{
send_msg_to_another_one(bev, self);
}
else if (buf[1] == '4') //公共消息转发
{
send_msg_to_chat_room(bev, self);
}
else if (buf[1] == '5') //文件传输
{
bufferevent_disable(bev, EV_READ | EV_WRITE);
struct threadpool_arg *thrarg = malloc(sizeof(struct threadpool_arg));
thrarg->bev = bev;
thrarg->self = self;
add_task(pool, file_transfer, thrarg);
}
}
void event_cb(struct bufferevent *bev, short events, void *arg)
{
if (events & BEV_EVENT_EOF)
{
//do something on socket closed
fprintf(stderr, "socket closed\n");
}
if (events & BEV_EVENT_ERROR)
{
//do something on socket error happened
fprintf(stderr, "socket error\n");
}
struct login_user *self = (struct login_user *)arg;
if (self == g_login_user)
{
g_login_user = g_login_user->next;
free(self);
}
else
{
self->prev->next = self->next;
free(self);
}
bufferevent_free(bev);
}
void IO_sig_alrm(int signo)
{
g_IO_time_out = 1;
}
int run()
{
struct event_base *base = event_base_new();
evutil_socket_t listenfd = serv_init(g_info->portoto, 16);
if (listenfd == -1)
{
return -1;
}
signal(SIGALRM, IO_sig_alrm);
g_IO_time_out = 0;
struct event *ev = event_new(base, listenfd, EV_READ | EV_PERSIST, accept_cb, (void *)base);
event_add(ev, NULL);
event_base_dispatch(base);
event_base_free(base);
return 0;
}
int main()
{
config_init("./config");
evthread_use_pthreads();
/*printf("portoto = %d\nportcr = %d\nportfr = %d\n", g_info->portoto, g_info->portcr, g_info->portfr);
struct user_list *p = g_info->head;
while (p)
{
printf("name = %s\npasswd = %s\n", p->name, p->passwd);
p = p->next;
}*/
pool = malloc(sizeof(thread_pool));
init_pool(pool, 17);
run();
return 0;
}<file_sep>/source/threadpool.h
#ifndef _THREAD_POOL_H_
#define _THREAD_POOL_H_
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <pthread.h>
#define MAX_WAITING_TASKS 1000
#define MAX_ACTIVE_THREADS 20
#define BUFSIZE 100
#define PATHSIZE 100
struct task//任务结点
{
void *(*do_task)(void *arg); //函数指针,指向任务要执行的函数
void *arg; //任务执行函数时作业函数的参数传入
struct task *next;
};
typedef struct thread_pool//线程池头结点
{
pthread_mutex_t lock; //互斥锁,用来保护这个"线程池",就是保护这个链表的
pthread_cond_t cond; //任务有无的条件
bool shutdown; //是否退出。
struct task *task_list;//任务链表,即指向第一个任务结点
pthread_t *tids;//指向线程ID的数组
unsigned max_waiting_tasks;//表示最大的执行的任务数
unsigned waiting_tasks; //目前正在链表上的任务数,即待执行任务
unsigned active_threads; //正在服役的线程数
}thread_pool;
bool init_pool(thread_pool *pool, unsigned int threads_number);
bool add_task(thread_pool *pool, void *(*do_task)(void *arg), void *task);
int add_thread(thread_pool *pool, unsigned int additional_threads_number);
int remove_thread(thread_pool *pool, unsigned int removing_threads_number);
bool destroy_pool(thread_pool *pool);
void *routine(void *arg);//任务执行函数
#endif
| f52357d4d1baf9b7461630c1202143c11b4622b9 | [
"Markdown",
"C",
"Makefile"
]
| 6 | C | wanfeng42/chat | 70af57967c196fd4a9d23639c1d54970d1d7f801 | 32877f0cbabaa64857a786601d28b0c1a5e046c1 |
refs/heads/master | <file_sep># Removing Local GIT Branches with No Remote
If you don't actively clean up old branches in your local git repository, it's very easy for it to get polluted with old branches which have been deleted on the remote repository. Worst case this will make listing your local branches almost useless! I believe `git branch` should show a relevant listing of active work that you have checked out, not a list of every branch you've ever checked out locally. Fortunately, there is an easy way around this, if we're willing to put in a little bit of work into automating it.
## TL;DR: Just Give Me the Script
This is the finished product, safeguards and all. Run this from a bash or shell terminal and follow the prompts, and your local repository should get cleaned up. Read on for a more detailed explanation, or skip to [making it a git command](#Registering-as-git-command).
```bash
#!/usr/bin/env sh
if !(git rev-parse --is-inside-work-tree); then
echo "Not inside a git repository, aborting"
exit 0
fi
git remote prune origin
git branch -r --format "%(refname:lstrip=3)" > remotes
git branch --format "%(refname:lstrip=2)" > locals
cat locals | grep -xv -f remotes > branchesToDelete
# -w checks word counts to ignore blank lines
if [ $(wc -w < branchesToDelete) -gt 0 ];
then
echo "$(wc -l < branchesToDelete) branches without matching remote found, outputting to editor"
echo "Waiting for editor to close"
code branchesToDelete -w
for branch in `cat branchesToDelete`;
do
git branch -D $branch
done
else
echo "There are no branches to cleanup.";
fi
rm branchesToDelete remotes locals
```
## Getting to the Root of It
The process behind identifying dead local branches that we'll use follows a few basic steps:
1. Get lists of remote and local branch names
2. Compare the lists of branches, and keep only local branches which aren't in the list of remote branches
3. Since we will be forcing branch deletion, confirm with the user that we have the right branches before deleting
4. Delete all of the branches resulting from the comparison of the two lists
### Listing the Branches
The only unique requirement when listing out local and remote branches for this purpose is to make sure that the two lists are comparable. We want to be sure that a branch in the remote list can match up exactly with a corresponding branch in the list of local branches. Luckily git gives us the tools we need to format our branches into a clean list:
```bash
git branch -r --format "%(refname:lstrip=3)" > remotes
git branch --format "%(refname:lstrip=2)" > locals
```
#### Breakdown by Phrase
* `git branch`
* Lists out all local branches by default, adding the `-r` parameter lists only remote branches
* `--format`
* Gives options to output only specific pieces of information about each branch
* `refname`
* This part of the format string specifies that we only want the refname field from this branch. This is a complete unique identifier for each branch
* For local branches, this would look like `refs/heads/master`
* For remote branches, this would look like `refs/remotes/origin/master`
* `:lstrip=n`
* This is a modifier on the `refname` field. It is used to specify that the first `n` path sections should be removed from the branch name before it is output. For example, by stripping the first 3 sections off of a remote branch name `refs/remotes/origin/feature/dropdown`, it leaves just `feature/dropdown`. More info on git's formatting syntax is available here: https://git-scm.com/docs/git-for-each-ref#_field_names
* `> [filename]`
* Output everything into a file for use later on
### Comparing the Lists
The `grep` command is configurable enough to use it for this purpose by using a few command line options. In effect this configuration attempts to exactly match each line in `locals` against every line in `remotes`, and only output lines from `locals` which do not match.
```bash
cat locals | grep -x -v -f remotes > branchesToDelete
```
#### Breakdown by Phrase
* `cat locals | `
* Takes the `locals` file and pipes it into the next command. `grep` accepts this piped input
* `grep`
* The [grep](https://linux.die.net/man/1/grep) command
* `-x`
* Forces grep to only match full lines, instead of the default of partial matches inside of a line
* `-v`
* Inverts the output: typically grep would only output the input lines which match, now it will only output lines which do not match
* `-f remotes`
* Tells grep to attempt to match each input against every line in the `remotes` file
### Deleting the Branches
Once we have a list of all of the branches we want to get rid of, they are looped through, with each one deleted in sequence:
```bash
for branch in `cat branchesToDelete`;
do
git branch -D $branch
done
```
## Cleaning It Up
So far we have a pretty basic setup that will get us what we need:
```bash
git branch -r --format "%(refname:lstrip=3)" > remotes
git branch --format "%(refname:lstrip=2)" > locals
cat locals | grep -x -v -f remotes > branchesToDelete
for branch in `cat branchesToDelete`;
do
git branch -D $branch
done
```
But this has a few problems if we want to start using it more reliably. Most obvious is that it leaves a bunch of files lying around! Let's clean those up by adding a `rm` at the end:
```bash
rm branchesToDelete remotes locals
```
### User Input to Protect Active Local Branches
Next up, there's another problem. What if I've got a new local branch that I haven't pushed up yet? That branch would get deleted with what we have now, it'd be nice if I could exclude it from this process. Let's add an option to edit the list of branches right before they get deleted:
```bash
code branchesToDelete -w
```
This opens VSCode to edit the `branchesToDelete` file, and `-w` blocks the script execution until the file is closed. Now I can look through the list that's about to be deleted and make sure there's nothing I care about in there. This could be replaced with any editor command, even `notepad branchesToDelete` would work if you prefer not to use VSCode.
-----
What we have now does well when we're in a git repository, and have some branches to delete, but this might not always be the case when running the script. To finish it up let's add some early exits in case we're not in a repository, or in case we end up with no branches to delete. And a few informational printouts so a new user doesn't feel lost. That leaves us with the final product:
```bash
#!/usr/bin/env sh
if !(git rev-parse --is-inside-work-tree); then
echo "Not inside a git repository, aborting"
exit 0
fi
git remote prune origin
git branch -r --format "%(refname:lstrip=3)" > remotes
git branch --format "%(refname:lstrip=2)" > locals
cat locals | grep -xv -f remotes > branchesToDelete
# -w checks word counts to ignore blank lines
if [ $(wc -w < branchesToDelete) -gt 0 ];
then
echo "$(wc -l < branchesToDelete) branches without matching remote found, outputting to editor"
echo "Waiting for editor to close"
code branchesToDelete -w
for branch in `cat branchesToDelete`;
do
git branch -D $branch
done
else
echo "There are no branches to cleanup.";
fi
rm branchesToDelete remotes locals
```
# Registering as git command
To use this script in multiple repositories easily, it can be set up as a git command so that all it takes to run it is `git clean-branches` from any console. The setup for this is pretty quick:
---
### Create script in /usr/bin/
Copy or create a script to become a git command into your git installation's `/usr/bin/` directory, on Windows it is likely here: `C:\Program Files\Git\usr\bin`.
This can be found on windows by navigating to `/usr/bin/` in a Git bash console, and opening an explorer window at that location with `explorer .`
---
### Set script name
Rename the script based on what you want the name of the command to be. In this case "git-clean-branches", note that there is no `.sh` extension in the name. Git will look for filenames starting with "git-", and take the remaining part of the whole filename as the command's name.
Since there is no file extension there must be a shebang at the start of the file to indicate how the script is to be run (`#!/usr/bin/env sh`)
---
### Done!
Now any terminal that has access to regular Git commands will also have access to your new custom script
# Conclusion
Taking some time to build tools to help yourself or other work a little faster is something that I find can be quite rewarding. I hope that this not only helps clean up your git repos in the future, but also inspires you to look for other ways you can reduce repetitiveness in your workflow with these sorts of tools. Once you start automating things, it's hard to resist continuing to automate.
# About Me
I started my adventure in coding by playing around with coding environments such as [Scratch](https://scratch.mit.edu/), [Processing](https://processing.org/), and [Grobots](http://grobots.sourceforge.net/). After making it through college I got started in web development, working with Angular front-ends and NodeJS or C# back-ends. In my free time I love to play games like Factorio and Noita, or occasionally trying my hand at woodwork.<file_sep>#!/usr/bin/env sh
if !(git rev-parse --is-inside-work-tree); then
echo "Not inside a git repository, aborting"
exit 0
fi
git remote prune origin
# more info on the --format option's syntax available here: https://git-scm.com/docs/git-for-each-ref#_field_names
git branch -r --format "%(refname:lstrip=3)" > remotes
git branch --format "%(refname:lstrip=2)" > locals
# with these flags, grep outputs items from the input pipe (locals) which do not exactly match any line of the input file (remotes)
# this gits us the set of local branches which are not listed when (git branch -r) is run
cat locals | grep -xv -f remotes > branchesToDelete
# -w checks word counts that way we can ignore blank lines
if [ $(wc -w < branchesToDelete) -gt 0 ];
then
echo "$(wc -l < branchesToDelete) branches without matching remote found, outputting to editor"
echo "Waiting for editor to close"
code branchesToDelete -w &&
for branch in `cat branchesToDelete`;
do
git branch -D $branch
done
else
echo "There are no branches to cleanup.";
fi
rm branchesToDelete remotes locals | 0132b0071c424d1edf3d7ec767bd10fe8b9ca151 | [
"Markdown",
"Shell"
]
| 2 | Markdown | dsmiller95/CleanLocalGitBranches | 8044a1882555342f22c67c993c576c96aa39a8cb | 9589b1d3283d1b66c4ae5fc132874ae5e8e270fa |
refs/heads/master | <file_sep>
% update 'datadirectory' variable in dva_make_chart_fitted.m
% to point to the software controller output directory
% The software output directory should be under the user directory
dva_make_chart_fitted('PATIENT_NAME');<file_sep>/*
* PatientReader.java
*
* Created on June 5, 2007, 7:36 AM
*
*/
package dva.xml;
import dva.DvaCheckerException;
import dva.Patient;
import dva.util.DvaLogger;
import java.io.CharArrayWriter;
import java.io.Reader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.ParserAdapter;
/**
*
* @author J-Chris
*/
public class PatientReader extends DefaultHandler {
String text = "";
private Patient patient = new Patient();
/**
*
* @param connection
* @param userBean
* @return
*/
final private static PatientReader getInstance() {
PatientReader instance = new PatientReader();
return instance;
}
/**
*
*
*/
private PatientReader() {
}
/**
*
* @param connection
* @param userBean
* @param file
* @throws DvaCheckerException
*/
public static Patient process(Reader reader) throws DvaCheckerException {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
ParserAdapter pa = new ParserAdapter(sp.getParser());
PatientReader patientReader = PatientReader.getInstance();
pa.setContentHandler(patientReader);
pa.parse(new InputSource(reader));
return patientReader.patient;
} catch (Exception e) {
throw new DvaCheckerException("Failed to get patient data", e);
}
}
/**
*
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String namespace, String localName, String qName, Attributes atts) {
text = "";
}
public String getText(){
return text.trim();
}
public void characters(char[] ch, int start, int length)
{
text = new String(ch, start, length);
//DvaLogger.debug(PatientReader.class, "value:"+text );
}
/**
*
* @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
public void endElement(String namespace, String localName, String qName) {
//DvaLogger.debug(PatientReader.class, "startElement/localName:"+localName + ", text:" + getText());
if (localName.equals("lastname")) {
patient.setLastname( getText() );
} else if (localName.equals("firstname")) {
patient.setFirstname( getText() );
} else if (localName.equals("sex")) {
patient.setSex( getText() );
} else if (localName.equals("age")) {
patient.setAge( getText() );
} else if (localName.equals("comment")) {
patient.setComment( getText() );
}
}
}
<file_sep>/*
* ImagesBuffer.java
*
* Created on June 11, 2007, 3:54 AM
*
*/
package dva.util;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import javax.imageio.ImageIO;
/**
*
* @author J-Chris
*/
public class ImagesBuffer {
final public static DvaLogger.LogLevel level = DvaLogger.LogLevel.INFO;
//list of already instancied bufferedimage
private static HashMap<String, BufferedImage> bimgList = new HashMap<String, BufferedImage>();
//prevent from instanciation
private ImagesBuffer() {
}
public static BufferedImage get(String name){
//check if bufferedImage is already existing
BufferedImage bimg = bimgList.get(name);
if (bimg==null) {
//open file
//URL url = this.getClass().getResource("/dva/ressources/"+name+".jpg");
URL url = BufferedImage.class.getResource("/dva/ressources/"+name+".jpg");
if (url!=null){
try {
bimg = ImageIO.read(url);
bimgList.put(name, bimg);
} catch (IOException ex) {
DvaLogger.fatal( ImagesBuffer.class, ex, "Failed to read image file " + url.getFile() );
}
} else {
DvaLogger.fatal(ImagesBuffer.class, "Failed to access image " + "/dva/ressources/"+name+".jpg");
}
} else {
DvaLogger.debug(ImagesBuffer.class, "Re-use bufferedimage named '" + name + "'");
}
return bimg;
}
}
<file_sep>/*
* AcuityTestConvergenceException.java
*
* Created on June 4, 2007, 10:21 PM
*
*/
package dva.acuitytest;
/**
*
* @author J-Chris
*/
public class AcuityTestConvergenceException extends AcuityTestException {
/** Creates a new instance of AcuityTestConvergenceException */
public AcuityTestConvergenceException(double value, double stddev) {
super("The converged value is " + value + " with stddev: " + stddev);
}
}
<file_sep>/*
* OptotypeC.java
*
* Created on May 17, 2007, 12:31 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package dva.rr_moved;
import dva.displayer.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
/**
*
* @author J-Chris
*/
public class OptotypeC extends Element {
public OptotypeC(int x, int y, float size, Color color) {
super(x, y, color);
this.size = size;
init();
}
public OptotypeC(float size, Color color) {
super(color);
this.size = size;
init();
}
public OptotypeC(float size, Orientation orientation) {
super(orientation);
this.size = size;
init();
}
public OptotypeC(float size) {
this.size = size;
init();
}
private void init(){
float gapsize = size / 5;
float sizeIn = size - gapsize * 2;
Ellipse2D.Float circleOut = new Ellipse2D.Float(x - size / 2, y - size / 2, size, size);
Ellipse2D.Float circleIn = new Ellipse2D.Float(x - sizeIn/2, y - sizeIn / 2, sizeIn, sizeIn);
Rectangle2D.Float gap = new Rectangle2D.Float(x, y - gapsize /2, size / 2, gapsize);
// Create Areas from the shapes.
area = new Area(circleOut);
area.subtract( new Area(circleIn) );
area.subtract( new Area(gap) );
}
public void setOrientation(Orientation orientation){
}
public String toString(){
return "OPTOTYPE_C";
}
// Return the circle as a Shape reference
public Shape getShape() {
return area;
}
public float getSize() {
return size;
}
public void draw(Graphics2D g2D){
AffineTransform tx = new AffineTransform();
//translate to origine
tx.translate(x, y);
//rotate
tx.rotate(Math.toRadians( orientation.ordinal() * 45 ) );
//translate back
tx.translate(-x, -y);
//apply transform
g2D.setTransform(tx);
g2D.setPaint(this.color);
g2D.draw(area);
g2D.fill(area);
}
public String toXml(){ return ""; }
// Return the rectangle bounding this circle
public java.awt.Rectangle getBounds() {
return area.getBounds();
}
private float size;
private Area area;
}
<file_sep>/*
* PatientFileCreationException.java
*
* Created on June 5, 2007, 12:56 AM
*
*/
package dva;
import java.io.File;
/**
*
* @author J-Chris
*/
public class PatientFileCreationException extends DvaCheckerException {
/** Creates a new instance of PatientFileCreationException */
public PatientFileCreationException(File file) {
super("Failed to create patient file:" + (file != null ? file.getAbsoluteFile() : "NULL") );
}
public PatientFileCreationException(File file, Throwable cause) {
super("Failed to create patient file:" + (file != null ? file.getAbsoluteFile() : "NULL"), cause);
}
}
<file_sep>/*
* DvaLogger.java
*
* Created on May 8, 2007, 3:42 AM
*
*/
package dva.util;
import java.lang.reflect.Field;
/**
*
* @author J-Chris
*/
public class DvaLogger {
final public static DvaLogger.LogLevel level = DvaLogger.LogLevel.DEBUG;
public enum LogLevel {
DEBUG, INFO, WARN, ERROR, FATAL
}
public static void debug(String msg){
log(LogLevel.DEBUG, msg);
}
public static void debug(Class clazz, String msg){
log(LogLevel.DEBUG, clazz, null, msg);
}
public static void debug(Class clazz, Exception e){
log(LogLevel.DEBUG, clazz, e, null);
}
public static void info(String msg){
log(LogLevel.INFO, msg);
}
public static void info(Class clazz, String msg){
log(LogLevel.INFO, clazz, null, msg);
}
public static void warn(String msg){
log(LogLevel.WARN, msg);
}
public static void warn(Class clazz, String msg){
log(LogLevel.WARN, clazz, null, msg);
}
public static void warn(Class clazz, Exception e){
log(LogLevel.WARN, clazz, e, null);
}
public static void warn(Class clazz, Exception e, String msg){
log(LogLevel.WARN, clazz, e, msg);
}
public static void error(Class clazz, String msg){
log(LogLevel.ERROR, clazz, null, msg);
}
public static void error(Class clazz, Exception e){
log(LogLevel.ERROR, clazz, e, null);
}
public static void error(Class clazz, Exception e, String msg){
log(LogLevel.ERROR, clazz, e, msg);
}
public static void fatal(String msg){
log(LogLevel.FATAL, msg);
}
public static void fatal(Class clazz, String msg){
log(LogLevel.FATAL, clazz, null, msg);
}
public static void fatal(Class clazz, Exception e){
log(LogLevel.FATAL, clazz, e, null);
}
public static void fatal(Class clazz, Exception e, String msg){
log(LogLevel.FATAL, clazz, e, msg);
}
public static void log(LogLevel level, String msg){
log(level, null, null, msg);
}
public static void log(LogLevel level, Exception e, String msg){
log(level, null, e, msg);
}
/**
* Append a String to the jTextAreaLog maintaining the log size below a given limit
*/
public static void log(LogLevel level, Class clazz, Exception e, String msg){
if (jTextAreaLog==null) return;
if (e!=null) e.printStackTrace();
DvaLogger.LogLevel clazzLevel = currentLogLevel;
if (clazz != null){
try{
//check class local level
Field fLevel = clazz.getDeclaredField("level");
clazzLevel = (DvaLogger.LogLevel)fLevel.get(clazz);
//System.out.println("level:"+clazzLevel);
if (clazzLevel.ordinal() > level.ordinal()) return;
} catch (NoSuchFieldException nsfex){/* ignore */ }
catch (IllegalAccessException iaex){/* ignore */ }
}
if ( currentLogLevel.ordinal() <= level.ordinal() ){
if (msg==null) msg = "";
if (e!=null){
msg+=" " + e;
}
jTextAreaLog.append(">" + (clazz!=null ? "[" + clazz.getName() + "] ": "") + msg + "\n");
// if (e!=null){
// StackTraceElement stackTraceElement[] = e.getStackTrace();
// for (int i=0; i < stackTraceElement.length; i++){
// jTextAreaLog.append("\t" + stackTraceElement[i] + "\n" );
// }
//
// Throwable t = null;
// while ( (t = e.getCause()) != null){
//
// }
// }
if (jTextAreaLog.getLineCount() == logLineCount){
logCurrentTruncSize = jTextAreaLog.getDocument().getLength();
}
//check log size
if (jTextAreaLog.getLineCount() == logLineCount + logLineCount * 0.2){
jTextAreaLog.replaceRange("", 0, logCurrentTruncSize);
}
}
}
public static void initLogger(javax.swing.JTextArea _jTextAreaLog){
jTextAreaLog = _jTextAreaLog;
}
private static int logLineCount = 100;
private static int logCurrentTruncSize = 0;
private static LogLevel currentLogLevel = LogLevel.DEBUG;
private static javax.swing.JTextArea jTextAreaLog;
}
<file_sep>/*
* DisplayView.java
*
* Created on May 7, 2007, 2:48 PM
*
*/
package dva.displayer;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
/**
*
* @author J-Chris
*/
public class DisplayView extends JPanel implements Observer {
/**
* Creates a new instance of DisplayView
*/
public DisplayView(Displayer cd) {
this.cd = cd;
this.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
setBackground(Color.WHITE);
createPopupMenu();
}
public void createPopupMenu() {
JMenuItem menuItem;
//Create the popup menu.
JPopupMenu popup = new JPopupMenu();
//item resize
menuItem = new JMenuItem("Maximize/Restaure window");
menuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cd.resizeDisplayer();
}
});
popup.add(menuItem);
//Add listener to the text area so the popup menu can come up.
DisplayerMouseListener displayerMouseListener = new DisplayerMouseListener(popup);
addMouseListener(displayerMouseListener);
addMouseMotionListener(displayerMouseListener);
}
public void update(Observable o, Object Rectangle){
repaint();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2D = (Graphics2D)g;
//g2D.clearRect(0,0,this.getWidth(), this.getHeight());
g2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
// RenderingHints.VALUE_ANTIALIAS_ON);
// g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
// RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
if (cd.getDisplayModel().isMessage()){
AffineTransform tx = new AffineTransform();
//translate character
tx.translate( translateX, translateY );
//apply transform
g2D.setTransform(tx);
g2D.setFont(cd.getDisplayModel().getMessageFont());
g2D.setPaint(cd.getDisplayModel().getMessageColor());
g2D.drawString(cd.getDisplayModel().getMessageToDisplay(), cd.getDisplayModel().getX(), cd.getDisplayModel().getY());
//help garbage
tx = null;
} else if (cd.getDisplayModel().isImage()) {
g2D.drawImage(cd.getDisplayModel().getImage(), 0, 0, null);
} else {
Element el = cd.getDisplayModel().getCurrentDisplayedElement();
cd.getDisplayModel().getCurrentDisplayedElement().draw(g2D);
}
}
JPopupMenu popupMenu;
private Displayer cd;
private int translateX = 0;
private int translateY = 0;
class DisplayerMouseListener extends MouseAdapter implements MouseMotionListener {
private JPopupMenu popup;
private int lastOffsetX;
private int lastOffsetY;
DisplayerMouseListener(JPopupMenu popupMenu) {
popup = popupMenu;
}
public void mousePressed(MouseEvent e) {
// capture starting point
lastOffsetX = e.getX();
lastOffsetY = e.getY();
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(e.getComponent(),
e.getX(), e.getY());
}
}
//mousemotionlistener methods
public void mouseMoved(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {
// new x and y are defined by current mouse location subtracted
// by previously processed mouse location
int newX = e.getX() - lastOffsetX;
int newY = e.getY() - lastOffsetY;
// increment last offset to last processed by drag event.
lastOffsetX += newX;
lastOffsetY += newY;
// update the character location
translateX += newX;
translateY += newY;
// schedule a repaint.
repaint();
}
}
}
<file_sep>/*
* DisplayModel.java
*
* Created on May 7, 2007, 5:14 PM
*
*/
package dva.displayer;
import dva.acuitytest.AcuityTestConvergenceException;
import dva.acuitytest.AcuityTestDivergenceException;
import dva.acuitytest.AcuityTestManager;
import dva.acuitytest.AcuityTestMaxStepException;
import dva.util.DvaLogger;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Observable;
/**
*
* @author J-Chris
*/
public class DisplayModel extends Observable implements ComponentListener {
/**
* Creates a new instance of DisplayModel
*/
public DisplayModel() {
setDefault();
}
public Element getCurrentDisplayedElement(){
return currentElement;
}
public void updateX(int x){
currentElement.setX(x);
this.x = x;
setChanged();
notifyObservers();
}
public void updateY(int y){
currentElement.setY(y);
this.y = y;
setChanged();
notifyObservers();
}
public void update(int x, int y){
currentElement.setX(x);
currentElement.setY(y);
this.x = x;
this.y = y;
setChanged();
notifyObservers();
}
public void update(Element element, int size){
//keep current position
element.setX(currentElement.getX());
element.setY(currentElement.getY());
this.currentElement = element;
setChanged();
notifyObservers();
}
public void enableCallibration(){
currentElement = new Optotype(true);
}
public boolean setupAcuityTest(File patientdir) {
try {
AcuityTestManager.reset();
AcuityTestManager.setNextAcuityTest(patientdir);
setMessageToDisplay(resourceBundle.getString("message.displayer.patientready"));
return true;
} catch (Exception e){
DvaLogger.error(DisplayModel.class, e);
return false;
}
}
public State getState(){
return currentState;
}
public Element notifyOperatorEvent(OperatorEvent operatorEvent) {
try{
//if no acuitytest is available, exit
if (AcuityTestManager.getCurrentAcuityTest() == null) return null;
DvaLogger.debug(DisplayModel.class, "state:"+currentState);
if (currentState == State.INIT){
if (operatorEvent == OperatorEvent.NEXT_OPTOTYPE){
//save time
this.savedTime = System.currentTimeMillis();
//disable message
disableMessage();
disableImage();
//display next character
currentElement = AcuityTestManager.getCurrentAcuityTest().getNext();
//set new state
this.currentState = State.TESTING;
}
} else if (currentState == State.TESTING){
//compute answertime
answerTime = savedTime - System.currentTimeMillis();
//save patient response
if (operatorEvent != OperatorEvent.NEXT_OPTOTYPE){
//should be an 'OPTOTYPE_' event
this.patientAnswerStr = operatorEvent.toString();
this.patientAnswer = patientAnswerStr.equals(currentElement.toString());
}
//save patient answer
AcuityTestManager.getCurrentAcuityTest().saveAnswer(answerTime, this.currentElement, patientAnswer, patientAnswerStr);
//update status
AcuityTestManager.updateStatus();
if (AcuityTestManager.getStatus() == AcuityTestManager.Status.TEST_RUNNING) {
//if there is a pause between each character
if (pauseBetween){
//display ready message
setMessageToDisplay(resourceBundle.getString("message.displayer.patientready"));
//set new state
this.currentState = State.PAUSE;
} else {
disableMessage();
disableImage();
//display next character
currentElement = AcuityTestManager.getCurrentAcuityTest().getNext();
}
} else if (AcuityTestManager.getStatus() == AcuityTestManager.Status.TEST_DONE){
//update displayer
setMessageToDisplay(resourceBundle.getString("message.displayer.patientready"));
}
} else if (currentState == State.PAUSE){
if (operatorEvent == OperatorEvent.NEXT_OPTOTYPE){
disableMessage();
disableImage();
//display next character
currentElement = AcuityTestManager.getCurrentAcuityTest().getNext();
//set new state
this.currentState = State.TESTING;
}
}
//notify ModelView
setChanged();
notifyObservers(DisplayModel.EventType.OPERATOR_EVENT);
DvaLogger.debug(DisplayModel.class, "currentState:"+currentState);
return this.currentElement;
} catch (AcuityTestConvergenceException atcex){
AcuityTestManager.getCurrentAcuityTest().toFile();
setMessageToDisplay(atcex.getMessage());
DvaLogger.error(DisplayModel.class, atcex.getMessage());
} catch (AcuityTestDivergenceException atdex){
AcuityTestManager.getCurrentAcuityTest().toFile();
setMessageToDisplay(atdex.getMessage());
DvaLogger.error(DisplayModel.class, atdex.getMessage());
} catch (AcuityTestMaxStepException atmsex) {
AcuityTestManager.getCurrentAcuityTest().toFile();
setMessageToDisplay(atmsex.getMessage());
DvaLogger.error(DisplayModel.class, atmsex.getMessage());
} finally {
return null;
}
}
public void setPauseBetween(boolean pauseBetween){
this.pauseBetween = pauseBetween;
}
public BufferedImage getImage(){
return bimg;
}
public void disableImage(){
this.image = false;
this.bimg = null;
}
public void displayImage(BufferedImage bimg){
this.bimg = bimg;
this.image = true;
//notify ModelView
setChanged();
notifyObservers(DisplayModel.EventType.DISPLAY_IMAGE);
}
public void setMessageToDisplay(String messageToDisplay){
this.messageToDisplay = messageToDisplay;
this.message = true;
//notify ModelView
setChanged();
notifyObservers(DisplayModel.EventType.DISPLAY_MESSAGE);
}
public void disableMessage(){
this.message = false;
}
public String getMessageToDisplay(){
return messageToDisplay;
}
public Font getMessageFont(){
return messageFont;
}
public void setMessageFont(Font messageFont){
this.messageFont = messageFont;
}
public Color getMessageColor(){
return this.messageColor;
}
public void setMessageColor(Color messageColor){
this.messageColor = messageColor;
}
public boolean isMessage(){
return this.message;
}
public boolean isImage(){
return this.image;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void setDefault(){
x = resourceBundle.getInt("config.displayer.defaultX");
y = resourceBundle.getInt("config.displayer.defaultY");
}
public double getScaleCorrectionFactor() {
return scaleCorrectionFactor;
}
public void setScaleCorrectionFactor(double scaleCorrectionFactor) {
this.scaleCorrectionFactor = scaleCorrectionFactor;
//notify ModelView
setChanged();
notifyObservers(DisplayModel.EventType.SCALING);
}
public void componentHidden(ComponentEvent e){
//do nothing
}
public void componentMoved(ComponentEvent e){
//do nothing
}
public void componentResized(ComponentEvent e){
DvaLogger.debug(DisplayView.class, "Window resized");
//notify ModelView
setChanged();
notifyObservers(DisplayModel.EventType.RESIZED_WINDOW);
}
public void componentShown(ComponentEvent e) {
//do nothing
}
//state machine attributes
public enum OperatorEvent {NEXT_OPTOTYPE, OPTOTYPE_DONTKNOW, OPTOTYPE_C, OPTOTYPE_D, OPTOTYPE_H, OPTOTYPE_K, OPTOTYPE_N, OPTOTYPE_O, OPTOTYPE_R, OPTOTYPE_S, OPTOTYPE_V, OPTOTYPE_Z };
public enum State { INIT, TESTING, PAUSE, END };
public enum EventType { DISPLAY_MESSAGE, DISPLAY_IMAGE, OPERATOR_EVENT, SCALING, RESIZED_WINDOW};
boolean pauseBetween = false;
private State currentState = State.INIT;
//patient asnwer specific attribute
private long savedTime;
private long answerTime;
private boolean patientAnswer = true;
private String patientAnswerStr = "";
//Graphics attribute
private int x;
private int y;
private Element currentElement = new Optotype(true);
private double scaleCorrectionFactor = 1;
//image attribute
private BufferedImage bimg = null;
private boolean image = false;
//message attributes
private String messageToDisplay = "";
private boolean message = false;
private Font messageFont = new Font("Tahoma", Font.PLAIN, 40);
private Color messageColor = Color.BLACK;
//resources
private dva.util.MessageResources resourceBundle = new dva.util.MessageResources("dva/Bundle"); // NOI18N;
}
<file_sep>/*
* AcuityTestFileCreationException.java
*
* Created on June 5, 2007, 3:46 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package dva.acuitytest;
import dva.DvaCheckerException;
import java.io.File;
/**
*
* @author J-Chris
*/
public class AcuityTestFileCreationException extends DvaCheckerException {
/** Creates a new instance of AcuityTestFileCreationException */
public AcuityTestFileCreationException(File file) {
super("Failed to create acuitytest file:" + (file != null ? file.getAbsoluteFile() : "NULL") );
}
public AcuityTestFileCreationException(File file, Throwable cause) {
super("Failed to create acuitytest file:" + (file != null ? file.getAbsoluteFile() : "NULL"), cause);
}
}
<file_sep>/*
* DisplayElement.java
*
* Created on May 8, 2007, 2:56 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package dva.displayer;
import dva.displayer.Element.Orientation;
import dva.util.DvaLogger;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
/**
*
* @author J-Chris
*/
public class DisplayElement extends Element {
public DisplayElement(String character, float size){
this.character = character;
this.font = this.font.deriveFont(size);
}
public DisplayElement(String character, float size, Orientation orientation){
super(orientation);
this.character = character;
this.font = this.font.deriveFont(size);
//rotate font
AffineTransform tx = new AffineTransform();
tx.rotate( Math.toRadians(orientation.ordinal() * 45 ) ) ;
this.font = this.font.deriveFont(tx);
}
public DisplayElement(int x, int y, String character, float size){
super(x, y);
this.character = character;
this.font = this.font.deriveFont(size);
}
public DisplayElement(int x, int y, String character, float size, Orientation orientation){
super(x, y);
this.character = character;
this.font = this.font.deriveFont(size);
//rotate font
AffineTransform tx = new AffineTransform();
tx.rotate( Math.toRadians(orientation.ordinal() * 45 ) ) ;
this.font = this.font.deriveFont(tx);
this.orientation = orientation;
}
public DisplayElement(int x, int y, String character, Font font) {
super(x, y);
this.character = character;
this.font = font;
}
/**
* Creates a new instance of DisplayElement
*/
public DisplayElement(int x, int y, String character, Font font, Orientation orientation) {
super(x, y);
this.character = character;
this.font = font;
this.orientation = orientation;
//rotate font
AffineTransform tx = new AffineTransform();
tx.rotate( Math.toRadians(orientation.ordinal() * 45 ) ) ;
this.font = this.font.deriveFont(tx);
}
public java.awt.Rectangle getBounds(FontRenderContext fontRenderContext){
return (java.awt.Rectangle)font.getMaxCharBounds(fontRenderContext);
}
public java.awt.Rectangle getBounds(){
return null;
}
public Shape getShape(){
return null;
}
public String getCharacter(){
return character;
}
public void setCharacter(String character){
this.character = character;
}
public Font getFont(){
return font;
}
public void setFont(Font font){
this.font = font;
}
public void setOrientation(Orientation orientation){
this.orientation = orientation;
//rotate font
AffineTransform tx = new AffineTransform();
tx.rotate( Math.toRadians(orientation.ordinal() * 45 ) ) ;
this.font = this.font.deriveFont(tx);
}
public void reset(){
font = new Font("Tahoma", Font.PLAIN, 30);
}
public float getSize(){
DvaLogger.debug(DisplayElement.class, "Size:" + font.getSize());
return font.getSize();
}
public String toString(){
return character;
}
public void setSize(float size){
this.font = this.font.deriveFont(size);
}
public void draw(Graphics2D g2D){
g2D.setFont(getFont());
g2D.setPaint(getColor());
g2D.drawString(character, x, y);
}
public String toXml(){
StringBuffer sb = new StringBuffer("<displayelement><character>");
sb.append(character);
sb.append("</character><size>");
sb.append(this.getSize());
sb.append("</size></displayelement>");
return sb.toString();
}
private String character = "0";
private Font font = new Font("Tahoma", Font.PLAIN, 30);
}
| 76b83b053cab995897cad5afe2998baca5d1baac | [
"Java",
"Text"
]
| 11 | Text | jcfr/dvachecker | ee39804711dccc1ebda1d3507339b0e46555d87d | 2887bfb14cc31ef9ae7a623f4c4a735c4a0ec04d |
refs/heads/master | <file_sep><?php
session_start();
//suppress notices
//error_reporting(E_ALL ^ E_NOTICE);
if(!isset($_SESSION['email']) && (!strpos($_SERVER['REQUEST_URI'], "index.php")))
header("location:index.php?loggedIn=no");
//Connect to database
include 'dbConnect.php';
include '../_publicFunctions.php';
//Global Variables
$pageTitle = "Admin Interface";
$region = $_SESSION['region'];
$table = $region;
$header = "_header.php";
$footer = "_footer.php";
$msg = isset($_GET['msg']) ? mysqli_real_escape_string($dblink, $_GET['msg']) : null;
$err = isset($_GET['err']) ? mysqli_real_escape_string($dblink, $_GET['err']) : null;
//File Upload variables
$rootUploadDirectory = "http://fpan.us/uploads/";
$uploadDirectory = "../uploads/$region/";
$allowed_filetypes = array('.svg','.SVG','.jpg','.JPG','.gif','.GIF','.bmp','.BMP','.png','.PNG',
'.txt','.TXT','.doc','.DOC','.docx','.DOCX','.pdf','.PDF','.rtf','.RTF',
'.odt','.ODT','.xls','.xlsx','.XLS','.XLSX','.ppt','.pptx','.PPT','.PPTX');
$max_filesize = 15000000; // Maximum filesize in BYTES (currently 15MB), must also be set in php.ini
$calPage = "eventList.php";
//Determine newsletter folder names from region abbreviations
switch($region){
case "nwrc":
$newsletter = "northwest";
break;
case "ncrc":
$newsletter = "northcentral";
break;
case "nerc":
$newsletter = "northeast";
break;
case "crc":
$newsletter = "central";
break;
case "wcrc":
$newsletter = "westcentral";
break;
case "ecrc":
$newsletter = "eastcentral";
break;
case "serc":
$newsletter = "southeast";
break;
case "swrc":
$newsletter = "southwest";
break;
default:
break;
}
//Check to see if form field is blank throw error if it is
function check_input($field,$msg){
$field = trim($field);
$field = stripslashes($field);
$field = htmlspecialchars($field);
global $page;
if(empty($field))
event_error($msg,$page);
}
//Check date for mm/dd/yyyy format
function check_date($date){
global $page;
$regex = "'(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](20)\d\d'";
$msg = "Please enter a valid date. Must use mm/dd/yyyy format.";
check_input($date,"Date must not be blank.");
if(!preg_match($regex,$date))
event_error($msg,$page);
}
//Check time for hh:mm format
function check_time($time){
global $page;
check_input($time,"Times must not be blank.");
// HH:MM format, leading zeroes optional
$regex = "/^([0]?[1-9]|1[0-2]):([0-5][0-9])\s?(?:AM|PM)$/i";
$msg = "Please enter a valid time. Must use hh:mm am/pm format.";
if(!preg_match($regex,$time))
event_error($msg,$page);
}
//Redirect and display error message
function event_error($msg,$page){
global $eventID;
$redirect = "location:$page?msg=$msg&err=true";
if($eventID)
$redirect .= "&eventID=$eventID";
header($redirect);
die();
}
?><file_sep><?php
include '../header.php';
$employeeSql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($employeeSql);
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true){
$formVars = $_SESSION['formVars'];
$activityDate = $formVars['year'] ."-". $formVars['month'] ."-". $formVars['day'];
$typeMedia = $formVars['typeMedia'];
$comments = $formVars['comments'];
//Insert new Activity ID
$sql = "INSERT INTO Activity VALUES (NULL);";
if(!mysql_query($sql)){
$err = true;
$msg .= ' Error: ' . mysql_error();
}
//Insert activity info with new Activity ID
$sql = "INSERT INTO Publication (id, submit_id, activityDate, typeMedia, comments)
VALUES (LAST_INSERT_ID(), '$_SESSION[my_id]', '$activityDate', '$typeMedia', '$comments');";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error();
}
//For each staff member checked, insert entry into EmployeeActivity to associate that employee with this activity
foreach($formVars['staffInvolved'] as $staff){
$sql = "INSERT INTO EmployeeActivity VALUES ($staff, LAST_INSERT_ID());";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error();
}
}
//If there were no erorrs while inserting: Clear temporary event array, display success message
if($err != true){
$_SESSION['formVars'] = "";
$msg = "Activity was successfully logged!";
}
?>
<div class="summary">
<br/><br/>
<?php echo "<h3>".$msg."</h3>"; ?>
<br/><br/><br/><br/>
<a href="<?php echo $_SERVER['../PHP_SELF']; ?>">Enter another Publication activity</a> or
<a href="../main.php">return to main menu</a>.
<br/><br/>
</div>
<?php } //End confirmed submission IF ?>
<?php //Form has been submitted. Process form submission.
if(isset($_POST['submit']) && !isset($_POST['confirmSubmission'])){
// Sanitize Data
$formVars['month'] = mysql_real_escape_string(addslashes($_POST['month']));
$formVars['day'] = mysql_real_escape_string(addslashes($_POST['day']));
$formVars['year'] = mysql_real_escape_string(addslashes($_POST['year']));
$formVars['typeMedia'] = mysql_real_escape_string(addslashes($_POST['typeMedia']));
$formVars['staffInvolved'] = $_POST['staffInvolved'];
$formVars['comments'] = mysql_real_escape_string(addslashes($_POST['comments']));
$activityDate = $formVars['year'] ."-". $formVars['month'] ."-". $formVars['day'];
$_SESSION['formVars'] = $formVars;
?>
<br/><br/>
<div class="summary">
<br/>
<br/>
<div style="text-align:left; margin-left:100px;">
<?php
echo "<strong>Date:</strong> " .$activityDate."<br/>";
echo "<strong>Media Type:</strong> ".$formVars['typeMedia']."<br/>";
echo "<strong>The staff involved:</strong> <br/>";
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName']." ".$employee['lastName'];
if(in_array($employee['id'], $formVars['staffInvolved']))
echo "<span style=\"margin-left:10px;\">". $employeeName."</span><br/>";
}
echo "<strong>Comments:</strong> ".$formVars['comments']."<br/>";
?>
</div>
<br/><br/>
If any of this is incorrect, please
<a href="<?php echo $_SERVER['../PHP_SELF']; ?>"> go back and correct it</a>.
<br/><br/>
Otherwise, please confirm your submission:
<br/><br/>
<form id="submissionForm" method="post" action="<?php echo $_SERVER['../PHP_SELF']; ?>" >
<input type="hidden" name="confirmSubmission" value="true" />
<input type="submit" name="submit" value="Confirm" />
</form>
<br/>
<br/>
</div>
<?php }elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="publications" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Publication</h2>
<p>Please fill out the information below to log this activity.</p>
</div>
<ul>
<li id="li_1" >
<label class="description" for="element_1">Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text" required="required"> /
<label for="element_1_1">MM</label>
</span>
<span>
<input id="element_1_2" name="day" class="element text" size="2" maxlength="2" value="<?php echo $formVars['day']; ?>" type="text" required="required"> /
<label for="element_1_2">DD</label>
</span>
<span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text" required="required"><a class="red"> *</a>
<label for="element_1_3">YYYY</label>
</span>
<span id="calendar_1">
<img id="cal_img_1" class="datepicker" src="../images/calendar.gif" alt="Pick a date.">
</span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</li>
<li id="li_3" >
<label class="description" for="element_3">Type of Media </label>
<div>
<select class="element select small" id="element_3" name="typeMedia" required="required">
<option value="" selected="selected"></option>
<option value="Book" <?php if($formVars['typeMedia'] == 'Book') echo 'selected="selected"'; ?> >Book</option>
<option value="Chapter" <?php if($formVars['typeMedia'] == 'Chapter') echo 'selected="selected"'; ?> >Chapter</option>
<option value="Magazine" <?php if($formVars['typeMedia'] == 'Magazine') echo 'selected="selected"'; ?> >Magazine</option>
<option value="Newspaper" <?php if($formVars['typeMedia'] == 'Newspaper') echo 'selected="selected"'; ?>>Newspaper</option>
<option value="Newsletter" <?php if($formVars['typeMedia'] == 'Newsletter') echo 'selected="selected"'; ?>>Newsletter</option>
<option value="Blog" <?php if($formVars['typeMedia'] == 'Blog') echo 'selected="selected"'; ?>>Blog</option>
<option value="Other" <?php if($formVars['typeMedia'] == 'Other') echo 'selected="selected"'; ?>>Other</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_5" >
<?php include("../staffInvolved.php"); ?>
</li>
<li id="li_2" >
<label class="description" for="element_2">Comments </label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium" onKeyDown="limitText(this.form.comments,this.form.countdown,2080);"
onKeyUp="limitText(this.form.comments,this.form.countdown,2080);"><?php echo $formVars['comments']; ?></textarea><br/>
<font size="1">(Maximum characters: 2080)<br>
You have <input readonly type="text" name="countdown" size="3" value="2080"> characters left.</font>
</div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close else ?>
<div id="footer"> </div>
</div>
<img id="bottom" src="../images/bottom.png" alt="">
</body></html><file_sep><?php
$pageTitle = "Programs";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Project Archaeology</h1></th>
</tr>
<tr>
<td>
<p class="center">
<img src="images/projectArchaeology.jpg" class="padded" />
</p><br/>
<p>
<br/>
<strong>Project Archaeology: Investigating Shelter</strong> is a supplementary science and social studies curriculum unit for grades 3 through 5. This workshop aims to familiarize educators with archaeology resources for the classroom that enhance learning opportunities in math, science, art, and social studies. Workshop participants will receive archaeology education guides published byProject Archaeology that take students through scientific processes and an archaeological investigation of Kingsley Plantation, including accounts from oral history, use of primary documents, and interpreting the archaeological record. <br />
<br />
To learn more about Project Archaeology, visit <a href="http://www.projectarchaeology.org/" target="_blank">www.projectarchaeology.org</a>. <br />
</p>
<br />
<hr/>
<p>
<h4> <a href="http://www.flpublicarchaeology.org/programs/">< Go Back to Program List</a></h4>
</p>
</td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?><file_sep><?php
$pageTitle = "Home";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Welcome to the West Central Region</h1></th>
</tr>
<tr>
<td class="table_mid">
<p align="center"><img src="images/WestCentral.jpg" alt="West Central" border="0"
usemap="#map_wc" style="border: 0;" href="#" />
<map name="map_wc" id="map_wc">
<area shape="poly" alt="Explore Brevard County"
coords="139,36,157,27,182,18,204,25,224,49,240,70,258,84,256,100,272,123,287,138,293,158,295,170,220,171,137,170,138,116,137,95,137,65,130,64,131,48,140,47"
href="explore.php?county=polk" />
<area shape="poly" coords="139,293,219,294,218,233,139,233" href="explore.php?county=desoto" />
<area shape="poly" coords="291,171,219,172,220,236,220,294,271,294,270,277,287,277,324,258" href="explore.php?county=highlands" />
<area shape="poly" coords="139,172,218,171,218,232,140,232" href="explore.php?county=hardee" />
<area shape="poly" coords="54,223,105,223,106,256,136,258,137,294,106,293,105,310,84,313,68,290,63,263,52,247" href="explore.php?county=sarasota" />
<area shape="poly" coords="137,172,136,256,107,255,107,222,53,222,30,206,31,195,37,189,48,192,43,183,50,171" href="explore.php?county=manatee" />
<area shape="poly" coords="38,64,37,96,47,101,44,106,58,106,59,117,57,124,55,130,67,136,70,132,67,123,76,131,56,169,136,170,135,66" href="explore.php?county=hillsborough" />
<area shape="poly" coords="29,11" href="#" />
<area shape="poly" coords="27,14,106,12,106,5,138,4,138,45,129,47,129,63,14,64" href="explore.php?county=pasco" />
<area shape="poly" coords="15,66,2,133,13,146,23,168,34,165,44,157,52,129,56,121,41,114,42,107,35,103,36,97,36,65" href="explore.php?county=pinellas" />
</map>
</p>
<p>The West Central Region is hosted by the University of South Florida in Tampa, Florida. The West Central region covers Desoto, Hardee, Highlands, Hillsborough, Manatee, Pasco, Pinellas, Polk and Sarasota counties.</p>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include '../events/eventBox.php'; ?><br/>
<?php include '../events/calendar.php'; ?>
</div>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?>
<file_sep><?php
include $header;
$link = mysqli_connect($server, 'fpan_dbuser', '$ESZ5rdx', 'fpan_events') ;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// number of events to show per page
$rowsperpage = 10;
//initialized some vars
$listEvents ="";
?>
<div class="container">
<div class="page-header">
<h1>Upcoming Events</h1>
</div>
<div class="row">
<div class="col-sm-8">
<?php
$printDate = date('M d, Y', strtotime($_GET['eventDate']));
?>
<h3><small> All Events for</small> <?php echo $printDate; ?> </h3>
<div class="row box box-line box-tab">
<?php
$class = (isset($err) ? $class="alert-danger" : $class="alert-success");
if($msg) //if there is an error or success message, display it
echo "<p class=\"text-center $class\"> $msg </p>";
//If eventDate is define in URL, show only events for that day
if($_GET['eventDate']){
$eventDate = $_GET['eventDate'];
//Get events that match this day
$sql = "SELECT * FROM $table WHERE eventDateTimeStart LIKE '$eventDate%' ORDER BY eventDateTimeStart ASC;";
//if eventDate is not set, show all upccoming events
}else{
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM $table
WHERE eventDateTimeStart >= CURDATE()";
$result = mysqli_query($link, $sql);
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT * FROM $table
WHERE eventDateTimeStart >= CURDATE()
ORDER BY eventDateTimeStart ASC
LIMIT $offset, $rowsperpage";
}
$listEvents = mysqli_query($link, $sql);
//If events found, print out events
if(mysqli_num_rows($listEvents) != 0){
while($event = mysqli_fetch_array($listEvents)){
$timestampStart = strtotime($event['eventDateTimeStart']);
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventDate = date('F j', $timestampStart);
$eventTimeStart = date('g:i a', $timestampStart);
$eventTimeEnd = date('g:i a', $timestampEnd);
?>
<div class="row">
<p class="col-md-7 col-md-push-5 text-center">
<strong><?php echo $eventDate?> @ <?php echo $eventTimeStart ?> til <?php echo $eventTimeEnd;?></strong><br/>
<?php echo stripslashes($event['title']) ?>
</p>
<div class="col-md-5 col-md-pull-7 text-center">
<a class="btn btn-sm btn-primary" href="eventEdit.php?eventID=<?php echo $event['eventID'];?>" >Edit</a>
<a class="btn btn-sm btn-primary" href="eventEdit.php?eventID=<?php echo $event['eventID'];?>&dupe=true" >Duplicate</a>
<a class="btn btn-sm btn-primary" href="processEdit.php?eventID=<?php echo $event['eventID']; ?>&del=true" onclick="return confirm('Are you sure you want to delete this event?');">Delete</a>
</div>
</div>
<hr/>
<?php
}//end while
}else{
echo '<p class="text-center">No events are currently in the archive.</p>';
}
/****** build the pagination links ******/
if($totalpages > 1){
echo "<div class=\"text-center\">";
// range of num links to show on either side of current page
$range = 1;
// if not on page 1, show back links
if ($currentpage > 1) {
echo "<a class=\"btn btn-primary btn-sm hidden-xs\" href='{$_SERVER['PHP_SELF']}?currentpage=1'> << </a> ";
// get previous page num
$prevpage = $currentpage - 1;
echo " <a class=\"btn btn-primary btn-sm\" href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'> < </a>";
}
// if on page 1, disable back links
if ($currentpage == 1) {
echo "<button type=\"button\" class=\"btn btn-default btn-sm hidden-xs\" disabled=\"disabled\"> << </button> ";
echo "<button type=\"button\" class=\"btn btn-default btn-sm\" disabled=\"disabled\"> < </button> ";
}
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
echo "<button type=\"button\" class=\"btn btn-default\" disabled=\"disabled\">$x</button>";
// if not current page...
} else {
// make it a link
echo " <a class=\"btn btn-default\" href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
}
}
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
echo " <a class=\"btn btn-primary btn-sm\" href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'> > </a> ";
echo " <a class=\"btn btn-primary btn-sm hidden-xs\" href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'> > > </a> ";
} // end if
if ($currentpage == $totalpages) {
echo " <button type=\"button\" class=\"btn btn-default btn-sm\" disabled=\"disabled\"> > </button>";
echo " <button type=\"button\" class=\"btn btn-default btn-sm hidden-xs\" disabled=\"disabled\"> >> </button>";
}
echo "</div>";
}
/****** end build pagination links ******/
?>
</div><!-- /.row -->
</div><!-- /.row -->
<div class="col-sm-4">
<?php include '../events/calendar.php'; ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include $footer ?><file_sep><?php
$pageTitle = "Resources - Links";
include('../_header.php');
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1>Resources, <small>Links</small></h1>
</div>
<div class="col-md-6 col-sm-12">
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a href="http://www.panhandlehistoricalliance.org/" target="_blank">Panhandle Historic Preservation Alliance</a></li>
<!-- <li><a href="http://library.uwf.edu/phac/" target="_blank">Pensacola History and Archaeology Council</a></li> -->
<li><a href="http://www.sha.org" target="_blank">Society for Historical Archaeology</a></li>
<li><a href="http://www.saa.org" target="_blank">Society for American Archaeology</a></li>
<li><a href="http://www.archaeology.org" target="_blank">Archaeological Institute of America</a></li>
<li><a href="http://www.acuaonline.org" target="_blank">Advisory Council on Underwater Archaeology</a></li>
<li><a href="http://www.fasweb.org" target="_blank">Florida Anthropological Society</a></li>
<li><a href="http://www.nauticalarchaeologysociety.org" target="_blank">Nautical Archaeology Society</a></li>
<li><a href="http://www.flarchcouncil.org" target="_blank">Florida Archaeological Council </a></li>
<li><a href="http://dhr.dos.state.fl.us" target="_blank">Florida Division of Historical Resources</a></li>
<li><a href="http://www.uri.edu/mua/" target="_blank">Museum of Underwater Archaeology</a></li>
<li><a href="http://www.ncptt.nps.gov/" target="_blank"> National Center for Preservation Technology</a></li>
<li><a href="http://www.nps.gov/history/seac/" target="_blank">National Park Service Southeastern Archaeological Center</a></li>
<li><a href="http://www.flmnh.ufl.edu/histarch/" target="_blank">Florida Museum of Natural History, Historical Archaeology</a></li>
<li><a href="http://www.floridatrust.org/" target="_blank">Florida Trust for Historic Preservation</a></li>
<li><a href="http://www.myfloridahistory.org/" target="_blank">Florida Historical Society</a></li>
<li><a href="http://flarchaeology.org/" target="_blank"> Archaeological and Historical Conservancy</a></li>
</ul>
</div>
<h3>Florida Anthropology Departments</h3>
<div class="box-tab">
<ul>
<li><a href="http://uwf.edu/anthropology/" target="_blank">University of West Florida, Dept. of Anthropology</a></li>
<li><a href="http://anthropology.usf.edu/" target="_blank">University of South Florida, Dept. of Anthropology</a></li>
<li><a href="http://www.fau.edu/anthro/" target="_blank">Florida Atlantic University, Dept. of Anthropology</a></li>
<li><a href="http://www.unf.edu/coas/soc-anth/" target="_blank">University of North Florida, Dept. of Sociology and Anthropology</a></li>
<li><a href="http://anthropology.cos.ucf.edu/content/index.html" target="_blank">University of Central Florida, Dept. of Anthropology</a></li>
<li><a href="http://www.anthro.fsu.edu/" target="_blank">Florida State University, Dept. of Anthropology</a></li>
<li><a href="http://www.fgcu.edu/CAS/Anthropology/index.asp" target="_blank">Florida Gulf Coast University, Dept. of Anthropology</a></li>
<li><a href="http://www.ncf.edu/academics/concentrations/anthropology" target="_blank">New College, Program in Anthropology</a></li>
<li><a href="http://www.anthro.ufl.edu/" target="_blank">University of Florida, Dept. of Anthropology</a></li>
</ul>
</div>
</div>
<div class="col-md-6 col-sm-12">
<h3>Heritage Tourism</h3>
<div class="box-tab">
<ul>
<li><a href="http://www.floridapanhandledivetrail.com/" target="_blank">Panhandle Shipwreck Trail</a></li>
<li><a href="http://www.flpublicarchaeology.org/geocaching.php" target="_blank">Destination: Archaeology, Geo-Trail</a></li>
<li><a href="http://www.museumsinthesea.com" target="_blank">Florida's Underwater Archaeological Preserves</a></li>
<li><a href="http://www.flheritage.com/archaeology/underwater/maritime" target="_blank">Florida's Maritime Heritage Trail</a></li>
<li><a href="http://www.flheritage.com/archaeology/underwater/galleontrail" target="_blank">1733 Spanish Galleon Trail</a></li>
<li><a href="http://www.missionsanluis.org" target="_blank">Mission San Luis</a></li>
<li><a href="http://www.trailoffloridasindianheritage.org/" target="_blank">Trail of Florida's Indian Heritage</a></li>
<li><a href="http://www.floridastateparks.org/" target="_blank">Florida State Parks</a></li>
<li><a href="http://www.nps.gov/applications/parksearch/state.cfm?st=fl" target="_blank">National Parks in Florida</a></li>
<li><a href="http://www.moundhouse.org/index.htm" target="_blank">Mound House Museum</a></li>
</ul>
</div>
<h3>Civil War Sesquicentennial Links</h3>
<div class="box-tab">
<ul>
<li><a href="http://www.flheritage.com/preservation/trails/civilwar/index.cfm" target="_blank">Florida Civil War Heritage Trail </a></li>
<li><a href="http://www.nps.gov/features/waso/cw150th/" target="_blank">National Park Service - Civil War 150th</a></li>
<li><a href="http://www.georgiasouthern.edu/camplawton/index.php/home" target="_blank">GSU: Camp Lawton</a></li>
<li><a href="http://www.washingtonpost.com/wp-srv/lifestyle/special/civil-war-interactive/civil-war-battles-and-casualties-interactive-map/" target="_blank">Civil War Battles and Casualties, Interactive Map</a></li>
<li><a href="http://www.history.com/interactives/civil-war-150#/home" target="_blank">History Channel - Civil War 150</a></li>
<li><a href="http://www.illinoiscivilwar150.org/pdfs/SlaveryCause_CatalystNPS.pdf" target="_blank">Slavery: Cause and Catalyst of the Civil War </a></li>
<li><a href="http://civilwarflorida.blogspot.com/" target="_blank">Historian Dale Cox's Civil War blog about Florida in the Civil War</a></li>
</ul>
</div>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
//Determine if user has editing priveleges
function isAdmin(){
if(($_SESSION['my_role'] == 1) || ($_SESSION['my_role'] == 2))
return true;
else
return false;
}
function truncate($string, $limit, $break=" ", $pad="...")
{
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit) return $string;
$string = substr($string, 0, $limit);
if(false !== ($breakpoint = strrpos($string, $break))) {
$string = substr($string, 0, $breakpoint);
}
return $string . $pad;
}
//Return an array of all FPAN activities that user is allowed to see from specified table
function getActivities($table){
//SQL for region-specific activities if user is outreach coordinator/intern/other staff
if(($_SESSION['my_role'] == 2) || ($_SESSION['my_role'] == 3)){
$sql = "SELECT * FROM $table
WHERE submit_id IN (SELECT id FROM Employees
WHERE region = '$_SESSION[my_region]') ";
$sql.= "UNION ";
$sql.= "SELECT * FROM $table WHERE id IN(
SELECT activityID FROM EmployeeActivity
WHERE employeeID IN(
SELECT id FROM Employees
WHERE region = '$_SESSION[my_region]')) ORDER BY activityDate DESC; ";
//SQL for all region activities if user is admin
}elseif($_SESSION['my_role'] == 1){
$sql = "SELECT * FROM $table ORDER BY activityDate DESC";
}
$results = mysql_query($sql);
$results_array = array();
if(mysql_num_rows($results) != 0)
while($row = mysql_fetch_assoc($results)){
$results_array[] = $row;
}
return $results_array;
}
//Return array of all Professional Service events user is allowed to see from specified table
function getServices($table){
//SQL for region-specific activities if user is outreach coordinator/intern/other staff
if(($_SESSION['my_role'] == 2) || ($_SESSION['my_role'] == 3)){
$sql = "SELECT * FROM $table
JOIN Employees
ON $table.submit_id = Employees.id
WHERE $table.submit_id IN
(SELECT id FROM Employees WHERE region = '$_SESSION[my_region]')
ORDER BY $table.serviceDate DESC ";
//SQL for all region activities if user is admin
}elseif($_SESSION['my_role'] == 1){
$sql = "SELECT * FROM $table
JOIN Employees
ON $table.submit_id = Employees.id
ORDER BY serviceDate DESC";
}
$results = mysql_query($sql);
$results_array = array();
if(mysql_num_rows($results) != 0)
while($row = mysql_fetch_assoc($results)){
$results_array[] = $row;
}
return $results_array;
}
//Print activities of a given type
function printActivities($activityArray, $typeActivity, $displayLimit){
$startLimit = 1;
if($typeActivity == "PublicOutreach"){
echo "<table>";
foreach($activityArray as $activity){
echo "<tr><td><a href=\"publicOutreach.php?id=".$activity['id']."\">Edit</a> </td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("F d, Y", $displayDate)." </td><td>";
echo $activity['county']." </td><td>";
echo $activity['typeActivity']." </td><td>";
echo "</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
echo "</table>";
}
if($typeActivity == "TrainingWorkshops"){
foreach($activityArray as $activity){
$displayDate = strtotime($activity['activityDate']);
echo date("F d, Y", $displayDate)." - ";
echo $activity['county']." - ";
echo stripslashes($activity['activityName'])."<br/>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "GovernmentAssistance"){
foreach($activityArray as $activity){
$displayDate = strtotime($activity['activityDate']);
echo date("F d, Y", $displayDate)." - ";
echo $activity['county']." - ";
echo $activity['typeOrganization']." <br/>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "SocialMedia"){
foreach($activityArray as $activity){
$displayDate = strtotime($activity['activityDate']);
echo date('F, Y', $displayDate)."<br/>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "PressContact"){
foreach($activityArray as $activity){
$displayDate = strtotime($activity['activityDate']);
echo date("F d, Y", $displayDate)." - ";
echo $activity['typeMedia']." - ";
echo $activity['typeContact']."<br/>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "Publication"){
foreach($activityArray as $activity){
$displayDate = strtotime($activity['activityDate']);
echo date("F d, Y", $displayDate)." - ";
echo $activity['typeMedia']."<br/>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "DirectMail"){
foreach($activityArray as $activity){
$displayDate = strtotime($activity['activityDate']);
echo date("F d, Y", $displayDate)." - ";
echo " - Direct Mail <br/>";
if($startLimit++ == $displayLimit){break;}
}
}
}
//print services of a given type
function printServices($serviceArray, $typeService, $displayLimit){
$startLimit = 1;
if($typeService == "ServiceToProfessionalSociety"){
foreach($serviceArray as $service){
$employeeName = $service['firstName']." ".$service['lastName'];
$displayDate = strtotime($service['serviceDate']);
echo date("F, Y", $displayDate)." - ";
echo $employeeName." - ";
echo $service['typeSociety']." ";
echo "<br/>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "ServiceToHostInstitution"){
foreach($serviceArray as $service){
$employeeName = $service['firstName']." ".$service['lastName'];
$displayDate = strtotime($service['serviceDate']);
echo date("F, Y", $displayDate)." - ";
echo $employeeName." - ";
echo stripslashes($service['comments'])." ";
echo "<br/>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "ServiceToCommunity"){
foreach($serviceArray as $service){
$employeeName = $service['firstName']." ".$service['lastName'];
$displayDate = strtotime($service['serviceDate']);
echo date("F, Y", $displayDate)." - ";
echo $employeeName." - ";
echo stripslashes($service['comments'])." ";
echo "<br/>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "TrainingCertificationEducation"){
foreach($serviceArray as $service){
$employeeName = $service['firstName']." ".$service['lastName'];
$displayDate = strtotime($service['serviceDate']);
echo date("F, Y", $displayDate)." - ";
echo $employeeName." - ";
echo $service['typeTraining']." ";
echo "<br/>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "ConferenceAttendance"){
foreach($serviceArray as $service){
$employeeName = $service['firstName']." ".$service['lastName'];
$displayDate = strtotime($service['serviceDate']);
echo date("F, Y", $displayDate)." - ";
echo $employeeName." - ";
echo $service['typeConference']." ";
echo "<br/>";
if($startLimit++ == $displayLimit){break;}
}
}
}
?><file_sep><?php
$pageTitle = "Exhibits";
include('_header.php');
?>
<div class="page-content container">
<div class="page-header"><h1>Exhibits</h1></div>
<div class="row">
<div class="col-sm-10 col-sm-push-1 box-tab">
<h2>Permanent Exhibits</h2>
<h3>A Road Trip through Florida Archaeology</h3>
<p>With 500 years of European history and more than 10,000 years of Native American prehistory, Florida is host to an array of cultural landmark sites. Archaeological sites across the state have helped shed the light on our past. In this exhibit you will journey through the eight different regions of Florida and visit significant archaeological sites along the way. These include prehistoric mounds, shipwrecks, forts and Spanish missions, battlefields, and museums. Throughout the exhibit you can interact with digital displays and get a chance to touch real artifacts from a few of these sites. The best part about the sites featured in the exhibit- you can visit them in person and we can show you how to get there!</p>
<div class="text-center">
<div class="image">
<img src="images/exhibits.jpg" class="img-responsive" />
</div>
</div>
</div>
<div class="col-sm-10 col-sm-push-1 box-tab ">
<h2>Rotating Exhibits</h2>
<div class="row">
<h3>Lost Virtue <small>Currently on Display</small></h3>
<div class="col-md-7">
<p>During the Gilded Age (1870-1910), prostitution was seen as a necessary evil. According to popular belief at the time men had insatiable sexual appetites that needed to be channeled towards “appropriate avenues.” This often meant lower-class women, minorities, and especially prostitutes. </p>
<p>Cities like Pensacola sought to keep prostitution out of sight and their communities safer by segregating working girls into red light districts.</p>
<p>While the women who worked in Pensacola’s red light district left few written records behind, archaeology is finally helping to tell their story. Several artifacts associated with the women who worked in Pensacola’s red light district during the late 1800s and early 1900s uncovered through archaeology will be on display for the first time. <a href="//www.youtube.com/embed/iXn2m3P2cnc" class="youtube fancybox.iframe">View exhibit trailer on YouTube</a>.</p>
<p>Guest curator: <span class="curator"><NAME></span></p>
</div>
<div class="col-md-5">
<a href="images/lost_virtue.jpg" class="fancybox" ><img src="images/lost_virtue_sm.jpg" alt="Flyer for Lost Virtue exhibit" class="img-responsive"/></a>
</div>
</div>
<div class="row">
<h3>Talking Smack <small>Previously on Display</small></h3>
<div class="col-md-7">
<p>The end of the American Civil War offered almost limitless possibilities for northerners looking to bring business south. Pensacola, Florida, was one of the many southern port cities to bloom in the years following the war. The growth of the red snapper fishing industry in Pensacola contributed prominently to the city’s worldly and unique nature at the beginning of the 20th century.</p>
<p>Due to the huge boom in Pensacola, fish houses were established throughout Northwest Florida to partake in the lucrative red snapper market. While overfishing and international economic regulations largely ended commercial red snapper fishing from the area by the mid-20th century, the industry left an indelible mark on modern Northwest Florida.</p>
<p>The exhibit features artifacts on display from the shipwrecks of two fishing smacks excavated by University of West Florida archaeologists.</p>
<p>Guest curator: <span class="curator"><NAME></span></p>
</div>
<div class="col-md-5">
<a href="images/talking_smack_full.jpg" class="fancybox"><img src="images/talkingsmack.jpg" alt="Fishing industry" class="img-responsive"/></a>
</div>
</div>
<div class="row">
<h3>Mahogany and Iron <small>Previously on Display</small></h3>
<div class="col-md-7">
<p>In the late 1990s underwater archaeologists from the University of West Florida uncovered the remarkably well-preserved 17th century Spanish shipwreck of Nuestra Señora del Rosario y Santiago Apostal. Rosario was built in 1696 as a powerful warship for the Spanish navy. As part of the Windward Fleet, she protected convoys of ships loaded with valuable goods traveling between Spain and its New World colonies.</p>
<p>Throughout her career the ship performed many duties including hunting pirates and supplying far-flung settlements. The ship was lost in 1705 while resupplying the colony at Pensacola, then known as Presidio Santa María de Galve. This exhibit examines the excavation of this shipwreck and the clues archaeologists are uncovering about its construction currently under research. Several artifacts from the wreck are on display.</p>
<p>Guest curator: <span class="curator"><NAME></span></p>
</div>
<div class="col-md-5">
<a href="images/mahagony_iron_full.jpg" class="fancybox"><img src="images/mahagony_iron.jpg" alt="Mahogany and Iron Flyer" class="img-responsive"/></a>
</div>
</div>
<div class="row">
<h3>Rebel Guns <small>Previously on Display</small></h3>
<div class="col-sm-7">
<p>During the Civil War in Florida waterways were vital to the movement of troops and supplies. In the South, the Apalachicola River led straight to the manufacturing heart of the Confederacy in Columbus, Georgia. Controlling it meant victory or defeat. The Confederacy built obstacles in the river and gun emplacements, or batteries, at strategic points along the river edge to prevent the Union from passing upriver. </p>
<p>In 2010 a team of archaeologists from the University of West Florida and Florida Public Archaeology Network meticulously removed layers of earth in Florida’s Torreya State Park along the banks of the Apalachicola River. Here they uncovered a part of history from the American Civil War. This exhibit is the story of this site as it was revealed through archaeological investigations. </p>
<p>Guest curator: <span class="curator"><NAME></span></p>
</div>
<div class="col-sm-5">
<a href="images/rebel_guns.jpg" class="fancybox"><img src="images/rebel_guns_sm.jpg" alt="Rebel Guns Flyer" class="img-responsive"></a>
</div>
</div>
<div class="row">
<h3>Florida’s Fishing Ranchos: Legacy of Cuban Trade <small>Previously on Display</small></h3>
<div class="col-md-7">
<p>Before the Marxist inspired revolution of 1959, trade between Cuba and the land of Florida lasted for hundreds of years. Fishermen from Cuba found the waters on Florida’s southwest coast productive and markets in Havana made trade opportunities between them profitable. By the 19th century Cuban fishing ranchos on Florida’s Gulf coast were occupied year round and they formed deep connections with other cultural groups living in the state. This exhibit is about this legacy of trade and the fishermen who formed these unique communities. The exhibit features interpretive panels and artifacts.</p>
<p>Guest curator: <span class="curator">Jeff</span></p>
</div>
<div class="col-md-5 text-center">
<a href="images/ranchos_full.jpg" class="fancybox"><img src="images/ranchos.jpg" alt="Florida's Fishing Ranchos Flyer" class="img-responsive"></a>
</div>
</div>
</div>
</div>
</div><!-- /.page-content /.container -->
<?php include('_footer.php'); ?>
<file_sep><?php
$pageTitle = "Volunteer";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-tab">
<div class="text-center">
<div class="image center-block" style="max-width:400px;">
<img src="images/volunteer.jpg" alt="" class="img-responsive">
<p>Artifacts recovered as part of our Sifting for Technology educational program need to be documented. You can help!</p>
</div>
</div>
<p>Join the <strong>Crystal River State Parks</strong>, the <strong>Florida Public Archaeology Network</strong>, the <strong>Friends of Crystal River State Parks</strong>, and the <strong>Florida Coastal Offices</strong> to assist in the preservation of the natural and cultural resources of the region. FPAN needs volunteers to help with our artifact documentation program. </p>
<p>Volunteers will photograph artifacts and enter associated data into our artifact database. We are also currently recruiting volunteers for the docent program. We also have volunteer programs for Bright Futures students logging community service volunteer hours.</p>
<p>Please us at <a href="mailto:<EMAIL>"><EMAIL></a> if you are interested in volunteering!</p>
</div><!-- /.box-tab -->
<h2>Get Involved</h2>
<div class="box-tab">
<p>There are many Organizations you can join to pursue an interest in archaeology. Here are some of our favorites in the West Central region:</p>
<h3>Local Organizations</h3>
<ul>
<li><a target="_blank" href="http://www.fasweb.org/chapters/ancientones.htm">Florida Archaeological Society Chapter: Ancient Ones Archaeological Society of North Central Florida</a></li>
<li><a target="_blank" href="http://classics.ufl.edu/other-resources/aia/">Archaeology Institute of America Chapter: Gainesville Society of Archaeology Institute of America, University of Florida</a></li>
<li><a target="_blank" href="http://classics.ufl.edu/other-resources/aia/">The Gainesville Society of the Archaeological Institute of America</a> </li>
</ul>
<h3>State Organizations</h3>
<ul>
<li><a target="_blank" href="http://www.fasweb.org/">Florida Anthropological Society</a></li>
<li><a target="_blank" href="http://www.flamuseums.org/">Florida Association of Museums</a></li>
<li><a target="_blank" href="http://www.floridatrust.org/">Florida Trust</a></li>
</ul>
<h3>National & International Organizations</h3>
<ul>
<li><a target="_blank" href="http://www.saa.org/">Society for American Anthropology</a></li>
<li><a target="_blank" href="http://www.sha.org/">Society for Historical Archaeology</a></li>
<li><a target="_blank" href="http://www.southeasternarchaeology.org/">Southeastern Archaeological Conference</a></li>
<li><a target="_blank" href="http://www.interpnet.com/">National Association for Interpretation</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Programs";
include 'header.php';
?>
<!-- Main Middle -->
<script type="text/javascript">
showElement('projects_sub');
</script>
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Ongoing Programs</h1></th>
</tr>
<tr>
<td class="table_mid">
<h2 >Archaeology of Lincolnville: The Kelton Family Site</h2>
<p><strong>Exhibit on Display at the Excelsior Cultural Center</strong></p>
<p><strong>St. Augustine, Florida (Lincolnville)</strong></p>
<p><a href="documents/FINALLincolnvillePanels_000.pdf"><img src="images/KeltonSite.jpg" alt="img" width="348" height="229" border="0" /></a></p>
<p>You may know that archaeology happens in St. Augustine, but did you know that over 30 sites have been excavated in Lincolnville? FPAN is proud to partner with the City of St. Augustine and the <a href="http://www.excelsiorculturalcenter.com">Excelsior Cultural Center</a> in of the first interpretive displays on the findings from archaeological investigations on a turn of the century Lincolnville Household. Visit the Museum's website for directions, or view the panels from your computer at home. </p>
<p><a href="documents/FINALLincolnvillePanels.pdf"><strong>Lincolnville Panels</strong></a></p>
<p> </p>
<h2 align="left">St. Augustine Archaeology Association Meeting/Lecture </h2>
<p align="left">On the first Tuesday of each month the St. Augustine Archaeology Association holds their regular meeting. After the meeting, invited lecturers provide a talk on a current and relevant topic in archaeology. For upcoming meeting dates and speakers visit the <a href="http://saaa.shutterfly.com">SAAA website</a>. </p>
<p align="left"> </p>
<h2 align="left">Additional Programming</h2>
<p align="left">Still want more? Check out our <a href="http://storify.com/FPANNortheast"><strong>Storify</strong></a> and <a href="http://fpannortheast.tumblr.com/"><strong>Tumblr</strong></a> pages!</p>
<p>For more local archaeology news, sign up for our latest <a href="http://flpublicarchaeology.org/newsletter/northeast/user/subscribe.php"><strong>newsletter</strong></a>!</p>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
/**
*
* A plugin to generate a file download list.
* This download folder can be relative to your Zenphoto root (<i>foldername</i>) or external to it (<i>../foldername</i>).
* By default the <var>%UPLOAD_FOLDER%</var> folder is chosen so you can use the file manager to manage those files.
*
* You can also override that folder by using the <var>printdownloadList()</var> function parameters directly. Additionally
* you can set a downloadlink to a specific file directly as well using <code>printDownloadURL(<i>path-to-file</i>);<code>.
*
* The file names and the download path of the items are stored with the number of downloads in the database's plugin_storage table.
*
* The download link is something like:
* <var>www.yourdomain.com/download.php?file=<i>id number of the download</i></var>.
*
* So the actual download source is not public. The list itself is generated directly from the file system. However,
* files which no longer exist are
* kept in the database for statistical reasons until you clear them manually via the statistics utility.
*
* You will need to modify your theme to use this plugin. You can use the codeblock fields if your theme supports them or
* insert the function calls directly where you want the list to appear.
*
* To protect the download directory from direct linking you need to set up a proper <var>.htaccess</var> for this folder.
*
* The <var>printDownloadAlbumZipURL()</var> function will create a zipfile of the album <i>on the fly</i>.
* The source of the images may be the original
* images from the album and its subalbums or they may be the <i>sized</i> images from the cache. Use the latter if you want
* the images to be watermarked.
*
* The list has a CSS class <var>downloadList</var> attached.
*
* @author <NAME> (acrylian)
* @package plugins
* @subpackage misc
* @tags "file download", "download manager", download
*/
$plugin_is_filter = 800 | ADMIN_PLUGIN | THEME_PLUGIN;
$plugin_description = gettext("Plugin to generate file download lists.");
$plugin_author = "<NAME> (acrylian), <NAME> (sbillard)";
$option_interface = "downloadList";
zp_register_filter('admin_utilities_buttons', 'DownloadList::button');
/**
* Plugin option handling class
*
*/
class DownloadList {
function __construct() {
setOptionDefault('downloadList_directory', UPLOAD_FOLDER);
setOptionDefault('downloadList_showfilesize', 1);
setOptionDefault('downloadList_showdownloadcounter', 1);
setOptionDefault('downloadList_user', NULL);
setOptionDefault('downloadList_password', getOption('downloadList_pass'));
setOptionDefault('downloadList_hint', NULL);
setOptionDefault('downloadList_rights', NULL);
setOptionDefault('downloadList_zipFromCache', 0);
}
function getOptionsSupported() {
$options = array(gettext('Download directory') => array('key' => 'downloadList_directory', 'type' => OPTION_TYPE_TEXTBOX,
'order' => 2,
'desc' => gettext("This download folder can be relative to your Zenphoto installation (<em>foldername</em>) or external to it (<em>../foldername</em>)! You can override this setting by using the parameter of the printdownloadList() directly on calling.")),
gettext('Show filesize of download items') => array('key' => 'downloadList_showfilesize', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 3,
'desc' => ''),
gettext('Show download counter of download items') => array('key' => 'downloadList_showdownloadcounter', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 4,
'desc' => ''),
gettext('Files to exclude from the download list') => array('key' => 'downloadList_excludesuffixes', 'type' => OPTION_TYPE_TEXTBOX,
'order' => 5,
'desc' => gettext('A list of file suffixes to exclude. Separate with comma and omit the dot (e.g "jpg").')),
gettext('Zip source') => array('key' => 'downloadList_zipFromCache', 'type' => OPTION_TYPE_RADIO,
'order' => 6,
'buttons' => array(gettext('From album') => 0, gettext('From Cache') => 1),
'desc' => gettext('Make the album zip from the album folder or from the sized images in the cache.')),
gettext('User rights') => array('key' => 'downloadList_rights', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 1,
'desc' => gettext('Check if users are required to have <em>file</em> rights to download.'))
);
if (GALLERY_SECURITY == 'public') {
$options[gettext('credentials')] = array('key' => 'downloadList_credentials', 'type' => OPTION_TYPE_CUSTOM,
'order' => 0,
'desc' => gettext('Provide credentials to password protect downloads'));
}
return $options;
}
function handleOption($option, $currentValue) {
$user = getOption('downloadList_user');
$x = getOption('downloadList_password');
$hint = getOption('downloadList_hint');
?>
<input type="hidden" name="password_enabled_downloadList" id="password_enabled_downloadList" value="0" />
<p class="password_downloadListextrashow">
<a href="javascript:toggle_passwords('_downloadList',true);">
<?php echo gettext("Password:"); ?>
</a>
<?php
if (empty($x)) {
?>
<img src="<?php echo WEBPATH . '/' . ZENFOLDER; ?>/images/lock_open.png" alt="" class="icon-postiion-top8" />
<?php
} else {
$x = ' ';
?>
<a onclick="resetPass('_downloadList');" title="<?php echo gettext('clear password'); ?>"><img src="<?php echo WEBPATH . '/' . ZENFOLDER; ?>/images/lock.png" alt="" class="icon-postiion-top8" /></a>
<?php
}
?>
</p>
<div class="password_downloadListextrahide" style="display:none">
<a href="javascript:toggle_passwords('_downloadList',false);">
<?php echo gettext("Guest user:"); ?>
</a>
<br />
<input type="text" size="27" id="user_name_downloadList" name="user_downloadList"
onkeydown="passwordClear('_downloadList');"
value="<?php echo html_encode($user); ?>" />
<br />
<span id="strength_downloadList"><?php echo gettext("Password:"); ?></span>
<br />
<input type="password" size="27"
id="pass_downloadList" name="pass_downloadList"
onkeydown="passwordClear('_downloadList');"
onkeyup="passwordStrength('_downloadList');"
value="<?php echo $x; ?>" />
<label><input type="checkbox" name="disclose_password_downloadList" id="disclose_password_downloadList" onclick="passwordClear('_downloadList');
togglePassword('_downloadList');"><?php echo gettext('Show password'); ?></label>
<br />
<span class="password_field__downloadList">
<span id="match_downloadList"><?php echo gettext("(repeat)"); ?></span>
<br />
<input type="password" size="27"
id="pass_r_downloadList" name="pass_r_downloadList" disabled="disabled"
onkeydown="passwordClear('_downloadList');"
onkeyup="passwordMatch('_downloadList');"
value="<?php echo $x; ?>" />
<br />
</span>
<?php echo gettext("Password hint:"); ?>
<br />
<?php print_language_string_list($hint, 'hint_downloadList', false, NULL, 'hint_downloadList', 27); ?>
</div>
<?php
}
static function handleOptionSave($themename, $themealbum) {
$notify = processCredentials('downloadList', '_downloadList');
if ($notify == '?mismatch=user') {
return '&custom=' . gettext('You must supply a password for the DownloadList user');
} else if ($notify) {
return '&custom=' . gettext('Your DownloadList passwords were empty or did not match');
}
return false;
}
/**
* Updates the download count entry when processing a download. For internal use.
* @param string $path Path of the download item
* @param bool $nocountupdate false if the downloadcount should not be increased and only the entry be added to the db if it does not already exist
*/
static function updateListItemCount($path) {
$checkitem = query_single_row("SELECT `data` FROM " . prefix('plugin_storage') . " WHERE `aux` = " . db_quote($path) . " AND `type` = 'downloadList'");
if ($checkitem) {
$downloadcount = $checkitem['data'] + 1;
query("UPDATE " . prefix('plugin_storage') . " SET `data` = " . $downloadcount . ", `type` = 'downloadList' WHERE `aux` = " . db_quote($path) . " AND `type` = 'downloadList'");
}
}
/**
* Adds a new download item to the database. For internal use.
* @param string $path Path of the download item
*/
static function addListItem($path) {
$checkitem = query_single_row("SELECT `data` FROM " . prefix('plugin_storage') . " WHERE `aux` = " . db_quote($path) . " AND `type` = 'downloadList'");
if (!$checkitem) {
query("INSERT INTO " . prefix('plugin_storage') . " (`type`,`aux`,`data`) VALUES ('downloadList'," . db_quote($path) . ",'0')");
}
}
/* * Gets the download items from all download items from the database. For internal use in the downloadList functions.
* @return array
*/
static function getListItemsFromDB() {
$downloaditems = query_full_array("SELECT id, `aux`, `data` FROM " . prefix('plugin_storage') . " WHERE `type` = 'downloadList'");
return $downloaditems;
}
/* * Gets the download items from all download items from the database. For internal use in the downloadlink functions.
* @return array
*/
static function getListItemFromDB($file) {
$downloaditem = query_single_row($sql = "SELECT id, `aux`, `data` FROM " . prefix('plugin_storage') . " WHERE `type` = 'downloadList' AND `aux` = " . db_quote($file));
return $downloaditem;
}
/**
* Gets the id of a download item from the database for the download link. For internal use.
* @param string $path Path of the download item (without WEBPATH)
* @return bool|string
*/
static function getItemID($path) {
$downloaditem = query_single_row("SELECT id, `aux`, `data` FROM " . prefix('plugin_storage') . " WHERE `type` = 'downloadList' AND `aux` = " . db_quote($path));
if ($downloaditem) {
return $downloaditem['id'];
} else {
return false;
}
}
/**
* @param array $array List of download items
* @param string $listtype "ol" or "ul" for the type of HTML list you want to use
* @return array
*/
static function printListArray($array, $listtype = 'ol') {
if ($listtype != 'ol' || $listtype != 'ul') {
$listtype = 'ol';
}
$filesize = '';
foreach ($array as $key => $file) {
?>
<li>
<?php
if (is_array($file)) { // for sub directories
echo $key;
echo '<' . $listtype . '>';
self::printListArray($file, $listtype);
echo '</' . $listtype . '>';
} else {
printDownloadURL($file);
}
?>
</li>
<?php
}
}
/**
* Admin overview button for download statistics utility
*/
static function button($buttons) {
$buttons[] = array(
'category' => gettext('Info'),
'enable' => true,
'button_text' => gettext('Download statistics'),
'formname' => 'downloadstatistics_button',
'action' => WEBPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/downloadList/download_statistics.php',
'icon' => WEBPATH . '/' . ZENFOLDER . '/images/bar_graph.png',
'title' => gettext('Counts of downloads'),
'alt' => '',
'hidden' => '',
'rights' => ADMIN_RIGHTS,
);
return $buttons;
}
static function noFile() {
global $_downloadFile;
if (TEST_RELEASE) {
$file = $_downloadFile;
} else {
$file = basename($_downloadFile);
}
?>
<script type="text/javascript">
// <!-- <![CDATA[
window.onload = function() {
alert('<?php printf(gettext('File “%s” was not found.'), $file); ?>');
}
// ]]> -->
</script>
<?php
}
}
class AlbumZip {
/**
* generates an array of filenames to zip
* recurses into the albums subalbums
*
* @param object $album album object to add
* @param int $base the length of the base album name
*/
static function AddAlbum($album, $base, $filebase) {
global $_zp_zip_list, $zip_gallery;
$albumbase = substr($album->name, $base) . '/';
foreach ($album->sidecars as $suffix) {
$f = $albumbase . $album->name . '.' . $suffix;
if (file_exists(internalToFilesystem($f))) {
$_zp_zip_list[$filebase . $f] = $f;
}
}
$images = $album->getImages();
foreach ($images as $imagename) {
$image = newImage($album, $imagename);
$f = $albumbase . $image->filename;
$_zp_zip_list[$filebase . internalToFilesystem($f)] = $f;
$imagebase = stripSuffix($image->filename);
foreach ($image->sidecars as $suffix) {
$f = $albumbase . $imagebase . '.' . $suffix;
if (file_exists($f)) {
$_zp_zip_list[$filebase . $f] = $f;
}
}
}
$albums = $album->getAlbums();
foreach ($albums as $albumname) {
$subalbum = newAlbum($albumname);
if ($subalbum->exists && !$album->isDynamic()) {
self::AddAlbum($subalbum, $base, $filebase);
}
}
}
/**
* generates an array of cachefilenames to zip
* recurses into the albums subalbums
*
* @param object $album album object to add
* @param int $base the length of the base album name
*/
static function AddAlbumCache($album, $base, $filebase) {
global $_zp_zip_list, $zip_gallery, $defaultSize;
$albumbase = substr($album->name, $base) . '/';
$images = $album->getImages();
foreach ($images as $imagename) {
$image = newImage($album, $imagename);
$uri = $image->getSizedImage($defaultSize);
if (strpos($uri, 'i.php?') === false) {
$f = $albumbase . $image->filename;
$c = $albumbase . basename($uri);
$_zp_zip_list[$filebase . $c] = $f;
}
}
$albums = $album->getAlbums();
foreach ($albums as $albumname) {
$subalbum = newAlbum($albumname);
if ($subalbum->exists && !$album->isDynamic()) {
self::AddAlbumCache($subalbum, $base, $filebase);
}
}
}
/**
* Emits a page error. Used for attempts to bypass password protection
*
* @param string $err error code
* @param string $text error message
*
*/
static function pageError($err, $text) {
header("HTTP/1.0 " . $err . ' ' . $text);
header("Status: " . $err . ' ' . $text);
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head> <title>" . $err . " - " . $text . "</TITLE> <META NAME=\"ROBOTS\" CONTENT=\"NOINDEX, FOLLOW\"></head>";
echo "<BODY bgcolor=\"#ffffff\" text=\"#000000\" link=\"#0000ff\" vlink=\"#0000ff\" alink=\"#0000ff\">";
echo "<FONT face=\"Helvitica,Arial,Sans-serif\" size=\"2\">";
echo "<b>" . sprintf(gettext('Page error: %2$s (%1$s)'), $err, $text) . "</b><br /><br />";
echo "</body></html>";
exitZP();
}
/**
* Creates a zip file of the album
*
* @param string $albumname album folder
* @param bool fromcache if true, images will be the "sized" image in the cache file
*/
static function create($albumname, $fromcache) {
global $_zp_zip_list, $_zp_gallery, $defaultSize;
$album = newAlbum($albumname);
if (!$album->isMyItem(LIST_RIGHTS) && !checkAlbumPassword($albumname)) {
self::pageError(403, gettext("Forbidden"));
}
if (!$album->exists) {
self::pageError(404, gettext('Album not found'));
}
$_zp_zip_list = array();
if ($fromcache) {
$opt = array('large_file_size' => 5 * 1024 * 1024, 'comment' => sprintf(gettext('Created from cached images of %1$s on %2$s.'), $album->name, zpFormattedDate(DATE_FORMAT, time())));
loadLocalOptions(false, $_zp_gallery->getCurrentTheme());
$defaultSize = getOption('image_size');
self::AddAlbumCache($album, strlen($albumname), SERVERPATH . '/' . CACHEFOLDER . '/' . $albumname);
} else {
$opt = array('large_file_size' => 5 * 1024 * 1024, 'comment' => sprintf(gettext('Created from images in %1$s on %2$s.'), $album->name, zpFormattedDate(DATE_FORMAT, time())));
self::AddAlbum($album, strlen($albumname), SERVERPATH . '/' . ALBUMFOLDER . '/' . $albumname);
}
$zip = new ZipStream($albumname . '.zip', $opt);
foreach ($_zp_zip_list as $path => $file) {
@set_time_limit(6000);
$zip->add_file_from_path(internalToFilesystem($file), internalToFilesystem($path));
}
$zip->finish();
}
}
/**
* Prints the actual download list included all subfolders and files
* @param string $dir An optional different folder to generate the list that overrides the folder set on the option.
* @param string $listtype "ol" or "ul" for the type of HTML list you want to use
* @param array $filters an array of files to exclude from the list. Standard items are Array( '.', '..','.DS_Store','Thumbs.db','.htaccess','.svn')
* @param array $excludesuffixes an array of file suffixes (without trailing dot to exclude from the list (e.g. "jpg")
* @param string $sort 'asc" or "desc" (default) for alphabetical ascending or descending list
*/
function printdownloadList($dir = '', $listtype = 'ol', $filters = array(), $excludesuffixes = '', $sort = 'desc') {
if ($listtype != 'ol' || $listtype != 'ul') {
$listtype = 'ol';
}
$files = getdownloadList($dir, $filters, $excludesuffixes, $sort);
echo '<' . $listtype . ' class="downloadList">';
DownloadList::printListArray($files, $listtype);
echo '</' . $listtype . '>';
}
/**
* Gets the actual download list included all subfolders and files
* @param string $dir8 An optional different folder to generate the list that overrides the folder set on the option.
* This could be a subfolder of the main download folder set on the plugin's options. You have to include the base directory as like this:
* "folder" or "folder/subfolder" or "../folder"
* You can also set any folder within or without the root of your Zenphoto installation as a download folder with this directly
* @param string $listtype "ol" or "ul" for the type of HTML list you want to use
* @param array $filters8 an array of files to exclude from the list. Standard items are '.', '..','.DS_Store','Thumbs.db','.htaccess','.svn'
* @param array $excludesuffixes an array of file suffixes (without trailing dot to exclude from the list (e.g. "jpg")
* @param string $sort 'asc" or "desc" (default) for alphabetical ascending or descending list
* @return array
*/
function getdownloadList($dir8, $filters8, $excludesuffixes, $sort) {
$filters = Array('Thumbs.db');
foreach ($filters8 as $key => $file) {
$filters[$key] = internalToFilesystem($file);
}
if (empty($dir8)) {
$dir = SERVERPATH . '/' . getOption('downloadList_directory');
} else {
if (substr($dir8, 0, 1) == '/' || strpos($dir8, ':') !== false) {
$dir = internalToFilesystem($dir8);
} else {
$dir = SERVERPATH . '/' . internalToFilesystem($dir8);
}
}
if (empty($excludesuffixes)) {
$excludesuffixes = getOption('downloadList_excludesuffixes');
}
if (empty($excludesuffixes)) {
$excludesuffixes = array();
} elseif (!is_array($excludesuffixes)) {
$excludesuffixes = explode(',', $excludesuffixes);
}
if ($sort == 'asc') {
$direction = 0;
} else {
$direction = 1;
}
$dirs = array_diff(scandir($dir, $direction), $filters);
$dir_array = Array();
if ($sort == 'asc') {
natsort($dirs);
}
foreach ($dirs as $file) {
if (@$file{0} != '.') { // exclude "hidden" files
if (is_dir(internalToFilesystem($dir) . '/' . $file)) {
$dirN = filesystemToInternal($dir) . "/" . filesystemToInternal($file);
$dir_array[$file] = getdownloadList($dirN, $filters8, $excludesuffixes, $sort);
} else {
if (!in_array(getSuffix($file), $excludesuffixes)) {
$dir_array[$file] = $dir . '/' . filesystemToInternal($file);
}
}
}
}
return $dir_array;
}
/**
* Gets the download url for a file
* @param string $file the path to a file to get a download link.
*/
function getDownloadURL($file) {
if (substr($file, 0, 1) != '/' && strpos($file, ':') === false) {
$file = SERVERPATH . '/' . getOption('downloadList_directory') . '/' . $file;
}
$request = parse_url(getRequestURI());
if (isset($request['query'])) {
$query = parse_query($request['query']);
} else {
$query = array();
}
DownloadList::addListItem($file); // add item to db if not already exists without updating the counter
$link = '';
if ($id = DownloadList::getItemID($file)) {
$query['download'] = $id;
$link = FULLWEBPATH . '/' . preg_replace('~^' . WEBPATH . '/~', '', $request['path']) . '?' . http_build_query($query);
}
return $link;
}
/**
* Prints a download link for a file, depending on the plugin options including the downloadcount and filesize
* @param string $file the path to a file to print a download link.
* @param string $linktext Optionally how you wish to call the link. Set/leave to NULL to use the filename.
*/
function printDownloadURL($file, $linktext = NULL) {
if (substr($file, 0, 1) != '/' && strpos($file, ':') === false) {
$file = SERVERPATH . '/' . getOption('downloadList_directory') . '/' . $file;
}
$filesize = '';
if (getOption('downloadList_showfilesize')) {
$filesize = @filesize(internalToFilesystem($file));
$filesize = ' (' . byteConvert($filesize) . ')';
}
if (getOption('downloadList_showdownloadcounter')) {
$downloaditem = DownloadList::getListItemFromDB($file);
if ($downloaditem) {
$downloadcount = ' - ' . sprintf(ngettext('%u download', '%u downloads', $downloaditem['data']), $downloaditem['data']);
} else {
$downloadcount = ' - 0 downloads';
}
$filesize .= $downloadcount;
}
if (empty($linktext)) {
$filename = basename($file);
} else {
$filename = $linktext;
}
echo '<a href="' . html_encode(getDownloadURL($file)) . '" rel="nofollow">' . html_encode($filename) . '</a><small>' . $filesize . '</small>';
}
/**
*
* Prints a download link for an album zip of the current album (therefore to be used only on album.php/image.php).
* This function only creates a download count and then redirects to the original Zenphoto album zip download.
*
* @param string $linktext
* @param object $albumobj
* @param bool $fromcache if true get the images from the cache
*/
function printDownloadAlbumZipURL($linktext = NULL, $albumobj = NULL, $fromcache = NULL) {
global $_zp_current_album;
$request = parse_url(getRequestURI());
if (isset($request['query'])) {
$query = parse_query($request['query']);
} else {
$query = array();
}
if (is_null($albumobj)) {
$albumobj = $_zp_current_album;
}
if (!is_null($albumobj) && !$albumobj->isDynamic()) {
$file = $albumobj->name . '.zip';
DownloadList::addListItem($file);
if (getOption('downloadList_showdownloadcounter')) {
$downloaditem = DownloadList::getListItemFromDB($file);
if ($downloaditem) {
$downloadcount = ' - ' . sprintf(ngettext('%u download', '%u downloads', $downloaditem['data']), $downloaditem['data']);
} else {
$downloadcount = ' - 0 downloads';
}
$filesize = '<small>' . $downloadcount . '</small>';
} else {
$filesize = '';
}
if (!empty($linktext)) {
$file = $linktext;
}
$query['download'] = pathurlencode($albumobj->name);
$query['albumzip'] = 'true';
if ($fromcache) {
$query['fromcache'] = 'true';
}
$link = FULLWEBPATH . '/' . preg_replace('~^' . WEBPATH . '/~', '', $request['path']) . '?' . http_build_query($query);
echo '<a href="' . html_encode($link) . '" rel="nofollow">' . html_encode($file) . '</a>' . $filesize;
}
}
/**
* Process any download requests
*/
if (isset($_GET['download'])) {
$item = sanitize($_GET['download']);
if (empty($item) || !extensionEnabled('downloadList')) {
if (TEST_RELEASE) {
zp_error(gettext('Forbidden'));
} else {
header("HTTP/1.0 403 " . gettext("Forbidden"));
header("Status: 403 " . gettext("Forbidden"));
exitZP(); // terminate the script with no output
}
}
$hash = getOption('downloadList_password');
if (GALLERY_SECURITY != 'public' || $hash) {
// credentials required to download
if (!zp_loggedin((getOption('downloadList_rights')) ? FILES_RIGHTS : ALL_RIGHTS)) {
$user = getOption('downloadList_user');
zp_handle_password('download_auth', $hash, $user);
if (!empty($hash) && zp_getCookie('download_auth') != $hash) {
$show = ($user) ? true : NULL;
$hint = get_language_string(getOption('downloadList_hint'));
printPasswordForm($hint, true, $show, '?download=' . $item);
exitZP();
}
}
}
if (isset($_GET['albumzip'])) {
DownloadList::updateListItemCount($item . '.zip');
require_once(SERVERPATH . '/' . ZENFOLDER . '/lib-zipStream.php');
if (isset($_GET['fromcache'])) {
$fromcache = sanitize($isset($_GET['fromcache']));
} else {
$fromcache = getOption('downloadList_zipFromCache');
}
AlbumZip::create($item, $fromcache);
exitZP();
} else {
require_once(SERVERPATH . '/' . ZENFOLDER . '/lib-MimeTypes.php');
$item = (int) $item;
$path = query_single_row("SELECT `aux` FROM " . prefix('plugin_storage') . " WHERE id=" . $item);
$_downloadFile = internalToFilesystem($path['aux']);
if (file_exists($_downloadFile)) {
DownloadList::updateListItemCount($_downloadFile);
$ext = getSuffix($_downloadFile);
$mimetype = getMimeString($ext);
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimetype);
header('Content-Disposition: attachment; filename=' . basename(urldecode($_downloadFile)));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($_downloadFile));
flush();
readfile($_downloadFile);
exitZP();
} else {
zp_register_filter('theme_body_open', 'DownloadList::noFile');
}
}
}
?><file_sep><?php
$pageTitle = "Training Workshops";
include('../_header.php');
?>
<!-- page-content begins -->
<div class="container">
<div class="page-header">
<h1>Workshops</h1>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="box-dash">
<p>
The Florida Public Archaeology Network offers training programs, workshops, and informational presentations on a variety of topics.
</p>
<p>
Whether you need:
<ul>
<li>training for professional certification</li>
<li>to maintain CEUs</li>
<li>a new way to get your organization involved in your local heritage</li>
<li>to learn about archaeological resources for your job or volunteer position</li>
</ul>
... we can help out!
</p>
<p>
Some of our programs are free of charge, while others have a small registration fee to help cover the cost of materials and activities. Click on the links below to learn more about FPAN's Training Programs.
</p>
<p>
If you don't see the program you're interested in scheduled in your area, <a href="/staff.php#regionStaff">contact your local FPAN office</a> and request it! All FPAN Regions can offer these programs, but usually need 5-10 people (depending on the program) to make a class.
</p>
</div>
</div>
<div class="col-sm-6">
<div class="box-tab">
<h3 class="text-center">Heritage Awareness Diving Seminar (HADS)</h3>
<img src="images/hads_thumb.png" class="img-responsive img-circle center-block" width="175" height="176" alt="HADS Logo" />
<p>The Heritage Awareness Diving Seminar provides scuba training agency Course Directors, Instructor Trainers, and Instructors with information and skills to proactively protect shipwrecks, artificial reefs, and other underwater cultural sites as part of the marine environment. Participants will be prepared to teach the new Heritage Awareness Diving Specialty through NAUI, PADI, and SDI.
<br/>
<em>*Taught in partnership with the Florida Bureau of Archaeological Research.</em></p>
<a href="HADS.php" class="btn btn-primary center-block">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Submerged Sites Education and Archaeological Stewardship (SSEAS)</h3>
<img src="images/sseas_thumb.jpg" class="img-responsive img-circle center-block" width="175" height="172" alt="SSEAS diver"/>
<p>This program is intended to train sport divers in the methods of non-disturbance archaeological recording and then give these trained divers a mission!</p>
<a href="SSEAS.php" class="btn btn-primary center-block">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Cemetery Resource Protection Training (CRPT)</h3>
<img src="images/crpt.svg" class="img-responsive center-block" width="175" height="175" alt="CRPT, cemetery headstone" />
<p>Join Florida Public Archaeology Network staff to learn about protecting human burial sites and preserving historic cemeteries.</p>
<a href="CRPT.php" class="btn btn-primary center-block">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Historical & Archaeological Resources Training (HART)</h3>
<img src="images/hart_thumb.jpg" class="img-responsive img-circle center-block" width="175" height="175" alt="HART resources" />
<p>Designed for county and municipal governmental administrators, land managers, and planners, this one-day seminar describes how best to manage historical and archaeological resources and methods for promoting these resources for the benefit of their communities.<br/>
<em>*Taught in partnership with the Florida Bureau of Archaeological Research.</em></p>
<a href="HART.php" class="btn btn-primary center-block">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Park Ranger Workshop</h3>
<img src="images/rangerWorkshop_thumb.jpg" class="img-responsive img-circle center-block" width="175" height="175" alt="Park Rangers" />
<p>This one-day training is designed to assist rangers and park personnel in the identification, protection, interpretation, and effective management of historical and archaeological resources.</p>
<a href="parkRanger.php" class="btn btn-primary center-block">Learn More</a>
</div>
</div><!-- /.col-->
<div class="col-sm-6">
<div class="box-tab">
<h3 class="text-center">Archaeology in the Classroom:<br/> <small>Teacher In-Service Workshop</small></h3>
<img src="images/inservice_thumb.jpg" class="img-responsive img-circle center-block" width="175" height="175" alt="Teach In-Service"/>
<p>Use the lure of the past to engage students in math, science, language arts, fine arts, and critical thinking!</p>
<a href="teacherInService.php" class="btn btn-primary center-block">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Project Archaeology: <small>Investigating Shelter</small></h3>
<img src="images/projectArchaeology.jpg" class="img-responsive center-block" width="350" height="142" alt="Project Archaeology" />
<p>This is a supplementary science and social studies curriculum unit for grades 3 through 5. This workshop aims to familiarize educators with archaeology resources for the classroom that enhance learning opportunities in math, science, art, and social studies. Workshop participants will receive archaeology education guides published by Project Archaeology that take students through scientific processes and an archaeological investigation of Kingsley Plantation, including accounts from oral history, use of primary documents, and interpreting the archaeological record.</p>
<a href="projectArchaeology.php" class="btn btn-primary center-block">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Human Remains and the Law</h3>
<img src="images/humanRemains_thumb.jpg" class="img-responsive img-circle center-block" width="175" height="175" alt="Human Remains" />
<p>Geared toward land mangers, this half-day workshop focuses on Florida and US laws regulating the discovery of human remains and the management of Native American remains within museum collections.</p>
<a href="humanRemains.php" class="btn btn-primary center-block">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Forest Resources Environmental Policy Special Sites Workshop</h3>
<img src="images/forestry_thumb.jpg" class="img-responsive img-circle center-block" width="175" height="175" alt="Forest Resources" />
<p>This one-day workshop helps forestry professionals to identify, manage, and protect "special sites" such as historical and archaeological resources they are likely to encounter in the course of their work, including Native American sites, cemeteries, industrial sites, and sites submerged in rivers and streams.</p>
<a href="forestResources.php" class="btn btn-primary center-block">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Archaeology Works</h3>
<img src="images/archworks_thumb.jpg" class="img-responsive img-circle center-block" width="175" height="175" alt="Archaeology works" />
<p>These hands-on workshops focus on different archaeological subjects but are designed for people of all ages.</p>
<a href="archworks.php" class="btn btn-primary center-block">Learn More</a>
</div>
</div><!-- /.col-->
</div><!-- /.row -->
</div><!-- /.page-content /.container -->
<?php include('../_footer.php'); ?>
<file_sep><?php
$pageTitle = "About Us - FAQ";
include('../_header.php');
?>
<!-- page-content begins -->
<div class="container-fluid">
<!-- Row Two -->
<div class="row">
<div class="page-header">
<h1>About Us, <small>FAQ</small></h1>
</div>
<div class="col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<div class="box box-line box-tab">
<ol class="faq">
<li><strong class="color">What is FPAN and how is it funded?</strong>
<p> The Florida Public Archaeology Network, FPAN, is a statewide network with regional centers dedicated to public outreach and assisting local governments and the Florida Division of Historical Resources, in order to promote the stewardship and protection of Florida’s archaeological resources. Through creating and developing partnerships, FPAN strives to engage many publics with Florida’s rich archaeological history. FPAN does not conduct large-scale field research projects nor is FPAN a CRM company. FPAN was created during the 2004 legislative session as part of the Florida Historical Resources Act and is funded through the Florida Legislature. </p>
</li>
<li><strong class="color">How can I volunteer with FPAN?</strong>
<p>There are many volunteer opportunities through FPAN. Depending on the season, opportunities include, but are not limited to, assisting with public events, giving introductory archaeology lectures to school-age children, helping with archaeology field trips, and participating in lab work. In addition to volunteering with FPAN, we can also identify other volunteer opportunities with partner organizations. Please contact the regional center in your area for details. </p>
</li>
<li><strong class="color">Do you appraise artifacts?</strong>
<p>Archaeologists do not appraise artifacts. Artifacts are nonrenewable resources that provide a window into understanding past cultures and life ways. The information and knowledge that can be gained about our past is priceless. <br />
</p>
</li>
<li><strong class="color">I have been told that I need to hire an archaeologist before I can get a permit. Can I hire FPAN to do this work?</strong>
<p>FPAN does not do archaeological contract work. Contact a Cultural Resource Management firm to ask about hiring an archaeologist for permit compliance. <br />
</p>
</li>
<li><strong class="color">Why can’t you answer my question about dinosaur fossils?</strong>
<p>The field of archaeology is concerned with learning about past peoples and cultures by examining the things that have been left behind. Archaeology is a subfield of Anthropology. As anthropologists, we study humankind. We do not study dinosaurs, fossils, or rocks and minerals. Please contact a paleontologist for questions about dinosaurs and other fossils, or a geologist for questions about rocks and minerals. <br />
<br />
The Florida Museum of Natural History's Division of Vertebrate Paleontology offers a <a href="http://www.flmnh.ufl.edu/vertpaleo/fos_id_svc.htm" target="_blank"> Fossil Identification Service website</a> for more information.</p>
</li>
<li><strong class="color">Can you come talk to my class?</strong>
<p>Although FPAN archaeologists do occasionally visit classrooms, it is not possible for us to fulfill every request. In order to more effectively serve all schools in our regions, FPAN focuses on teaching educators how to bring archaeology into the classroom through offering workshops and trainings, sharing resources, and providing guidance for presentations and activities. </p>
</li>
<li><strong class="color">I have an archaeological site on my property that I would like to know more about. Can you help me?</strong>
<p>Although FPAN does not perform large-scale excavations, we can help you find out more about your site and, most importantly, help you find ways to best protect it. Contact your regional center for assistance. </p>
</li>
<li><strong class="color">What can FPAN do for local governments?</strong> <br />
<br />
<ul>
<li>Assisting with identifying possible grants and funding sources for archaeological education and preservation</li>
<li>Guidance with Certified Local Governments</li>
<li>Archaeological resource training for government employees</li>
<li>Listing sites in the Florida Master Site File and the National Register of Historic Places</li>
<li>Navigating the state review and compliance process</li>
</ul>
<br/>
</li>
<li><strong class="color">What can FPAN do for teachers?</strong> <br />
<br />
<ul>
<li>Teacher Trainings
<ul type="disc">
<li>Teacher In-Services</li>
<li><a href="http://www.projectarchaeology.org" target="_blank">Project Archaeology Curriculum Training</a></li>
</ul>
</li>
</ul>
<br />
<ul>
<li><a href="/resources">Archaeology Resources</a>
<ul type="disc">
<li>Assistance from professional terrestrial and maritime archaeologists</li>
<li><em>Beyond Artifacts: Teaching Archaeology in the Classroom</em>, multi-volume teacher tool kit<br />
<br /></li>
</ul>
</li>
</ul>
</li>
<li><strong class="color">What can FPAN do for organizations, societies, scouts, museums, etc. ?</strong>
<p>FPAN is dedicated to assisting and partnering with a variety of entities in order to educate the public and instill stewardship of the past. Below are a few examples:</p>
<ul>
<li>Giving and facilitating lecture series</li>
<li>Boy Scout Merit Badge and Girl Scout Activity Badge Clinics</li>
<li>Supporting heritage tourism</li>
<li>Providing professional guidance and advice</li>
<li>Promoting archaeological events<br />
<br/></li>
</ul>
</li>
<li><strong class="color">If I find an artifact, can I keep it?</strong>
<p>On State or Federal lands, it is not lawful to collect or remove artifacts. The Isolated Finds Policy in Florida has been discontinued and does not allow individuals to keep artifacts discovered in Florida’s rivers. If you do find an artifact, the best thing to do is leave it in place, record the approximate location on a map, take a photo with a well-known object (like a coin) as a scale, and contact your regional FPAN office which can help you properly report the find.<br />
</p>
</li>
<li><strong class="color">Can I metal detect in Florida?</strong>
<p>Laws regarding metal detecting in Florida are rather confusing —we always encourage anyone interested in metal detecting to always get the permission of the land owner or manager before detecting - that will prevent misunderstandings about what is permitted, trespassing, etc. Most cities and counties have their own ordinances regarding metal detecting - the City Manager, County Commission, or the Parks/Recreation Department can probably tell you. Most coastal cities and counties in Florida do allow metal detecting on their beaches, although some, like St. Johns County, have ordinances that prohibit the removal of historical objects from county lands. They’re all a little different, so that’s why we suggest contacting them directly. </p>
<p>Detecting on state lands is different and the removal of historical objects from state lands is prohibited. Some coastal state parks do not allow metal detecting at all, some will allow it between the shoreward toe of the dunes and the mean high water line, but only for modern objects. Some state parks will only allow detecting for personal items that are specified as lost in a particular area. If counties or cities lease coastal lands from the state, they are required to abide by state laws. Every state park will have an entry station with a ranger on duty, so always ask first. <br />
</p>
<p>As for metal detecting in the water, all lands that are below the mean high water line are considered state sovereignty submerged lands and, while it is not against the law to possess a metal detector in the water, it IS against the law to disturb the bottom sediments. So, if something is detected, it would be illegal to dig for it.</p> </li>
</ol>
</div>
</div>
</div><!-- /.row -->
</div><!-- /.page-content /.container-fluid -->
<?php include('../_footer.php'); ?>
<file_sep><nav class="navbar navbar-main" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Large branding logo image -->
<?php echoImageBranding(); ?>
<!-- Small text-only branding -->
<a class="navbar-brand visible-xs" href="/index.php"> FPAN <?php if(isset($table)) echo getRegionName($table); ?> </a>
</div> <!-- /.navbar-header -->
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav">
<?php echoBrandingSpacer(); ?>
<!-- Regions menu shown only to xs screens -->
<li class="dropdown visible-xs">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Region Sites <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="/nwrc">Northwest</a></li>
<li><a href="/ncrc">North Central</a></li>
<li><a href="/nerc">Northeast</a></li>
<li><a href="/ecrc">East Central</a></li>
<li><a href="/crc">Central</a></li>
<li><a href="/wcrc">West Central</a></li>
<li><a href="/swrc">Southwest</a></li>
<li><a href="/serc">Southeast</a></li>
</ul>
</li><!-- /xsmall region menu -->
<!-- Main Nav items -->
<li class="<?=activeClassIfMatches('regions')?>"><a href="/regions.php">Regions</a></li>
<li class="dropdown <?=activeClassIfMatches('resources')?>">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Resources <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="/resources">Lesson Plans</a></li>
<li><a href="/iphone/">iPhone Apps</a></li>
<li><a href="/resources/videos.php">Videos</a></li>
<li><a href="/resources/links.php">Links</a></li>
</ul>
<li class="<?=activeClassIfMatches('workshops')?>"><a href="/workshops">Workshops</a></li>
<li class="<?=activeClassIfMatches('documents')?>"><a href="/documents">Documents</a></li>
<li class="dropdown <?=activeClassIfMatches('staff')?> <?=activeClassIfMatches('board')?>">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">People <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="/staff.php">Staff</a></li>
<li><a href="/board.php">Board</a></li>
</ul>
</li>
<li class="dropdown <?=activeClassIfMatches('about')?>">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">About Us <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="/about">Overview</a></li>
<li><a href="/about/FAQ.php">FAQ</a></li>
<li><a href="/about/opportunities.php">Opportunities</a></li>
</ul>
</li>
</ul><!-- /.nav /.navbar-nav -->
</div><!-- /.navbar-collapse -->
</nav><!-- /.navbar-main -->
<nav class="navbar navbar-region hidden-xs" role="navigation">
<div class="container-fluid">
<ul class="nav navbar-nav hidden-sm hidden-xs">
<?php echoBrandingSpacer(); ?>
<li class="<?=activeClassIfMatches('/nwrc')?>"><a href="/nwrc">Northwest</a></li>
<li class="<?=activeClassIfMatches('/ncrc')?>"><a href="/ncrc">North Central</a></li>
<li class="<?=activeClassIfMatches('/nerc')?>"><a href="/nerc">Northeast</a></li>
<li class="<?=activeClassIfMatches('/ecrc')?>"><a href="/ecrc">East Central</a></li>
<li class="<?=activeClassIfMatches('/crc')?>"><a href="/crc">Central</a></li>
<li class="<?=activeClassIfMatches('/wcrc')?>"><a href="/wcrc">West Central</a></li>
<li class="<?=activeClassIfMatches('/swrc')?>"><a href="/swrc">Southwest</a></li>
<li class="<?=activeClassIfMatches('/serc')?>"><a href="/serc">Southeast</a></li>
</ul>
<!-- Condense region menu to dropdown for smaller screens -->
<ul class="nav navbar-nav visible-sm pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Regions <b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="<?=activeClassIfMatches('/nwrc')?>"><a href="/nwrc">Northwest</a></li>
<li class="<?=activeClassIfMatches('/ncrc')?>"><a href="/ncrc">North Central</a></li>
<li class="<?=activeClassIfMatches('/nerc')?>"><a href="/nerc">Northeast</a></li>
<li class="<?=activeClassIfMatches('/ecrc')?>"><a href="/ecrc">East Central</a></li>
<li class="<?=activeClassIfMatches('/crc')?>"><a href="/crc">Central</a></li>
<li class="<?=activeClassIfMatches('/wcrc')?>"><a href="/wcrc">West Central</a></li>
<li class="<?=activeClassIfMatches('/swrc')?>"><a href="/swrc">Southwest</a></li>
<li class="<?=activeClassIfMatches('/serc')?>"><a href="/serc">Southeast</a></li>
</ul>
</li>
</ul>
</div><!-- /.container-fluid -->
</nav> <!-- /.navbar-region --><file_sep><?php
include 'dbConnect.php';
$upcomingEvents = mysql_query("SELECT * FROM nwrc
WHERE nwrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM nerc
WHERE nerc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM ncrc
WHERE ncrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM wcrc
WHERE wcrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM crc
WHERE crc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM ecrc
WHERE ecrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM serc
WHERE serc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM swrc
WHERE swrc.eventDateTimeStart >= CURDATE()
ORDER BY 3;");
?>
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Upcoming Events</h1></th>
</tr>
<tr>
<td>
<?php
if(mysql_num_rows($upcomingEvents) != 0){
$numEvents = 10;
$style = "";
while(($event = mysql_fetch_array($upcomingEvents)) && ($numEvents > 0)){
//Get proper region names
switch($event['region']){
case "nwrc":
$regionImage = "images/nw_event.png";
break;
case "ncrc":
$regionImage = "images/nc_event.png";
break;
case "nerc":
$regionImage = "images/ne_event.png";
break;
case "crc":
$regionImage = "images/c_event.png";
break;
case "wcrc":
$regionImage = "images/wc_event.png";
break;
case "ecrc":
$regionImage = "images/ec_event.png";
break;
case "serc":
$regionImage = "images/se_event.png";
break;
case "swrc":
$regionImage = "images/sw_event.png";
break;
default:
break;
}
$timestampStart = strtotime($event['eventDateTimeStart']);
$eventDate = date('M, j', $timestampStart);
$linkDate = date('m/d/Y', $timestampStart);
$eventTimeStart = date('g:i a', $timestampStart);
echo "<p class=\"small\"><strong class=\"small\">".$eventDate." @ "."".$eventTimeStart."</strong>in the<br/>";
echo "<img src=\"". $regionImage. "\" style=\"padding-top:4px;\" alt=\"FPAN Event\"/><br/>";
echo "<a href=\"".$event['region']."/eventDetail.php?eventID=$event[eventID]&eventDate=$linkDate\"><em>" . stripslashes($event['title']) . "</em></a></p>";
$numEvents--;
}
}
else
echo '<p style="font-size:12px;" align="center">No events currently scheduled. <br/> Check back soon!</p>';
?>
</td>
</tr>
</table>
<file_sep><?php
include 'appHeader.php';
$msg = $_GET['msg'];
$err = $_GET['err'];
if($delete){
$delete = mysql_real_escape_string($_GET['delete']);
if(unlink($uploadDirectory.$delete))
$msg = $delete . " was deleted successfully.";
else
$msg = "Unable to delete " . $delete;
}
if ($handle = opendir($uploadDirectory)) {
while (false !== ($file = readdir($handle))){
if ($file != "." && $file != ".."){
$thelist .= '<tr><td>'.$file.'</td><td align="right"><a href="'.$rootDirectory.$region."/".$file.'" target="_blank">View</a> /
<a href="?delete='.$file.'" onclick="return confirm(\'Are you sure you want to delete this file?\');">Delete</a>
</td></tr>';
}
}
closedir($handle);
}
$pageTitle = "File Upload";
include $header;
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>File Upload</h1></th>
</tr>
<tr>
<td class="table_mid">
<p align="center">
<form enctype="multipart/form-data" action="processUpload.php" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<!-- Name of input element determines name in $_FILES array -->
<p align="center">
<label for="file">Choose file:</label> <input name="userfile" type="file" id="file" /><br/><br />
<input type="submit" value="Upload" />
</p>
</form>
<hr />
<?php
if($err)
$color = "red";
if($msg)
echo "<p align=\"center\" style=\"color:$color;\" class=\"msg\"> $msg </p>";
?>
<table width="100%" cellpadding="5" style="margin-left:auto; margin-right:auto; padding-left:15px; padding-right:15px;">
<tr>
<th colspan="2">Contents of /uploads/<?php echo $region ?></th>
</tr>
<?=$thelist?>
</table>
</p>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
<br/>
</div>
<div id="sm_tables">
<?php include 'adminBox.php'; ?><br/>
<?php include '../events/calendar.php'; ?>
</div>
</div>
<!-- End Main div -->
<div class="clearFloat"></div>
<?php include $footer; ?><file_sep><?php
if(isset($_GET['video'])){
$video = $_GET['video'];
switch($video){
//Other Videos
case "ArchaeologyCafe":
$pageTitle = "Archaeology Cafe - Archaeology of the Taco";
$youtube = "";
break;
case "Flinknapping":
$pageTitle = "The Ancient Art of Flintknapping";
$youtube = "";
break;
//Virtual Florida Fieldtrips
case "XimenezFatio":
$pageTitle = "Virtual Florida Fieldtrips - Ximenez-Fatio Museum";
$youtube = "0/E3pkNWbfUHs";
break;
case "SugarMills":
$pageTitle = "Virtual Florida Fieldtrips - Florida's Sugar Mills";
$youtube = "1/_Ioy3xYd4QQ";
break;
case "Smyrnea":
$pageTitle = "Virtual Florida Fieldtrips - Smyrnea Settlement";
$youtube = "2/IXNnuDtoT3k";
break;
case "NombreDeDios":
$pageTitle = "Virtual Florida Fieldtrips - Nombre De Dios";
$youtube = "3/WAkfGUeKzkM";
break;
case "MalaCompra":
$pageTitle = "Virtual Florida Fieldtrips - Mala Compra";
$youtube = "0/6I30RTVUIvc";
break;
case "KingsleyPlantation":
$pageTitle = "Virtual Florida Fieldtrips - Kingsley Plantation";
$youtube = "4/vov4Bscn5pw";
break;
case "CastilloDeSanMarcos":
$pageTitle = "Virtual Florida Fieldtrips - Castillo De San Marcos";
$youtube = "5/N696SqWvptA";
break;
//Southeast Region Videos
case "ArchaeologyDayLecturesAnneKolb":
$pageTitle = "Archaeology Day Lectures - Anne Kolb";
$youtube = "1/VQcfhmTQAGI";
break;
case "ArchCreekParkTalkWalk":
$pageTitle = "Arch Creek Park - Talk & Walk";
$youtube = "0/dqKg2JYUVZ4";
break;
case "BonnetHouseMuseumGardens":
$pageTitle = "Exploring Archaeology at Bonnet House Museum & Gardens";
$youtube = "2/zo6L5DOgK2g";
break;
case "BrowardCountyHistoricalCommissionGrandOpening":
$pageTitle = "Broward County Historical Commission Grand Opening";
$youtube = "3/4VBpVadCRw4";
break;
case "DiningOut2000YearsAgoLecture":
$pageTitle = "Dining Out 2000 Years Ago";
$youtube = "4/0mWG5Rpn_Zk";
break;
case "IndianMoundPark":
$pageTitle = "Exploring Archaeology at Indian Mound Park";
$youtube = "5/i-pCEn6RYl4";
break;
case "SnakeWarriorIsland":
$pageTitle = "Exploring Archaeology at Snake Warrior's Island";
$youtube = "6/polEqYDN7xQ";
break;
case "StranahanHouse":
$pageTitle = "Exploring Archaeology at Stranahan House ";
$youtube = "7/ChZv-3TPmM4";
break;
case "TechniqueGPR":
$pageTitle = "Exploring Archaeological Techniques - GPR";
$youtube = "8/-EIGhrtuq4Q";
break;
case "TechniqueWetScreening":
$pageTitle = "Exploring Archaeological Techniques - Wet Screening";
$youtube = "9/nbJqbqvaSTI";
break;
case "destinationArchaeologyTour":
$pageTitle = "Destination Archaeology Tour";
$youtube = "";
break;
default:
break;
}
$flashvars = "file=http://www.flpublicarchaeology.org/resources/videos/$video.flv&screencolor=000000";
}else{
$pageTitle = "Video Resources";
}
include('../_header.php');
?>
<!-- page-content begins -->
<div class="container">
<div class="row">
<div class="page-header">
<h1>Resources, <small> Videos </small></h1>
</div>
<?php if(isset($video)){ ?>
<h2><?php echo $pageTitle ?></h2>
<div class="col-sm-12">
<div class="box-tab">
<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='665' height='450' id='single1' name='single1' class="center-block">
<param name='movie' value='player.swf'>
<param name='allowfullscreen' value='true'>
<param name='allowscriptaccess' value='always'>
<param name='wmode' value='transparent'>
<?php echo "<param name='flashvars' value='$flashvars'>" ?>
<embed
type='application/x-shockwave-flash'
id='single2'
name='single2'
src='player.swf'
width='665'
height='450'
bgcolor='000000'
allowscriptaccess='always'
allowfullscreen='true'
wmode='transparent'
<?php echo "flashvars='$flashvars'" ?>
/>
</object>
<div class="text-center">
<?php if($youtube)echo "Watch on <a href=\"http://www.youtube.com/user/FloridaArchaeology#p/u/$youtube\">YouTube</a>" ?> <br />
<?php echo "Download: <a href=\"videos/$video.wmv\">PC</a> | <a href=\"videos/$video.mov\"> Mac<br />" ?>
</a> (Right click -> Save link/target as...)
</div>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
<?php } ?>
<div class="row">
<div class="col-sm-6">
<h3>Northeast Region</h3>
<div class="box-tab">
<ul>
<li><a href="http://www.youtube.com/watch?v=kjqfG6FE5G4" target="_blank">Flagler Follies: The Archaeologist </a></li>
<li><a href="http://www.youtube.com/watch?v=xVJ89_6NXAk" target="_blank">GPR in St. Augustine Historic Cemeteries</a></li>
<li><a href="http://www.youtube.com/watch?v=lD-Ota0A7yM" target="_blank">In A Well With Carl</a></li>
<li><a href="http://www.youtube.com/watch?v=GD0Xu-VPNOw" target="_blank">Fort San Carlos Day on Amelia Island</a></li>
<li><a href="http://www.youtube.com/watch?v=NAQm5F9GLzY" target="_blank">A Walk Back In Time</a></li>
<li><a href="http://www.youtube.com/watch?v=MS08QwFPhpo" target="_blank">St. Augustine Lighthouse Festival</a></li>
</ul>
<h4 id="vff">Virtual Florida Field Trips</h4>
<ul>
<li><a href="videos.php?video=MalaCompra">Mala Compra </a> </li>
<li><a href="videos.php?video=Smyrnea">The Smyrnea Settlement</a></li>
<li><a href="videos.php?video=SugarMills">Sugar Mills</a></li>
<li><a href="videos.php?video=CastilloDeSanMarcos">Castillo De San Marcos</a></li>
<li><a href="videos.php?video=KingsleyPlantation">Kingsley Plantation</a></li>
<li><a href="videos.php?video=XimenezFatio">Ximenez-Fatio House </a></li>
<li><a href="videos.php?video=NombreDeDios">Nombre De Dios</a><br></li>
</ul>
</div>
<h3>Northwest Region</h3>
<div class="box-tab">
<ul>
<li><a href="http://www.youtube.com/watch?v=sdke1d8jIfk" target="_blank">Museums in the Sea: Florida's Underwater Archaeological Preserves</a></li>
<li><a href="http://fpan.us/resources/videos.php?video=AtlAtlTurkey" target="_blank">GoPro Atl-atl Hunting</a></li> <li><a href="http://www.youtube.com/watch?v=Ww8dBSLFKLQ" target="_blank">Apalachicola River Boiler Project </a></li>
<li><a href="http://fpan.us/resources/videos.php?video=ArchaeologyCafe" target="_blank">Archaeology Cafe - Archaeology of the Taco with Dr. Ramie</a></li>
</ul>
<h4>Archaeology in 3 Minutes</h4>
<ul>
<li><a href="https://www.youtube.com/watch?v=_tro0dX8gf0&list=UUQj8Epd8p21inIlEe9msMtg" target="_blank">Caves</a></li>
<li><a href="https://www.youtube.com/watch?v=OUJUUNzin5s&list=UUQj8Epd8p21inIlEe9msMtg" target="_blank">3D Printing</a></li>
<li><a href="https://www.youtube.com/watch?v=exIygak7fhc&list=UUQj8Epd8p21inIlEe9msMtg" target="_blank">3D Laser Scanning</a></li>
<li><a href="https://www.youtube.com/watch?v=cFACQfQIOUo&list=UUQj8Epd8p21inIlEe9msMtg" target="_blank">Underwater Gear</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h3>Central Region</h3>
<div class="box-tab">
<ul>
<li><a href="http://www.youtube.com/watch?v=iroz_feHUAk" target="_blank">BC Buddies Dive Club</a></li>
<li><a href="http://www.youtube.com/watch?v=3Ryco-R4yPo" target="_blank">Artifacts from Civil War Blockade Runner</a></li>
</ul>
</div>
<h3>Southeast Region</h3>
<div class="box-tab">
<ul>
<li><a href="videos.php?video=StranahanHouse">Stranahan House</a> </li>
<li><a href="videos.php?video=SnakeWarriorIsland">Snake Warrior's Island </a> </li>
<li><a href="videos.php?video=ArchaeologyDayLecturesAnneKolb">Archaeology Day Lectures - Anne Kolb </a> </li>
<li><a href="videos.php?video=BrowardCountyHistoricalCommissionGrandOpening">Broward County Historical </a> </li>
<li><a href="videos.php?video=BonnetHouseMuseumGardens">Bonnet House Museum & Gardens </a> </li>
<li><a href="videos.php?video=DiningOut2000YearsAgoLecture">“Dining Out 2,000 Years Ago” - Lecture </a> </li>
<li><a href="videos.php?video=ArchCreekParkTalkWalk">Arch Creek Park “Talk & Walk ” </a> </li>
<li><a href="videos.php?video=IndianMoundPark">Indian Mound Park</a> </li>
</ul>
</div>
<h3>Other Videos</h3>
<div class="box-tab">
<ul>
<li><a href="videos.php?video=Flintknapping">The Ancient Art of Flintknapping</a></li>
<li><a href="http://www.youtube.com/watch?v=xh5TI6teUbg" target="_blank">What is archaeology? - Carl Halbirt Interview </a></li>
<li><a href="http://www.youtube.com/watch?v=oAuigHwJSOs" target="_blank">What is Maritime Archaeology? - Chuck Meide Interview</a></li>
<li><a href="videos.php?video=TechniqueGPR">Archaeological Techniques: Ground Penetrating Radar</a></li>
<li><a href="videos.php?video=TechniqueWetScreening">Archaeological Techniques: Wet Screening </a></li>
<li><a href="http://www.youtube.com/watch?v=v9ZBHAEjoEQ" target="_blank">Journey of an Artifact</a></li>
</ul>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content /.container -->
<?php include('../_footer.php'); ?>
<file_sep><?php
include('header.php');
?>
<table>
<tr>
<td>
<button id="toggle_nwrc"> Show/Hide NWRC </button>
<div class="nwrc">
Northwest
</div>
</td>
<td>
<button id="toggle_ncrc"> Show/Hide NCRC</button>
<div class="ncrc">
North Central
</div>
</td>
<td>
<button id="toggle_nerc"> Show/Hide NERC</button>
<div class="nerc">
Northeast
</div>
</td>
<td>
<button id="toggle_crc"> Show/Hide CRC</button>
<div class="crc">
Central
</div>
</td>
</tr>
<tr>
<td>
<button id="toggle_wcrc"> Show/Hide WCRC </button>
<div class="wcrc">
West Central
</div>
</td>
<td>
<button id="toggle_ecrc"> Show/Hide ECRC</button>
<div class="ecrc">
East Central
</div>
</td>
<td>
<button id="toggle_swrc"> Show/Hide SWRC</button>
<div class="swrc">
Southwest
</div>
</td>
<td>
<button id="toggle_serc"> Show/Hide SERC</button>
<div class="serc">
Southeast
</div>
</td>
</tr>
</table>
</div>
</body>
</html><file_sep><?php
$link = @mysql_connect('fpanweb.powwebmysql.com', 'fpan_dbuser', '$ESZ5rdx');
if (!$link) {
$link = mysql_connect('localhost', 'fpan_dbuser', '$ESZ5rdx') ;
}else{
mysql_error();
}
// Select Database
mysql_select_db(fpan_civilwar);
$civilWarSites = mysql_query("SELECT *
FROM zp_albums;");
@date_default_timezone_set("GMT");
$xml = new XMLWriter();
$xml->openURI('php://output');
$xml->openMemory();
$xml->startDocument('1.0','UTF-8');
$xml->setIndent(4);
//Start Root element
$xml->startElement('allSites');
if(mysql_num_rows($civilWarSites) != 0 )
while($site = mysql_fetch_array($civilWarSites))
{
//Start Event Element
$xml->startElement('site');
$xml->writeElement('id', $site['id']);
$xml->writeElement('parentid', /*$site['parentid']*/ "1");
$xml->writeElement('folder', $site['folder']);
$xml->writeElement('title', $site['title']);
$xml->writeElement('desc', $site['desc']);
$xml->writeElement('thumb', $site['thumb']);
$xml->endElement();
}
//End Root Element
$xml->endElement();
$xml->endDocument();
echo $xml->outputMemory();
?><file_sep><?php include 'header.php' ?>
<table width="600" border="0" cellspacing="2" align="center">
<tr>
<td valign="top" style="width:300px;">
<h3 align="center">FPAN Activity / Event</h3>
<ul>
<li><a href="publicOutreach.php?new=true">Public Outreach</a></li>
<li><a href="trainingWorkshops.php?new=true">Training / Workshops</a></li>
<li><a href="governmentAssistance.php?new=true">Government Assistance</a></li>
<li><a href="meeting.php?new=true">Meeting</a></li>
<li><a href="socialMedia.php?new=true">Social Media</a></li>
<li><a href="pressContact.php?new=true">Press Contact</a></li>
<li><a href="publication.php?new=true">Publication</a></li>
<li><a href="directMail.php?new=true">Direct Mail / Newsletter</a></li>
</ul>
<p> </p></td>
<td valign="top" style="width:300px;">
<h3 align="center">Professional Service and Development</h3>
<ul>
<li><a href="serviceToProfessionalSociety.php?new=true">Service to Professional Society</a></li>
<li><a href="serviceToHostInstitution.php?new=true">Service to Host Institution</a></li>
<li><a href="serviceToCommunity.php?new=true">Service to Community</a></li>
<li><a href="trainingCertificationEducation.php?new=true">Training / Certification / Education</a></li>
<li><a href="conferenceAttendanceParticipation.php?new=true">Conference Attendance / Participation</a></li>
</ul>
</td>
</tr>
</table>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><!-- CSS element hide/show function -->
function showElement(layer){
var myLayer = document.getElementById(layer);
if(myLayer.style.display=="block")
myLayer.style.display="none";
else{
myLayer.style.display="block";
myLayer.backgroundPosition="top";
}
}
<!-- Image Swap Functions -->
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
<!-- Regioni Info Swap Functions -->
function replace(section)
{
var regionInfo = "";
var counties = "";
var image = "";
var title = "";
switch(section)
{
case "nwrc":
photos = 5;
title = "Northwest Region";
counties = "Escambia, Santa Rosa, Okaloosa, Walton, Holmes, Washington, Bay, Jackson, Calhoun, Gulf";
image = section + "_" + Math.ceil(Math.random()*photos) + ".jpg";
visit = "<h3><a href=\"http://www.flpublicarchaeology.org/nwrc\">Visit this region </a></h3>";
break;
case "ncrc":
photos = 3;
title = "North Central Region";
counties = "Gadsden, Liberty, Franklin, Leon, Wakulla, Jefferson, Madison, Taylor, Hamilton, Suwannee, Lafayette, Dixie, Columbia, Baker, Union";
image = section + "_" + Math.ceil(Math.random()*photos) + ".jpg";
visit = "<h3><a href=\"http://www.flpublicarchaeology.org/ncrc\">Visit this region </a></h3>";
break;
case "nerc":
photos = 4;
title = "Northeast Region";
counties = "Nassau, Duval, Clay, St. Johns, Putnam, Flagler, Volusia";
image = section + "_" + Math.ceil(Math.random()*photos) + ".jpg";
visit = "<h3><a href=\"http://www.flpublicarchaeology.org/nerc\">Visit this region </a></h3>";
break;
case "crc":
photos = 10;
title = "Central Region";
counties = "Gilchrist, Levy, Bradford, Alachua, Marion, Citrus, Hernando, Sumter, Lake";
image = section + "_" + Math.ceil(Math.random()*photos) + ".jpg";
visit = "<h3><a href=\"http://www.flpublicarchaeology.org/crc\">Visit this region </a></h3>";
break;
case "wcrc":
photos = 6;
title = "West Central Region";
counties = "Pasco, Pinellas, Hillsborough, Polk, Manatee, Sarasota, Hardee, Desoto, Highlands";
image = section + "_" + Math.ceil(Math.random()*photos) + ".jpg";
visit = "<h3><a href=\"http://www.flpublicarchaeology.org/wcrc\">Visit this region </a></h3>";
break;
case "ecrc":
photos = 1;
title = "East Central Region";
counties = "Seminole, Orange, Osceola, Brevard, Indian River, Okeechobee, St. Lucie, Martin";
image = section + "_" + Math.ceil(Math.random()*photos) + ".jpg";
visit = "<h3><a href=\"http://www.flpublicarchaeology.org/ecrc\">Visit this region </a></h3>";
break;
case "swrc":
photos = 10;
title = "Southwest Region";
counties = "Charlotte, Glades, Lee, Hendry, Collier";
image = section + "_" + Math.ceil(Math.random()*photos) + ".jpg";
visit = "<h3><a href=\"http://www.flpublicarchaeology.org/swrc\">Visit this region </a></h3>";
break;
case "serc":
photos = 1;
title = "Southeast Region";
counties = "Palm Beach, Broward, <NAME>, Monroe";
image = section + "_" + Math.ceil(Math.random()*photos) + ".jpg";
visit = "<h3><a href=\"http://www.flpublicarchaeology.org/serc\">Visit this region </a></h3>";
break;
default:
title = "Invalid Regional Code";
counties = "Not a list.";
image = "";
break;
}
// change content
regionInfo = "<h2 style=\"padding: 0;\">" + title + "</h2>\n\n";
regionInfo += "<p style=\"font-size: 80%; margin: 0 0 5px 0; padding: 0;\">" + counties + "</p>\n";
//content += "<p style=\"font-size: 80%; margin: 0 0 5px 0; padding: 0;\">" + visit + "</p>\n";
//content += "<p><image src=\"http://www.flpublicarchaeology.org/images/hovers/" + image + "\" /></p>\n";
document.getElementById('regionInfo').innerHTML = regionInfo;
}
function reset()
{
var content = "<p><em>\"...to promote and facilitate the conservation, study, and public understanding of Florida's archaeological heritage through regional centers.\"</em></p>\n";
content += "<h2>Explore Florida's Archaeology</h2>\n";
content += "<p>You can encounter archaeology in every region of Florida! Click on one of the map regions ... find one of our regional public archaeology centers . . . learn about archaeological sites, museums, and events . . . see how you can volunteer to help us conserve, study, and spread the word about Florida's buried heritage!</p>\n";
content += "<p>Our regional archaeologists are ready to answer your questions and help you encounter Florida archaeology.</p>\n";
document.getElementById("content").innerHTML = content;
}<file_sep><?php
//Determine which page days link to based on whether using admin interface
if($calPage == "")
$calPage = "eventDetail.php";
//This gets today's date
$date = time();
$day = date('d', $date);
//If month is defined in URL, use that
/*
if($_GET['month'])
$month = mysql_real_escape_string($_GET['month']);
else
$month = date('m', $date);
*/
$month = "03";
//If year is defined in URL, use that
if($_GET['year'])
$year = mysql_real_escape_string($_GET['year']);
else
$year = date('Y', $date);
//Generate the first day of the month
$first_day = mktime(0,0,0,$month, 1, $year) ;
//Get the month name
$title = date('F', $first_day) ;
//Find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;
//Once we know what day of the week it falls on, we know how many blank days occure before it. If the first day of the week is a Sunday then it would be zero
switch($day_of_week){
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}
//Determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year);
$sql = "SELECT * FROM $table
WHERE eventDateTimeStart
LIKE '$year-$month-%'
AND isApproved = 1";
$findEvents = mysql_query($sql);
$eventDays = array();
while($event = mysql_fetch_array($findEvents)){
$timestampDate = strtotime($event['eventDateTimeStart']);
$eventDate = date('Y-m-d', $timestampDate);
array_push($eventDays, $eventDate);
}
//Define calendar navigation variables
if($month < 12){
$nextMonth = $month+1;
if($nextMonth < 10)
$nextMonth = "0".$nextMonth;
$next = "month=$nextMonth&year=$year";
}
else{
$nextYear = $year+1;
$next = "month=1&year=$nextYear";
}
if($month > 1){
$prevMonth = $month-1;
if($prevMonth < 10)
$prevMonth = "0".$prevMonth;
$prev = "month=$prevMonth&year=$year";
}
else{
$prevYear = $year-1;
$prev = "month=12&year=$prevYear";
}
if($_GET['eventDate']){
$eventDate = mysql_real_escape_string($_GET['eventDate']);
$next .= "&eventDate=".$eventDate;
$prev .= "&eventDate=".$eventDate;
}
if($_GET['eventID']){
$eventID = mysql_real_escape_string($_GET['eventID']);
$next .= "&eventID=$eventID";
$prev .= "&eventID=$eventID";
}
if($_GET['pagenum']){
$eventID = mysql_real_escape_string($_GET['pagenum']);
$next .= "&pagenum=$pagenum";
$prev .= "&pagenum=$pagenum";
}
?>
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th class="sm_header">
<table width="100%">
<tr>
<td>
<?php echo "<h2>" .$title. " " .$year."</h2>" ?>
</td>
</tr>
</table>
</th>
</tr>
<tr>
<td class="sm_mid" colspan="3">
<table class="cal">
<tr class="cal_head">
<td class="cal_day">S</td>
<td class="cal_day">M</td>
<td class="cal_day">T</td>
<td class="cal_day">W</td>
<td class="cal_day">R</td>
<td class="cal_day">F</td>
<td class="cal_day">S</td>
</tr>
<?php
//This counts the days in the week, up to 7
$day_count = 1;
echo "<tr>";
//first we take care of those blank days
while ( $blank > 0 ) {
echo "<td ></td>";
$blank = $blank-1;
$day_count++;
}
//sets the first day of the month to 1
$day_num = 1;
//count up the days, untill we've done all of them in the month
while ( $day_num <= $days_in_month ){
//Add leading zeros for eventDate if needed
if($day_num < 10)
$eventDate = "$year-$month-0$day_num";
else
$eventDate = "$year-$month-$day_num";
//If this day has events, link to listing of events
if(in_array($eventDate, $eventDays))
echo "<td class=\"cal_day\" id=\"hasEvent\"><a href=\"$calPage?eventDate=$eventDate&month=$month&year=$year\">$day_num</a></td>";
else
echo "<td class=\"cal_day\"> $day_num </td>";
$day_num++;
$day_count++;
//Make sure we start a new row every week
if ($day_count > 7){
echo "</tr><tr>";
$day_count = 1;
}
}
//Finaly we finish out the table with some blank details if needed
while ( $day_count >1 && $day_count <=7 ){
echo "<td> </td>";
$day_count++;
}
?>
</tr></table>
</td>
</tr>
<tr>
<td class="sm_bottom"></td>
</tr>
</table>
<file_sep><?php
// Zenphoto theme definition file
$theme_description["name"] = "FPAN";
$theme_description["author"] = "admin";
$theme_description["version"] = "1.0";
$theme_description["date"] = "07/22/2010";
$theme_description["desc"] = "FPAN NW Theme Default";
?><file_sep><?php
$pageTitle = "Explore";
$county = isset($_GET['county']) ? $_GET['county'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<!-- ********* ****************** ************* -->
<!-- ********* Explore Desoto County ********** -->
<!-- ********* ****************** ************* -->
<?php if($county == 'desoto'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Desoto<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/desoto.jpg" alt="" width="600" height="444" class="img-responsive">
<p>Archaeologists and volunteers work to find evidence of the historic town of Pine Level in DeSoto County.</p>
</div>
</div>
<p>DeSoto County was founded in 1887 after it was split from Manatee County and initially encompassed present-day Charlotte, Glades, Hardee, and Highlands counties. Within DeSoto County’s borders today lie the Arcadia Historical District which encompasses 293 historic buildings as well as other remnants of DeSoto County’s varied past.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://desotobocc.com/">DeSoto County</a></li>
</ul>
</div>
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.nationalregisterofhistoricplaces.com/FL/De+Soto/state.html">Arcadia Historical District</a></li>
<li><a target="_blank" href="http://historicparkerhouse.com/">Historic Parker House</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.historicdesoto.org/">DeSoto County Historical Society</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** **************** -->
<!-- ********* Explore Hardee County ************* -->
<!-- ********* ****************** **************** -->
<?php }elseif($county == 'hardee'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Hardee<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/hardee.jpg" alt="" class="img-responsive" width="600" height="402">
<p>Suspension Bridge at the Paynes Creek Historic State Park</p>
</div>
</div>
<p>Hardee County was established in 1921 and named for Florida’s 23rd governor, <NAME>. In Hardee County there are opportunities to visit great sites that represent the great heritage of this area such as the Alafia River Rendezvous, the Southeast’s largest pre-1840 interpretive encampment. Hardee County is also home to Paynes Creek Historic State Park where you gain knowledge of the history of this interior Florida region and are guided through a unique set of marked trails designed to introduce visitors to a variety of ecosystems as well as stroll through an interpretive museum which helps transport visitors to the 1840’s.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.hardeecounty.net/">Hardee County</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridafrontiersmen.org/Alafia.html">Alafia River Rendezvous</a></li>
<li><a target="_blank" href="http://www.floridafrontiersmen.org/">Florida Frontiersmen</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.hardeecounty.net/crackertrailmuseum/index.html">Cracker Trail Museum and Pioneer Village</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/paynescreek/">Paynes Creek Historic State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** ******************* -->
<!-- ********* Explore Highlands County ************* -->
<!-- ********* ****************** ******************* -->
<?php }elseif($county == 'highlands'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Highlands<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/highlands.jpg" alt="" class="img-responsive" width="600" height="400" >
<p>Archaeology mural in downtown Lake Placid</p>
</div>
</div>
<p>Highlands County was established in 1921 when it was separated from DeSoto County. Within Highlands County’s borders lie informative locales such as the South Florida Community College Museum of Florida Art and Culture that features several permanent exhibits as well as ever-changing traveling exhibits for visitors to enjoy.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.hcbcc.net/departments/development_services/planning/index.php">Highlands County</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://mofac.org/">South Florida Community College Museum of Florida Art and Culture</a></li>
<li><a target="_blank" href="http://www.childrensmuseumhighlands.com/">Children’s Museum of the Highlands</a></li>
<li><a target="_blank" href="http://www.avonparkhistoricalsociety.com/">The Depot Museum of Avon Park</a></li>
<li><a target="_blank" href="http://www.visithighlandscounty.com/destinations/lake-placid-historical-society-depot-museum">Lake Placid Historical Society Depot Museum</a></li>
<li><a target="_blank" href="http://www.visithighlandscounty.com/destinations/civilian-conservation-corps-museum">Civilian Conservation Corps Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://floridastateparks.org/highlandshammock/default.cfm">Highlands Hammock State Park</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="https://www.facebook.com/KVAHC">Kissimmee Valley Archaeological and Historical Conservancy</a></li>
<li><a target="_blank" href="http://www.sebringhistoricalsociety.org/">Sebring Historical Society</a></li>
</ul>
</div>
<h2>Historical Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.lpfla.com/murals.htm">Lake Placid Historical Murals</a></li>
<li><a target="_blank" href="http://www.destinationdowntownsebring.com/Murals_in_Downtown.html">Sebring Historical Murals</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Hillsborough County ****************** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'hillsborough'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Hillsborough<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/hillsborough.jpg" alt="" class="img-responsive" width="600" height="382">
<p>Fort Foster State Historic Park</p>
</div>
</div>
<p>Hillsborough County offers the ability to see sites such as Fort Foster (built 1836-1837) where you can visit a replica wood picket Seminole War fort that stands on the original site. Hillsborough is also home to the Tampa Bay History Center. </p>
</div>
</div>
<div class="col-md-6">
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.americanvictory.org/">American Victory Mariners Memorial & Museum Ship</a></li>
<li><a target="_blank" href="http://www.tampabayhistorycenter.org/">Tampa Bay History Center</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/Yborcity/">Ybor City Museum State Park</a> </li>
<li><a target="_blank" href="http://plantmuseum.com/">Henry B. Plant Museum</a> </li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/egmontkey/">Egmont Key State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/fortfoster/default.cfm">Fort Foster State Historic Park</a></li>
<li><a target="_blank" href="http://www.hillsboroughcounty.org/Facilities/Facility/Details/Upper-Tampa-Bay-Regional-Park-7945">Upper Tampa Bay Park</a></li>
<li><a target="_blank" href="http://apps.tampagov.net/parks_search_webapp/ParkDetail.aspx?nbr=156">Cotanchobee Fort Brooke Park</a> </li>
<li><a target="_blank" href="http://www.floridastateparks.org/HILLsBOROUgHRIVER/default.cfm">Hillsborough River State Park</a> </li>
</ul>
</div>
<h2>Historical Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.tampagov.net/parks-and-recreation/programs/info/cemeteries/oaklawn-walking-tour">Oaklawn Cemetery</a> </li>
<li><a target="_blank" href="http://www.yborcityonline.com/">Ybor City Historic District</a> </li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.hillsboroughcounty.org/">Hillsborough County</a></li>
<li><a target="_blank" href="http://www.tampagov.net/historic-preservation">City of Tampa</a> </li>
<li><a target="_blank" href="http://www.plantcitygov.com/index.aspx?nid=118&PREVIEW=YES">City of Plant City</a> </li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://tampapreservation.com/">Tampa Preservation Inc.</a> </li>
<li><a target="_blank" href="https://www.facebook.com/pages/East-Hillsborough-Historical-Society/301331157803">East Hillsborough Historical Society</a> </li>
<li><a target="_blank" href="https://www.facebook.com/tampahistoricalsociety">Tampa Historical Society Inc.</a></li>
</ul>
</div>
<h2>Shipwrecks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.flaquarium.org/conservation-research/scientific-dive-program/civil-war-shipwrecks/friends-of-narcissus.aspx">Narcissus</a> </li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** ***************** -->
<!-- ********* Explore Manatee County ************* -->
<!-- ********* ****************** ***************** -->
<?php }elseif($county == 'manatee'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Manatee<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/manatee.jpg" alt="" class="img-responsive" width="600" height="436">
<p>Main mound at Emerson Point</p>
</div>
</div>
<p>Manatee County's rich heritage centers around the Manatee River. Evidence that prehistoric inhabitants depended on the Manatee River can be seen in the burial, midden and temple mounds located along the river's banks. By the 16th century, the Spaniards had arrived and were among the first Europeans to explore the Manatee River. In 1819, the United States government began a program to encourage the settlement of Florida. Enticed by the offer of free land, pioneers began arriving in the Manatee River region in 1842. Despite many problems, by 1855 enough settlers lived in the area to justify the establishment of a new county. At its creation, Manatee County consisted of 5,000 square miles and extended from the Gulf of Mexico to Lake Okeechobee.</p>
<p class="text-center"><a target="_blank" href="documents/ManateeMap_Final.pdf" class="btn btn-primary">Download our Explore Manatee map here!</a></p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.mymanatee.org/home/government/departments/building-and-development-services/planning-zoning/comprehensive-planning-section/historic-preservation.html">Manatee County</a> </li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.manateeclerk.com/historical/MaritimeMuseum.aspx">Florida Maritime Museum</a></li>
<li><a target="_blank" href="http://www.manateeclerk.com/historical/AgMuseum.aspx">Manatee County Agricultural Museum</a> </li>
<li><a target="_blank" href="http://www.southfloridamuseum.org/">South Florida Museum</a></li>
<li><a target="_blank" href="http://familyheritagehousemuseum.com/">Family Heritage House Museum</a></li>
<li><a target="_blank" href="http://www.frrm.org/">Florida Gulf Coast Railroad Museum</a></li>
<li><a target="_blank" href="http://www.annamariaisland-longboatkey.com/crosley-estate">Seagate, the Powel Crosley Estate</a></li>
<li><a target="_blank" href="http://www.amihs.org/">Anna Maria Island Historical Society</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.mymanatee.org/home/government/departments/natural-resources/resource-management/emerson-point.html">Emerson Point Preserve</a></li>
<li><a target="_blank" href="http://www.mymanatee.org/home/government/departments/natural-resources/resource-management/robinson-preserve.html">Robinson Preserve</a></li>
<li><a target="_blank" href="http://www.nps.gov/deso/">DeSoto National Memorial</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/MadiraBickelMound">Madira Bickel Mounds</a></li>
<li><a target="_blank" href="http://www.mymanatee.org/home/government/departments/natural-resources/resource-management/rye-wilderness.html">Rye Preserve</a></li>
<li><a target="_blank" href="http://www.mymanatee.org/home/government/departments/parks-and-recreation/natural-resources/preserves/neal-preserve.html">Neal Preserve</a> </li>
</ul>
</div>
<h2>Shipwrecks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.museumsinthesea.com/regina/index.htm">Regina</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/gambleplantation/default.cfm">Gamble Plantation Historic Park</a></li>
<li><a target="_blank" href="http://www.manateeclerk.com/historical/PalmettoPark.aspx">Palmetto Historical Park</a></li>
<li><a target="_blank" href="http://www.manateeclerk.com/historical/ManateeVillage.aspx">Manatee Village Historical Park</a></li>
<li><a target="_blank" href="http://www.manateeclerk.com/historical/palmettopark.aspx">Palmetto Historical Park</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.cortez-fish.org/">F.I.S.H. (The Florida Institute for Saltwater Heritage)</a></li>
<li><a target="_blank" href="http://cortezvillage.org/default.aspx">Cortez Village Historical Society</a></li>
<li><a target="_blank" href="http://www.manateecountyhistoricalsociety.org/">Manatee County Historical Society</a></li>
<li><a target="_blank" href="http://oldbradenriver.org/">Old Braden River Historical Society</a></li>
<li><a target="_blank" href="http://www.reflectionsofmanatee.com/">Reflections of Manatee</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Pasco County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'pasco'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Pasco<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/pasco.jpg" alt="" class="img-responsive" width="600" height="458">
<p><NAME></p>
</div>
</div>
<p>There are a variety of stops that you can make when looking for sites that demonstrate Pasco County’s heritage. One such stop would be at <NAME> which was purchased by <NAME> in 1925 and has been preserved. While in the Pasco area you can visit also the Pioneer Florida Museum and Village which provides interesting insight into the lives of Florida’s pioneers.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://pascocountyfl.net/">Pasco County</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.pioneerfloridamuseum.org/index.php">Pioneer Florida Museum and Village</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.lostworlds.org/oelsner_mound.html">Oelsner Mound</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://westpascohistoricalsociety.org/baker_house.html">The Baker House</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://westpascohistoricalsociety.org/">West Pasco Historical Society</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Pinellas County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'pinellas'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Pinellas<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/pinellas.jpg" alt="" class="img-responsive" width="600" height="460">
<p>Kids learn about Pinellas County’s prehistoric past at the Weedon Island Preserve.</p>
</div>
</div>
<p>Pinellas County is home to a variety of interesting locations that convey the county’s rich heritage. In addition to its geographic location directly along the Gulf of Mexico, Pinellas contains the Weedon Island Preserve which promotes an array of educational opportunities as well as housing an excellent museum.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.pinellascounty.org/historic/">Pinellas County</a></li>
<li><a target="_blank" href="http://www.stpete.org/historic_preservation/">City of St Petersburg</a> </li>
<li><a target="_blank" href="http://www.ctsfl.us/DevelopmentServices/HistoricPreservation.html">City of Tarpon Springs</a> </li>
<li><a target="_blank" href="http://www.townofbelleair.com/index.aspx?NID=103">Town of Belleair</a> </li>
<li><a target="_blank" href="http://mygulfport.us/">City of Gulfport</a> </li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.cityofsafetyharbor.com/index.aspx?nid=573">Safety Harbor Museum of Regional History</a></li>
<li><a target="_blank" href="http://tarponarts.org/tarpon-springs-information/our-venues/heritage-museum/">Tarpon Springs Heritage Museum</a> </li>
<li><a target="_blank" href="http://palmharbormuseum.com/">Palm Harbor Museum</a> </li>
<li><a target="_blank" href="http://dunedinmuseum.org/">Dunedin Historical Museum</a> </li>
<li><a target="_blank" href="http://www.pinellascounty.org/Heritage/">Heritage Village</a> </li>
<li><a target="_blank" href="http://spmoh.com/">St. Petersburg Museum of History</a> </li>
<li><a target="_blank" href="http://www.gulfbeachesmuseum.com/">Gulf Beaches Historical Museum</a> </li>
<li><a target="_blank" href="http://www.weedoislandpreserve.org/ed-center.htm">Weedon Island Cultural and Natural History Center </a></li>
</ul>
<p>The goal of Weedon Island Preserve is to effectively coordinate the management of the site’s ecological and cultural resources using methods that promote public education and encourage compatible recreational activities. In other words, show the public just how hot it was when the Weedons and their predecessors lived out there on the sandy, mangrove-laden shorelines of Tampa Bay! This is a first-class site for recreation and education. Learn about native Florida, the changes it has seen, and how we can relive prehistoric and historic times through active and salient scientific investigation. A must visit!</p>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.pinellascounty.org/park/11_Philippe.htm">Philippe Park/Safety Harbor Site</a></li>
<li><a target="_blank" href="http://www.stpeteparksrec.org/maximo-park.html">Maximo Park</a> </li>
<li><a target="_blank" href="http://www.exploresouthernhistory.com/pinellaspoint.html">Pinellas Point Mound</a> </li>
<li><a target="_blank" href="http://www.stpeteparksrec.org/abercrombie-park.html">Abercrombie Park</a> </li>
<li><a target="_blank" href="http://www.stpeteparksrec.org/jungle-prada.html">Jungle Prada Mound Park </a></li>
<li><a target="_blank" href="http://www.pinellascounty.org/park/05_ft_desoto.htm">Fort De Soto Park</a> </li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.spongedocks.net/">Tarpon Springs Sponge Docks</a> </li>
<li><a target="_blank" href="http://www.stpete.org/historic_preservation/african_american_heritage_project/index.asp">African American Heritage Trail</a> </li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<li><a target="_blank" href="http://cgcas.org/">Central Gulf Coast Archaeological Society</a> </li>
<li><a target="_blank" href="http://www.stpetepreservation.org/">St Pete Preservation</a> </li>
<li><a target="_blank" href="http://awiare.org/">Alliance for Weedon Island Archaeological Research and Education</a> </li>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Polk County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'polk'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Polk<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/polk.jpg" alt="" class="img-responsive" >
<p> Detail of one of the buildings at Florida Southern College designed by architect <NAME>.</p>
</div>
</div>
<p>Polk County, named after President <NAME>, was established in 1861 after being split from Hillsborough County. Located along the I-4 Corridor, Polk County has seen a lot of expansion over the past few decades. Polk County contains many sites that display the cultural heritage of this region.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.polk-county.net/">Polk County</a></li>
<li><a target="_blank" href="http://www.lakelandgov.net/commdev/communitydevelopment/historicpreservation.aspx">City of Lakeland</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.cityoflakewales.com/depot/index.shtml">Depot Museum-Lake Wales</a></li>
<li><a target="_blank" href="http://townofdundee.com/our-community/margaret-kampsen-historic-depot">Depot Museum-Dundee</a></li>
<li><a target="_blank" href="http://www.polk-county.net/county_offices/leisure_svcs/hist_museum/index.aspx">Historical Museum</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.polk-county.net/subpage.aspx?menu_id=52&nav=res&id=948">Homeland Heritage Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://boksanctuary.org/">Historic Bok Sanctuary</a></li>
<li><a target="_blank" href="http://www.lakelandgov.net/commdev/communitydevelopment/historicpreservation.aspx">Florida Southern College – Frank Lloyd Wright Architecture</a> </li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.polkcountyhistory.org/">Polk County Historical Association</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Sarasota County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'sarasota'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Sarasota<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/sarasota.jpg" alt="" class="img-responsive" width="600" height="424">
<p>Palmer House at Historic Spanish Point.</p></div>
</div>
<p>Within Sarasota County’s borders you can uncover an immense amount of information from all of the museums and other historical locations located within this county. In Sarasota County you have access to informational settings as diverse as the Crowley Museum and the Nature Center Ringling Museum of Art to satisfy a variety of intellectual desires. Sarasota also houses a large quantity of parks to enjoy.</p>
<p><a target="_blank" href="documents/Sarasota_Map.pdf" class="btn">Download our Explore Sarasota Map here!</a></p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="https://www.scgov.net/Pages/default.aspx">Sarasota County</a></li>
<li><a target="_blank" href="https://www.scgov.net/History/Pages/default.aspx">Sarasota County History Center</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://crowleyfl.org/">Crowley Museum and Nature Center</a></li>
<li><a target="_blank" href="http://www.longboatkeyhistory.com/">Longboat Key Historical Society, Inc. and Museum</a></li>
<li><a target="_blank" href="http://floridahistory.org/englewood.htm">The Lampp House Museum</a></li>
<li><a target="_blank" href="http://www.sarasotacarmuseum.org/)">Sarasota Classic Car Museum</a></li>
<li><a target="_blank" href="http://www.ringling.org/)">Ringling Museum of Art</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.myakkariver.org/index.php">Myakka River State Park</a></li>
<li><a target="_blank" href="https://www.scgov.net/parks/Pages/UrferFamilyPark.aspx">Dr. <NAME> House at Urfer Family Park</a></li>
<li><a target="_blank" href="https://www.scgov.net/PhillippiEstate/Pages/PhillippiEstate.aspx">Phillippi Estate Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/oscarscherer">Oscar Scherer State Park</a></li>
<li><a target="_blank" href="https://www.scgov.net/NaturalLands/Pages/Carlton.aspx">T. Mabry Carlton Jr. Memorial Reserve</a></li>
<li><a target="_blank" href="https://www.scgov.net/parks/Pages/IndianMoundPark.aspx">Indian Mound Park</a></li>
<li><a target="_blank" href="https://www.scgov.net/WarmMineralSprings/Pages/default.aspx">Warm Mineral Springs</a></li>
<li><a target="_blank" href="https://www.scgov.net/parks/Pages/NokomisBeach.aspx">Nokomis Beach Plaza</a></li>
<li><a target="_blank" href="http://www.venicegov.com/Park_links/venetian_waterway.asp">Venetian Waterway Park</a></li>
<li><a target="_blank" href="http://www.venicegov.com/Park_links/john_nolen.asp">John Nolen Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/myakkariver/">Myakka River State Park</a> </li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.historicspanishpoint.org/">Historic Spanish Point</a></li>
<li><a target="_blank" href="http://www.crowleymuseumnaturectr.org/">Crowley Museum and Nature Center</a></li>
<li><a target="_blank" href="http://sarasotadar.org/saradesotodar_cemetery.html">Pioneer Whitaker Cemetery</a></li>
<li><a target="_blank" href="http://www.hsosc.com/">Bidwell-Wood House and Crocker Memorial Church in Pioneer Park</a></li>
<li><a target="_blank" href="http://triangleinn.org/">City of Venice Archives and Area Historical Collection</a></li>
<li><a target="_blank" href="http://www.scgov.net/parksandrecreation/RecreationCenters/VeniceTrainDepot.asp">Venice Train Depot</a></li>
<li><a target="_blank" href="http://lord-higelhouse.com/">Lord-Higel House</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.sarasotahistoryalive.com/">Sarasota History Alive!</a></li>
<li><a target="_blank" href="http://ncf.edu/pal">New College of Florida Public Archaeology Lab</a></li>
<li><a target="_blank" href="http://www.timesifters.org/">Time Sifters Archaeology Society</a></li>
<li><a target="_blank" href="http://www.wmslss.org/">Warm Mineral Springs/ Little Salt Spring Archaeological Society</a></li>
<li><a target="_blank" href="http://www.historicsarasota.org/">Sarasota Alliance for Historic Preservation</a></li>
<li><a target="_blank" href="http://www.lemonbayhistory.com/">Lemon Bay Historic Society</a></li>
</ul>
</div>
</div><!-- /.col -->
<?php }else{ ?>
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-12 col-md-8 col-md-push-2">
<p>
The West Central region offers many amazing historical and archaeological sites that you can visit. Click on any county below to discover sites in your area.
<hr/>
<!-- Interactive SVG Map -->
<div id="wcmap" class="center-block"></div>
</p>
<!-- <hr/>
<div class="col-sm-12 text-center">
<div class="image"><img src="" alt="" class="img-responsive" width="400" height="464"></div>
</div> -->
</div>
</div><!-- /.row -->
<?php } ?>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#wcmap').mapSvg({
source: 'images/wc_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //North Central Region Marker
xy:[200,365],
tooltip:'West Central Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Pasco' :{popover:'<h3>Pasco</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=pasco"> Explore Pasco County</a></p>'},
'Hillsborough' :{popover:'<h3>Hillsborough</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=hillsborough"> Explore Hillsborough County</a></p>'},
'Pinellas' :{popover:'<h3>Pinellas</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=pinellas"> Explore Pinellas County</a></p>'},
'Manatee' :{popover:'<h3>Manatee</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=manatee"> Explore Manatee County</a></p>'},
'Sarasota' :{popover:'<h3>Sarasota</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=sarasota"> Explore Sarasota County</a></p>'},
'Polk' :{popover:'<h3>Polk</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=polk"> Explore Polk County</a></p>'},
'Hardee' :{popover:'<h3>Hardee</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=hardee"> Explore Hardee County</a></p>'},
'Highlands' :{popover:'<h3>Highlands</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=highlands"> Explore Highlands County</a></p>'},
'Desoto' :{popover:'<h3>Desoto</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=desoto"> Explore Desoto County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Archaeo Cart";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-dash">
<h3>What is Archaeo Cart?</h3>
<p><strong>Archaeo Cart</strong> is a program of FPAN used to deliver engaging educational programs and archaeology outreach. When Archaeo Cart visits your school or location, students and visitors can tour virtual displays of archaeology sites across Florida, uncover prehistoric and historic timelines, or discover what it takes to think like and be an archaeologist.</p>
<div class="text-center">
<div class="image"><img src="images/archaeo_cart_postcard.png" alt="Archaeo Cart. Get on the road to discovery!" class="img-responsive"></div>
</div>
<p><strong>Archaeo Cart</strong> is a Portable Public Archaeology Classroom. It comes equipped with archaeology-related educational activities, interactive displays, and reading and resource materials. It is available for use at museums, libraries, media centers, schools, classrooms, and special events. Groups or organizations can borrow Archaeo Cart for a predetermined length of time. Borrowers are required to provide security and dedicated electricity for the device and must also participate in a short training and workshop upon delivery.</p>
<div class="text-center">
<div class="image"><img src="images/archaeo_cart.jpg" alt="Archaeo Cart. Get on the road to discovery!" class="img-responsive"></div>
</div>
<h3>How can I get Archaeo Cart?</h3>
<p>ARCHAEO CART is currently being piloted at the <a target="_blank" href="http://www.tampabayhistorycenter.org/">Tampa Bay History Center</a> and <a target="_blank" href="http://www.staugustinelighthouse.com/">St. Augustine Lighthouse & Museum</a>. Please contact us at <a href="mailto:<EMAIL>"><EMAIL></a> for more information or to schedule the cart for your venue.</p>
<h3>Who is <NAME>?</h3>
<div class="text-center">
<img src="images/tommy_tortoise.png" alt="<NAME> Tortoise" class="img-responsive">
</div>
<p><NAME> Tortoise is your guide through Florida archaeology. His timeline program on ARCHAEO CART’s touch screen teaches participants about the many cultural time periods in Florida. He also travels to many sites in Florida and shares what he has learned through his Facebook page.</p>
<p>Make sure to visit <a target="_blank" href="http://www.facebook.com/pages/Tommy-the-Tortoise-Junior-Archaeologist/189861687739646">Tommy the Tortoise on Facebook</a> and become a fan!</p>
</div>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Contact";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-6 col-sm-push-3">
<h3>Address</h3>
<p class="text-center">
Florida Public Archaeology Network – West Central Regional Center
4202 E. Fowler Ave,NEC 116 <br/>
Tampa, FL 33620
</p>
</div>
</div>
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/jeff.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME>, M.A., RPA</strong>
<em>West Central Region Director</em><br/>
(813) 396-2327 <br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('jeff_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="jeff_bio" class="hidden bio">
Jeff is the Director of the West Central Regional Center of FPAN. He earned a M.A. in History/Historical Archaeology and a B.A. in Anthropology from the University of West Florida. Jeff’s work experiences prior to FPAN include employment as a field tech and crew chief with Archaeological Consultants, Inc (Sarasota, FL), an underwater archaeologist for the FL Bureau of Archaeological Research, and museum curator at the Florida Maritime Museum at Cortez. Jeff enjoys coffee and smoked mullet, but not necessarily at the same time.
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/becky.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME>, M.A., RPA</strong>
<em>Public Archaeology Coordinator II</em><br/>
(813) 396-2325 <br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('becky_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="becky_bio" class="hidden bio">
<NAME> earned a Bachelor’s degree in Anthropology from the University of Florida and a Master’s degree in Applied Anthropology with a concentration in Cultural Resource Management from the University of South Florida. Becky’s thesis focused on a survey of Bulow Plantation, an early 19th century sugar plantation located along the east coast of Florida, near what is now Daytona. In addition to using GIS and high-tech survey techniques, another area of interest for her is the archaeology of the more recent past. Becky got her start working with FPAN as a volunteer on the West Central Region’s Driftwood Community Archaeology Project. Working in partnership with local residents, this survey of a neighborhood near St. Petersburg uncovered the remains of an early historic settlement in the area.
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/kassie.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Public Archaeology Coordinator I</em><br/>
(813) 396-2325 <br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<!-- <strong onclick="javascript:showElement('kassie_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong> -->
</p>
</div>
<div class="col-xs-12">
<p id="kassie_bio" class="hidden bio">
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/brittany.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Outreach Assistant</em><br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<!-- <strong onclick="javascript:showElement('kassie_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong> -->
</p>
</div>
<div class="col-xs-12">
<p id="brittany_bio" class="hidden bio">
</p>
</div>
</div><!-- /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Timucuan Technology";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<th class="lg_header"><h1>Timucuan Technology</h1></th>
</tr>
<tr>
<td class="table_mid_white" >
<div align="center">
<img src="../images/timuTechHeader.png" />
</div>
<p> Resources for students and instructions for teachers for exploring northeast Florida's prehistory through biotechnology. Click on links below for full chapters or download the entire book <a href="Timucuan Tech_4.pdf">here</a></p>
<p><strong>Download:</strong> <a href="Timucuan Tech_4.pdf"><em><br />
Timucuan Technology</em></a> (60 MB)</p>
<p> <a href="teacher pages/teacherPagesCombined.pdf">Instructions for Teachers</a> (3 MB) <br />
<br/>
Alignment with Sunshine State Standards, answer keys, activity tips, references, recommended reading </p>
<p><img src="../images/clip_image002.jpg" alt="" width="52" height="52" hspace="12"> <a href="1a_intro.pdf">Introduction—Who Were the Timucua? </a></p>
<table border="0" cellspacing="8">
<tr>
<td>
<img src="../images/clip_image004.jpg" alt="" width="61" height="60" hspace="12">
</td>
<td><p>1.<br />
<a href="1b_debry.pdf">De Bry—Fact or Fiction?</a><br />
<a href="teacher pages/teacher_1.pdf">Teacher Pages </a><br />
</p>
</td>
<td><img src="../images/clip_image014.jpg" alt="" width="69" height="72" hspace="12" /></td>
<td><p>6.<br/>
<a href="6_agri.pdf">Agricultural Technology</a><br/>
<a href="teacher pages/teacher_6.pdf">Teacher Pages </a><br/>
</p>
</td>
</tr>
<tr>
<td>
<img src="../images/clip_image006.jpg" alt="" width="65" height="59" hspace="12">
</td>
<td><p>2.<br />
<a href="2_pyro.pdf">Pyrotechnology </a><br />
<a href="teacher pages/teacher_2.pdf">Teacher Pages </a><br />
<br />
Video - <a href="http://www.youtube.com/watch?v=LnXnuNMWE1I&list=PLuzZGqqA6qjcs_lDlxrFboatnEj60McZ9">Fire Drill</a><br />
Video -
<a href="http://www.youtube.com/watch?v=U6bALofxDOQ">Pyro & Balloons</a><br />
</p>
</td>
<td><img src="../images/clip_image016.jpg" alt="" width="75" height="77" hspace="12" /></td>
<td><p>7.<br/>
<a href="7_build.pdf">Building Technology</a><br/>
<a href="teacher pages/teacher_7.pdf">Teacher Pages</a><br />
<br />
Video - <a href="http://www.youtube.com/watch?v=xgGYuL0Nnlw">Thatching</a><br />
Video - <a href="http://www.youtube.com/watch?v=NLcs9T2I1Uc">Making a Weir</a><br />
<br/>
</p>
</td>
</tr>
<tr>
<td>
<img src="../images/clip_image008.jpg" alt="" width="69" height="73" hspace="12">
</td>
<td><p>3.<br />
<a href="3_tool.pdf">Tool-Making Technology</a><br />
<a href="teacher pages/teacher_3.pdf">Teacher Pages</a><br />
<br />
Video - <a href="http://www.youtube.com/watch?v=U6bALofxDOQ">Soap Carving </a><br />
</p>
</td>
<td><img src="../images/clip_image018.jpg" alt="" width="74" height="67" hspace="12" /></td>
<td><p>8.<br />
<a href="8_archy.pdf">Archaeological Technology</a><br/>
<a href="teacher pages/teacher_8.pdf">Teacher Pages</a><br />
<br />
Video - <a href="http://www.youtube.com/watch?v=SAPLd9Kwl_s">Excavation </a><br/>
</p>
</td>
</tr>
<tr>
<td>
<img src="../images/clip_image010.jpg" alt="" width="67" height="62" hspace="12">
</td>
<td><p>4.<br />
<a href="4_animal.pdf">Animal Technology</a><br />
<a href="teacher pages/teacher_4.pdf">Teacher Pages</a><br />
<br />
</p>
</td>
<td><img src="../images/clip_image020.jpg" alt="" width="75" height="70" hspace="12" /></td>
<td><p>9. <br />
<a href="9_archyB.pdf">Archaeology—Beyond Excavation</a><br/>
<a href="teacher pages/teacher_9.pdf">Teacher Pages <br />
</a><br />
Video - <a href="http://www.youtube.com/watch?v=yTu2iS5SvZg">Canoes</a></p></td>
</tr>
<tr>
<td>
<img src="../images/clip_image012.jpg" alt="" width="67" height="66" hspace="12">
</td>
<td><p>5. <br />
<a href="5_wild.pdf"> Wild Plant Technology</a><br/>
<a href="teacher pages/teacher_5.pdf">Teacher Pages</a><br />
<br />
Video - <a href="http://www.youtube.com/watch?v=Xev3ZjDvZaQ">Cord Making </a><br />
</p>
</td>
<td><img src="../images/clip_image022.jpg" alt="" width="75" height="69" hspace="12" /></td>
<td><p>10. <br />
<a href="10_hist.pdf">History and the Timucua</a><br/>
<a href="teacher pages/teacher_10.pdf">Teacher Pages</a>
</p>
</td>
</tr>
</table>
<p align="center"><img src="../images/3_author.jpg" width="507" height="170" /></p>
<p align="center"><img src="../images/4_credits.jpg" width="650" height="502" /></p>
</td>
</tr>
<tr>
<td height="2" class="lg_bottom_white"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?><file_sep><?php
$pageTitle = "Volunteer";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-tab">
<div class="text-center">
<div class="image center-block" style="max-width:400px;">
<img src="images/volunteer.jpg" alt="" class="img-responsive" >
<p>Volunteers learn to identify different prehistoric pottery types from FPAN archaeologists at the Weedon Island Preserve in St Pete.</p>
</div>
</div>
<p class="text-center"><strong>FPAN Archaeology Lab Volunteer Program at the Weedon Island Preserve Cultural and Natural History Center</strong></p>
<p><strong>WHERE:</strong> 1800 Weedon DR NE, St Petersburg, FL 33702</p>
<p><strong>WHEN:</strong> Check event calendar for specific days</p>
<p>FPAN is seeking enthusiastic volunteers of all ages to help rough sort artifacts recovered from local archaeological sites. Volunteers work inside our air-conditioned lab to rough sort artifacts recovered from local archaeological sites. Volunteers work with small screens, trays, brushes, magnets and other lab tools to clean and sort artifacts. Once artifacts have been cleaned, they are sorted into groups of like materials (i.e. brick, glass, shell, ceramics, stone, etc.) No experience is needed, but all volunteers are given a brief orientation by a professional archaeologist their first day.</p>
<p>The volunteer program is perfect for students who need volunteer hours for scholarships, individuals and groups interested in a unique way to experience local history and archaeology, as well as all of those who have dreamed of getting their hands dirty participating in real archaeological work. All ages are encouraged to participate; however, anyone under 17 years of age must be accompanied by an adult. Individuals, families and groups can be accommodated.
Lab work will be done in the classroom at the Weedon Island Preserve Cultural and Natural History Center.
<p>For more information contact <NAME> at <a href="mailto:<EMAIL>"><EMAIL></a> or 813-396-2325.</p>
</p>
</div><!-- /.box-tab -->
<h2>Get Involved</h2>
<div class="box-tab">
<p>There are many Organizations you can join to pursue an interest in archaeology. Here are some of our favorites in the West Central region:</p>
<h3>Local Organizations</h3>
<ul>
<li><a target="_blank" href="https://www.facebook.com/KVAHC">Kissimmee Valley Archaeological and Historical Conservancy</a></li>
<li><a target="_blank" href="http://www.cgcas.org/">Central Gulf Coast Archaeological Society</a> </li>
<li><a target="_blank" href="http://www.timesifters.org">Time Sifters Archaeological Society</a> </li>
<li><a target="_blank" href="http://www.awiare.org">Alliance for Weedon Island Archaeological Research and Education</a> </li>
<li><a target="_blank" href="http://www.wmslssas.org/">Warm Mineral Springs/Little Salt Spring Archaeological Society</a> </li>
</ul>
<h3>State Organizations</h3>
<ul>
<li><a target="_blank" href="http://www.fasweb.org/">Florida Anthropological Society</a></li>
<li><a target="_blank" target="_blank" href="http://www.flamuseums.org/">Florida Association of Museums</a></li>
<li><a target="_blank" href="http://www.floridatrust.org/">Florida Trust</a></li>
</ul>
<h3>National & International Organizations</h3>
<ul>
<li><a target="_blank" href="http://www.saa.org/">Society for American Anthropology</a></li>
<li><a target="_blank" href="http://www.sha.org/">Society for Historical Archaeology</a></li>
<li><a target="_blank" href="http://www.southeasternarchaeology.org/">Southeastern Archaeological Conference</a></li>
<li><a target="_blank" href="http://www.interpnet.com/">National Association for Interpretation</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
include 'header.php';
if ($submit) {
// required fields in the line below
if (!$old_password || !$new_password || !$conf_new_password){
$msg = "You must complete all fields";
$err = true;
}
else{
//Protect against SQL injection
$old_password = mysql_real_escape_string($old_password);
$new_password = mysql_real_escape_string($new_password);
$conf_new_password = mysql_real_escape_string($conf_new_password);
//Make sure username exists and old password is valid
$sql = "SELECT * FROM Employees WHERE email = '$_SESSION[my_email]' AND password = AES_ENCRYPT('$old_<PASSWORD>', '$_SESSION[aes_key]')";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count != 1){
$msg = "Invalid old password.";
$err = true;
}
//Make sure new passwords patch
if($new_password != $conf_new_password){
$msg = "New passwords do not match.";
$err = true;
}
//If no error so far, change password
if (!$err) {
$sql = "UPDATE Employees SET password = AES_ENCRYPT('$new_password', '$_SESSION[aes_key]') WHERE email = '$_SESSION[my_email]'";
$result=mysql_query($sql);
$msg = "Password successfully changed.";
}
}
}
?>
<h3 align="center"> Change Password </h3>
<table style="margin-left:auto; margin-right:auto;" cellpadding="0" cellspacing="0">
<tr>
<td>
<?
if($err)
$color = "red";
if($msg)
echo "<p align=\"center\" style=\"color:$color;\" class=\"msg\"> $msg </p>";
?>
<form action="<?php echo $php_SELF ?>" method="post">
<table border="0" align="center" cellpadding="3" cellspacing="0" >
<tr>
<td><div align="right">Email:</div></td>
<td><strong><?php echo $_SESSION['my_email']; ?></strong>
</td>
</tr>
<tr>
<td><div align="right">Old Password:</div></td>
<td><input name="old_password" type="<PASSWORD>" required="Yes" >
</td>
</tr>
<tr>
<td><div align="right" style="color:#900">New Password:</div></td>
<td><input name="new_password" type="password">
</td>
</tr>
<tr>
<td><div align="right" style="color:#900">Confirm New Password:</div></td>
<td><input name="conf_new_password" type="<PASSWORD>" >
</td>
</tr>
<tr>
<td colspan="2" valign="middle"><div align="center"> <br />
<input name="submit" type="submit" value="Submit" class="navbtn"/>
</div></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
<br/>
<br/>
<br/>
<br/>
</div>
</body>
</html>
<file_sep><?php
$pageTitle = "Presentations";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?> <small>Request a Speaker</small></h1>
</div>
<div class="box-dash">
<div class="col-sm-12 text-center">
<div class="image">
<img src="images/presentations.jpg" alt="Speaker presentations." class="img-responsive" width="500" height="281" />
</div>
</div>
<p>FPAN can help facilitate speakers for meetings of your civic group, community organization,
youth club, or heritage society, and for lecture series and special events.</p>
<p>Most presentations last about 30-45 minutes with additional time for questions, although
programs usually can be tailored for your needs. Specific topics are dependent on speaker
availability, so book early! There is no charge for presentations, although donations are
gratefully accepted to support FPAN educational programs.</p>
<p>Presentation topics are divided into two sections: </p>
<div class="col-sm-12 text-center">
<p>
<a href="#children" class="btn btn-info">Youth Programs</a>
<a href="#adults" class="btn btn-info">Presentations for Adults</a>
</p>
</div>
<p>Take a look at our offerings, then <a href="https://casweb.wufoo.com/forms/west-central-speaker-request-form/">
submit the form below</a> and let us
know what you’d like to learn about! If you don’t see what you’re looking for, ask us and we’ll do our
best to accommodate you.</p>
<p class="text-center"><em>Know what you want?</em> <br/> <a class="btn btn-primary"
href="https://casweb.wufoo.com/forms/west-central-speaker-request-form/" target="_blank">Submit a Speaker Request Form</a> </p>
</div>
<h2 id="children">Youth Programs</h2>
<div class="box-tab row">
<p>We have a wide variety of programming especially designed to educate kids about archaeology as well as Florida’s rich past. Whether for a classroom presentation, homeschool group, library event, school science night, or other group event we can tailor our programming to your interests and age level. Below are just a few examples of our youth programs:</p>
<div class="col-sm-6">
<ul>
<li><a href="#howold">Archaeology Works: How Old Is It?</a></li>
<li><a href="#matsci">Archaeology Works: Materials Science</a></li>
<li><a href="#diveinto">Dive into Archaeology</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#prefl">Discover Prehistoric Florida</a></li>
<li><a href="#atlatl">Atlatl Antics (for schools only)</a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div id="howold" class="col-sm-12">
<h3>Archaeology Works: How Old Is It?</h3>
<p>In this presentation you'll get to learn about a few of the ways archaeologists date artifacts and discover how they can help us learn about people who have lived in Florida throughout time!</p>
</div>
<div id="matsci" class="col-sm-12">
<h3>Archaeology Works: Materials Science</h3>
<p>Explore ancient artifacts from stone tools to pottery under a microscope just like an archaeologist! You'll get to see what aspects of these materials we, as archaeologists, focus on to get information about past technologies, and what aspects of Native American life we can learn about by studying the materials people left behind.</p>
</div>
<div id="diveinto" class="col-sm-12">
<h3>Dive into Archaeology</h3>
<p>Archaeologists don’t just work on land; they also try to learn about past people through the things they left behind underwater! In this fun and educational program, kids learn about the basics of archaeology as well as some of Florida’s important shipwrecks.</p>
</div>
<div id="prefl" class="col-sm-12">
<h3>Discover Prehistoric Florida</h3>
<p>People have lived throughout Florida for thousands of years, but the only way we know about them is through archaeology and the clues they left behind. Learn what it was like to live in prehistoric Florida long ago, complete with real artifacts and replicas of tools that ancient Floridians would have used to survive.</p>
</div>
<div id="atlatl" class="col-sm-12">
<h3>Atlatl Antics (for schools only)</h3>
<p>Learn about how hunting technology changed through time in prehistoric Florida, as well as how archaeologists study these changes. In this program kids get an introduction to archaeology and the chance to try a prehistoric hunting tool, the atlatl, for themselves.</p>
</div>
</div><!-- /.box /.row -->
<h2 id="adults">Presentations for Adults</h2>
<div class="box-tab row">
<p>Archaeologists from the FPAN West Central office have a wide variety of interests and expertise to share with your group. Below are just a few examples of presentations we can provide. If you have another topic related to Florida archaeology you would like to hear about please contact us. We’re coming up with new presentation ideas all the time!</p>
<div class="col-sm-6">
<ul>
<li><a href="#introarch">Intro to Archaeology: Bringing the Past to the Present</a></li>
<li><a href="#firstfl">Tracing the First Floridians, the Paleoindians</a></li>
<li><a href="#cemetery">Cemetery Transcription and Headstone Cleaning</a></li>
<li><a href="#histmaps">Using Historical Maps in your Genealogy Research</a></li>
<li><a href="#ybor">Ybor City beneath the Surface</a></li>
<li><a href="#peoplenight">People and the Night Sky</a></li>
<li><a href="#pastcontained">The Past Contained: Florida's Prehistoric Pottery Tradition</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#firstthanks">The First Thanksgiving in Florida: St Augustine, 1565</a></li>
<li><a href="#prepot">Prehistoric Pottery and the Crystal River Site</a></li>
<li><a href="#prepete">Prehistoric St Pete: Exploring the Archaeology of the Weedon Island Site</a></li>
<li><a href="#cuban">Cuban Fishing Ranchos in Tampa Bay</a></li>
<li><a href="#tampawrecks">Tampa Bay Shipwrecks of the Civil War</a></li>
<li><a href="#oldwrecks">The Oldest Shipwrecks of the Florida Keys</a></li>
<li><a href="#flpreserves">Florida's Shipwreck Preserves: Living Maritime Heritage You Can Visit</a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div id="introarch" class="col-sm-12">
<h3>Intro to Archaeology: Bringing the Past to the Present</h3>
<p>What do archaeologists do, exactly? Learn about the science of archaeology, its role as part of the field of anthropology, where archaeologists work, and how they discover and protect our cultural heritage. Appropriate for all ages, this fun and informative show sets the stage for understanding how archaeology preserves our past for the present and future.</p>
</div>
<div id="firstfl" class="col-sm-12">
<h3>Tracing the First Floridians, the Paleoindians</h3>
<p>Exciting research by archaeologists across Florida is shedding light on some of our state's earliest residents: the Paleoindians. This talk will explore what we know about Florida's first residents, as well as how archaeology can inform us about this little understood part of our past.</p>
</div>
<div id="cemetery" class="col-sm-12">
<h3>Cemetery Transcription and Headstone Cleaning</h3>
<p>Learn best practices for recording and cleaning historic grave markers in this introduction to cemetery preservation and maintenance.</p>
</div>
<div id="histmaps" class="col-sm-12">
<h3>Using Historical Maps in your Genealogy Research</h3>
<p>This talk covers the ways different historical maps such as Sanborn Fire Insurance maps, Plat maps, and Coastal Survey maps can be used in your research, as well as the many digital and paper sources for these maps, how to locate the map you need, and the possible information about your ancestors it might contain.</p>
</div>
<div id="ybor" class="col-sm-12">
<h3>Ybor City beneath the Surface</h3>
<p>Archaeology beneath the Ybor City we see today can tell us even more about the people who founded and lived in this bustling and unique cigar town. This presentation covers the current work to connect the small forgotten things recovered during excavations throughout the area to the people of Ybor City’s past and present.</p>
</div>
<div id="peoplenight" class="col-sm-12">
<h3>People and the Night Sky</h3>
<p>For Native Floridians, the night sky was very important for navigational, religious, and historical reasons. Over time, the sky has changed and so has the way people relate to it. Learn about how astronomical and cultural changes have affected the importance of the night sky to people today.</p>
</div>
<div id="pastcontained" class="col-sm-12">
<h3>The Past Contained: Florida's Prehistoric Pottery Tradition</h3>
<p>Pottery was an important part of Native American culture and has also become a valuable artifact for archaeologists today. In this presentation learn all about the Native American process for making pottery, how and why they used it, and what information archaeologists can get from studying these small pieces of the past.</p>
</div>
<div id="firstthanks" class="col-sm-12">
<h3>The First Thanksgiving in Florida: St Augustine, 1565</h3>
<p>This family friendly presentation discusses the first contact between European explorers and Native Americans in what is now Florida, as well as the real story of the first Thanksgiving in St. Augustine.</p>
</div>
<div id="prepot" class="col-sm-12">
<h3>Prehistoric Pottery and the Crystal River Site</h3>
<p>The Crystal River site was once a sprawling ceremonial center with impressive earthen architecture. Though the earthworks are still visible today there is still much to learn about the people who created them and the artifacts they contain. In this presentation learn about the Crystal River mound complex and recent findings on the site's pottery collection.</p>
</div>
<div id="prepete" class="col-sm-12">
<h3>Prehistoric St Pete: Exploring the Archaeology of the Weedon Island Site</h3>
<p>For almost 100 years, archaeologists have been the mounds and middens created by Native Americans at the Weedon Island site in St Petersburg. Learn about some of the amazing finds at this site, as well as what they reveal about the past residents of the area.</p>
</div>
<div id="cuban" class="col-sm-12">
<h3>Cuban Fishing Ranchos in Tampa Bay</h3>
<p>This talk focuses on some of the earliest historic settlements along the Gulf Coast, and how important these early Spanish/Cuban fishing camps were to the development of Tampa Bay.</p>
</div>
<div id="tampawrecks" class="col-sm-12">
<h3>Tampa Bay Shipwrecks of the Civil War</h3>
<p>The maritime battles of the Civil War employed a greater diversity of ships than any previous sustained naval action. This presentation illustrates this aspect and highlights a few examples of Civil War-related shipwrecks in the Tampa Bay area.</p>
</div>
<div id="oldwrecks" class="col-sm-12">
<h3>The Oldest Shipwrecks of the Florida Keys</h3>
<p>The Florida Keys are rife with remains of shipwrecks and maritime disasters. This presentation explores several that you can visit today, including the vessel remains of the famous 1733 Spanish Plate fleet disaster.</p>
</div>
<div id="flpreserves" class="col-sm-12">
<h3>Florida's Shipwreck Preserves: Living Maritime Heritage You Can Visit</h3>
<p>Clues to Florida’s maritime history are scattered along the state’s coasts, bays, and rivers in the form of shipwrecks relating to waterborne exploration, commerce, and warfare. This lecture features Florida’s Museums in the Sea, historic shipwrecks that have been interpreted for divers and snorkelers as a way to educate citizens and visitors about the real treasure of Florida’s shipwrecks – their history.</p>
</div>
</div><!-- /.box /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?> <file_sep><?php
include 'appHeader.php';
$eventID = mysqli_real_escape_string($dblink, $_POST['eventID']);
$page = "eventEdit.php"; //Redirect here if error occurs
//If event is being deleted
if($_GET['del']==true){
$eventID = mysqli_real_escape_string($dblink, $_GET['eventID']);
if($eventID == null){
$msg = "Cannot delete, no eventID was specified!";
event_error($msg,"eventList.php");
}
else{
$sql = "DELETE FROM $table WHERE eventID = $eventID;";
if(!mysqli_query($dblink, $sql)){
$err = true;
$msg = 'Error: ' . mysqli_error();
}
else
$msg = "Event successfully deleted.";
$archiveURL = ($_GET['archive'] == true) ? "&archive=true" : null;
header("location:eventList.php?&msg=$msg&err=$err$archiveURL");
die();
}
}
//******** File upload config *********/
if($_FILES['flyerFile']['size'] > 0){
$filename = $_FILES['flyerFile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes)){
$msg = 'The file type you attempted to upload is not allowed: '. $ext;
event_error($msg,$page);
}
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['flyerFile']['tmp_name']) > $max_filesize){
$msg = 'The file you attempted to upload is too large.';
event_error($msg,$page);
}
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($uploadDirectory)){
$msg = 'You cannot upload to the specified directory: '.$uploadDirectory;
event_error($msg,$page);
}
// Upload the file to your specified path.
if(!move_uploaded_file($_FILES['flyerFile']['tmp_name'],$uploadDirectory.$filename)){
$msg = 'There was an error during the file upload. Please try again.';
event_error($msg,$page);
}
}
/****** Sanitize Data ******/
//Get POST variables from form, add slashes and convert HTML characters. Store in an array to maintain form data in case of error
$eventVars['title'] = mysqli_real_escape_string($dblink, addslashes($_POST['title']));
$eventVars['description'] = mysqli_real_escape_string($dblink, addslashes($_POST['description']));
$eventVars['location'] = mysqli_real_escape_string($dblink, addslashes($_POST['location']));
$eventVars['eventDate'] = mysqli_real_escape_string($dblink, $_POST['eventDate']);
$eventVars['eventTimeStart'] = mysqli_real_escape_string($dblink, $_POST['eventTimeStart']);
$eventVars['eventTimeEnd'] = mysqli_real_escape_string($dblink, $_POST['eventTimeEnd']);
$eventVars['startAMPM'] = mysqli_real_escape_string($dblink, $_POST['startAMPM']);
$eventVars['endAMPM'] = mysqli_real_escape_string($dblink, $_POST['endAMPM']);
$eventVars['relation'] = mysqli_real_escape_string($dblink, $_POST['relation']);
$eventVars['link'] = mysqli_real_escape_string($dblink, $_POST['link']);
$eventVars['flyerLink'] = mysqli_real_escape_string($dblink, $_POST['flyerLink']);
$_SESSION['eventVars'] = $eventVars;
//****** Validate Inputs ******/
//Required field, cannot be blank, must have proper format
$eventDate = $eventVars['eventDate'];
check_date($eventDate);
//Required fields, cannot be blank, must have proper format
$eventTimeStart = $eventVars['eventTimeStart'];
$eventTimeEnd = $eventVars['eventTimeEnd'];
check_time($eventTimeStart);
check_time($eventTimeEnd);
//Convert times and dates to 24hr PHP timestamp
$timestampStart = strtotime($eventDate . $eventTimeStart);
$timestampEnd = strtotime($eventDate . $eventTimeEnd);
//Convert times and dates to 24hr MySQL time format
$eventDateTimeStart = date('Y-m-d H:i:s', $timestampStart);
$eventDateTimeEnd = date('Y-m-d H:i:s', $timestampEnd);
$relation = $eventVars['relation'];
$title = $eventVars['title'];
check_input($eventVars['title'],"You must enter a title.");
$location = $eventVars['location'];
check_input($location,"You must enter a location.");
$link = $eventVars['link'];
if($_FILES['flyerFile']['size'] > 0)
$flyerLink = $rootUploadDirectory.$region."/".$filename;
else
$flyerLink = $eventVars['flyerLink'];
$description = $eventVars['description'];
/****** Put the Event in the Database ******/
//If eventID is defined, event is being edited
if($_POST['eventID'] != null){
$sql = "UPDATE $table
SET title = '$title',
description = '$description',
location = '$location',
eventDateTimeStart = '$eventDateTimeStart',
eventDateTimeEnd = '$eventDateTimeEnd',
relation = '$relation',
link = '$link',
flyerLink = '$flyerLink'
WHERE eventID = $eventID;";
if(!mysqli_query($dblink, $sql)){
$err = true;
$msg = 'Error: ' . mysqli_error();
}
else
$msg = "Event successfully updated.";
//Clear temporary event array
$_SESSION['eventVars'] = "";
//Else if eventID is not defined, new event is being added
}else{
$sql = "INSERT INTO $table (title, description, location, eventDateTimeStart, eventDateTimeEnd, relation, link, flyerLink)
VALUES ('$title', '$description', '$location', '$eventDateTimeStart', '$eventDateTimeEnd', '$relation', '$link', '$flyerLink');";
if(!mysqli_query($dblink, $sql)){
$err = true;
$msg = 'Error: ' . mysqli_error();
}
else
$msg = "Event successfully added.";
//Clear temporary event array
$_SESSION['eventVars'] = "";
}
//set archive var to return to archive page if request came from there
$archiveURL = ($_GET['archive'] == true) ? "&archive=true" : null;
//Redirect after edit/delete has completed with message, error, and archive values.
header("location:eventList.php?&msg=$msg&err=$err$archiveURL");
?><file_sep><?php
session_start();
//Determine if user is logged in, redirect to login page if not
if(!isset($_SESSION['my_email'])){
header("location:index.php?loggedIn=no");
}
include_once('dbConnect.php');
include_once('resources/_viewFunctions.php');
include_once('resources/_formFunctions.php');
include_once('resources/_reportFunctions.php');
ini_set('display_errors', '1');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FPAN Activity Reports</title>
<link rel="stylesheet" type="text/css" href="resources/css/forms.css" media="all">
<link rel="stylesheet" type="text/css" href="resources/css/style.css" media="all">
<link rel="stylesheet" type="text/css" href="resources/css/theme.orange.css"/>
<script type="text/javascript" src="resources/js/view.js"></script>
<script type="text/javascript" src="resources/js/calendar.js"></script>
<script type="text/javascript" src="resources/js/java.js"></script>
<script type="text/javascript" src="resources/js/jquery-1.10.1.js"></script>
<script type="text/javascript" src="resources/js/jquery.tablesorter.js"></script>
<script type="text/javascript">
//****************************** Setup Tablesorter Tables *****************************
//*************************************************************************************
$(function(){
$("#resultsTable").tablesorter( {theme:'orange'} );
//$("#resultsTablePublicOutreach").tablesorter({headers: { 1: { sorter: 'shortDate'}}});
$("#resultsTablePublicOutreach").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableTrainingWorkshops").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableGovernmentAssistance").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableSocialMedia").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableMeeting").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTablePressContact").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTablePublication").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableDirectMail").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableServiceToProfessionalSociety").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableServiceToHostInstitution").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableServiceToCommunity").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableTrainingCertificationEducation").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTableConferenceAttendanceParticipation").tablesorter({theme:'orange', widgets: ["zebra"],
headers: { 0 : { sorter: false } , 1: { sorter: 'shortDate'}}});
$("#resultsTablenwrc").tablesorter({theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false },
1 : { sorter: false }, 2 : { sorter: false }, 3 : { sorter: false }}});
$("#resultsTablencrc").tablesorter({theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false },
1 : { sorter: false }, 2 : { sorter: false }, 3 : { sorter: false }}});
$("#resultsTablenerc").tablesorter({theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false },
1 : { sorter: false }, 2 : { sorter: false }, 3 : { sorter: false }}});
$("#resultsTablewcrc").tablesorter({theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false },
1 : { sorter: false }, 2 : { sorter: false }, 3 : { sorter: false }}});
$("#resultsTablecrc").tablesorter({theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false },
1 : { sorter: false }, 2 : { sorter: false }, 3 : { sorter: false }}});
$("#resultsTableecrc").tablesorter({theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false },
1 : { sorter: false }, 2 : { sorter: false }, 3 : { sorter: false }}});
$("#resultsTableserc").tablesorter({theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false },
1 : { sorter: false }, 2 : { sorter: false }, 3 : { sorter: false }}});
$("#resultsTableswrc").tablesorter({theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false },
1 : { sorter: false }, 2 : { sorter: false }, 3 : { sorter: false }}});
$("#volunteerResultsTable").tablesorter( {theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false }, 1 : { sorter: false }, 2 : { sorter: false }}} );
$("#attendeesResultsTable").tablesorter( {theme:'orange', widgets: ["zebra"], headers: { 0 : { sorter: false }, 1 : { sorter: false }, 2 : { sorter: false }}} );
}
);
//Confirm delete function
function confirmDelete(){
var agree=confirm("Are you SURE you want to delete this?");
if (agree)
return true;
else
return false;
}
</script>
</head>
<body id="main_body" >
<img id="top" src="images/top.png" alt="">
<div id="form_container">
<div id="header">
<a href="main.php"><img src="images/sun.png" align="right" /></a>
<h1>FPAN Reports System </h1>
</div>
<?php if($_SESSION['my_name'] && !$_GET['logout']){ ?>
<nav>
<ul>
<li><a href="main.php">Add Activities</a>
<ul>
<li><a href="#">Activities and Events </a>
<ul>
<li><a href="publicOutreach.php?new=true">Public Outreach</a></li>
<li><a href="trainingWorkshops.php?new=true">Training / Workshops</a></li>
<li><a href="governmentAssistance.php?new=true">Government Assistance</a></li>
<li><a href="meeting.php?new=true">Meeting</a></li>
<li><a href="socialMedia.php?new=true">Social Media</a></li>
<li><a href="pressContact.php?new=true">Press Contact</a></li>
<li><a href="publication.php?new=true">Publication</a></li>
<li><a href="directMail.php?new=true">Direct Mail / Newsletter</a></li>
</ul>
</li>
<li><a href="#">Professional Service and Development</a>
<ul>
<li><a href="serviceToProfessionalSociety.php?new=true">Service to Professional Society</a></li>
<li><a href="serviceToHostInstitution.php?new=true">Service to Host Institution</a></li>
<li><a href="serviceToCommunity.php?new=true">Service to Community</a></li>
<li><a href="trainingCertificationEducation.php?new=true">Training / Certification / Education</a></li>
<li><a href="conferenceAttendanceParticipation.php?new=true">Conference Attendance / Participation</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="viewActivities.php">View Activities</a>
<ul>
<li><a href="#">Activities and Events</a>
<ul>
<li><a href="viewTypeActivities.php?typeActivity=PublicOutreach">Public Outreach</a></li>
<li><a href="viewTypeActivities.php?typeActivity=TrainingWorkshops">Training / Workshops</a></li>
<li><a href="viewTypeActivities.php?typeActivity=GovernmentAssistance">Government Assistance</a></li>
<li><a href="viewTypeActivities.php?typeActivity=Meeting">Meeting</a></li>
<li><a href="viewTypeActivities.php?typeActivity=SocialMedia">Social Media</a></li>
<li><a href="viewTypeActivities.php?typeActivity=PressContact">Press Contact</a></li>
<li><a href="viewTypeActivities.php?typeActivity=Publication">Publication</a></li>
<li><a href="viewTypeActivities.php?typeActivity=DirectMail">Direct Mail / Newsletter</a></li>
</ul>
</li>
<li><a href="#">Professional Service and Development</a>
<ul >
<li><a href="viewTypeActivities.php?typeActivity=ServiceToProfessionalSociety">Service to Professional Society</a></li>
<li><a href="viewTypeActivities.php?typeActivity=ServiceToHostInstitution">Service to Host Institution</a></li>
<li><a href="viewTypeActivities.php?typeActivity=ServiceToCommunity">Service to Community</a></li>
<li><a href="viewTypeActivities.php?typeActivity=TrainingCertificationEducation">Training / Certification / Education</a></li>
<li><a href="viewTypeActivities.php?typeActivity=ConferenceAttendanceParticipation">Conference Attendance / Participation</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="reports.php">Generate Reports</a></li>
<li><a href="admin.php">Options</a></li>
<span>
You are logged in as <strong> <?php echo $_SESSION['my_name']; ?> </strong>
(<a href="index.php?logout=1" style="font-size:10px; font-weight:bold">Log Out</a>)
</span>
</ul>
</nav>
<?php } ?>
<p></p><file_sep><?php
$pageTitle = "Contact";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-6 col-sm-push-3">
<h3>Address</h3>
<p class="text-center">
74 King Street<br/> St. Augustine, FL 32085-1027
</p>
</div>
</div>
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/sarah.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME>, M.A., RPA</strong>
<em>Northeast Region Director</em><br/>
(904) 819-6476 <br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('sarah_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="sarah_bio" class="hidden bio">
<NAME> received her Masters degree in Anthropology from East Carolina University in 2001 where she developed archaeology education programs at Tryon Palace in New Bern, North Carolina. Upon graduation from ECU, Ms. Miller supervised field and lab projects with public involvement for the Kentucky Archaeological Survey, as well as reviewing compliance projects for the Kentucky Heritage Council. She now serves as Director for FPAN's Northeast and East Central Regions, statewide coordinator and Leadership Team member for Project Archaeology, Chair for the Society for Historical Archaeology's Public Education and Interpretation Committee, and sits on the Historic Resource Review Board for St. Johns County. Her specialties include public archaeology, historical archaeology, municipal archaeology and historic cemeteries.</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/ryan.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME>.</strong>
<em>Public Archaeology Coordinator II</em><br/>
(904) 819-6498 <br/>
<a href="<EMAIL>"><EMAIL></a>
<!-- <strong onclick="javascript:showElement('barbara_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong> -->
</p>
</div>
<!-- <div class="col-xs-12">
<p id="barbara_bio" class="hidden bio">
<NAME> is a Registered Professional Archaeologist who specializes in historic archaeology, 19th and early 20th century. Her interests include the turpentine and lumber industry, specifically focusing on the social aspects of "camp life". She also has taken an interest in early Florida architecture, and did her thesis work on an early 1900s Folk Victorian structure in Sopchoppy, Florida. Her thesis focused on examining the relationship between architecture, societal relationships and social class perceptions. Barbara has also taken an interest in Southeastern Indian communities after European contact, specifically in the late 1800 up to the present, focusing on the mixing of cultures and how the Southeastern Indian population has survived and adapted.
</p>
</div> -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/emily.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME>, M.A.</strong>
<em>Public Archaeology Coordinator I</em><br/>
(904) 392-7874<br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<!-- <strong onclick="javascript:showElement('barbara_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
--> </p>
</div>
<!-- <div class="col-xs-12">
<p id="barbara_bio" class="hidden bio">
<NAME> is a Registered Professional Archaeologist who specializes in historic archaeology, 19th and early 20th century. Her interests include the turpentine and lumber industry, specifically focusing on the social aspects of "camp life". She also has taken an interest in early Florida architecture, and did her thesis work on an early 1900s Folk Victorian structure in Sopchoppy, Florida. Her thesis focused on examining the relationship between architecture, societal relationships and social class perceptions. Barbara has also taken an interest in Southeastern Indian communities after European contact, specifically in the late 1800 up to the present, focusing on the mixing of cultures and how the Southeastern Indian population has survived and adapted.
</p>
</div> -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/robbie.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME> </strong>
<em>Office Manager</em><br/>
(904) 392-8022<br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<!-- <strong onclick="javascript:showElement('barbara_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong> -->
</p>
</div>
<!-- <div class="col-xs-12">
<p id="barbara_bio" class="hidden bio">
<NAME> is a Registered Professional Archaeologist who specializes in historic archaeology, 19th and early 20th century. Her interests include the turpentine and lumber industry, specifically focusing on the social aspects of "camp life". She also has taken an interest in early Florida architecture, and did her thesis work on an early 1900s Folk Victorian structure in Sopchoppy, Florida. Her thesis focused on examining the relationship between architecture, societal relationships and social class perceptions. Barbara has also taken an interest in Southeastern Indian communities after European contact, specifically in the late 1800 up to the present, focusing on the mixing of cultures and how the Southeastern Indian population has survived and adapted.
</p>
</div> -->
</div><!-- /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
include 'header.php';
$displayLimit = 99999999;
$activityArray = array();
//Assign POST display limiting variables
if($_POST['startYear'] && $_POST['endYear']){
$startDate = $_POST['startYear']."-".$_POST['startMonth']."-".$_POST['startDay'];
$endDate = $_POST['endYear']."-".$_POST['endMonth']."-".$_POST['endDay'];
}
if($_POST['reset']){
$startDate = NULL;
$endDate = NULL;
}
?>
<table width="680" border="0" cellspacing="2" align="center">
<tr>
<td valign="top">
<table cellspacing="15" align="center">
<tr>
<td>
<form action="<?php echo curPageUrl(); ?>" method="post">
<label class="description" for="element_1">Start Date </label>
<span>
<input id="element_1_1" name="startMonth" class="element text" size="2" maxlength="2" value="<?php echo $_POST['startMonth']; ?>" type="text" >
-
</span> <span>
<input id="element_1_2" name="startDay" class="element text" size="2" maxlength="2" value="<?php echo $_POST['startDay']; ?>" type="text">
-
</span> <span>
<input id="element_1_3" name="startYear" class="element text" size="4" maxlength="4" value="<?php echo $_POST['startYear']; ?>" type="text">
</span> <span id="calendar_1"> <img id="cal_img_1" class="datepicker" src="images/calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</td>
<td>
<label class="description" for="element_2">End Date </label>
<span>
<input id="element_2_1" name="endMonth" class="element text" size="2" maxlength="2" value="<?php echo $_POST['endMonth']; ?>" type="text">
-
</span> <span>
<input id="element_2_2" name="endDay" class="element text" size="2" maxlength="2" value="<?php echo $_POST['endDay']; ?>" type="text" >
-
</span> <span>
<input id="element_2_3" name="endYear" class="element text" size="4" maxlength="4" value="<?php echo $_POST['endYear']; ?>" type="text" >
</span> <span id="calendar_2"> <img id="cal_img_2" class="datepicker" src="images/calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_2_3",
baseField : "element_2",
displayArea : "calendar_2",
button : "cal_img_2",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</td>
</tr>
<tr><td colspan="2" style="text-align:center;">
<input type="submit" name="submit" value="Go"/>
<input type="submit" name="reset" value="Reset"/>
</form>
</td>
</tr></table>
<hr />
<h2 align="center">FPAN Activity / Event</h2>
<div align="center">
<a href="viewActivities.php">Show Recent</a> | <b>Show All</b>
</div>
<br/>
<span class="category_title">Public Outreach</span> - <a href="viewTypeActivities.php?typeActivity=PublicOutreach">View All</a>
<?php
if($startDate && $endDate)
$activityArray = getActivities("PublicOutreach", $startDate, $endDate);
else
$activityArray = getActivities($typeActivity);
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($activityArray) . "</b> activities found.</div>";
printActivities($activityArray, "PublicOutreach", $displayLimit);
?>
<hr/>
<span class="category_title">Training & Workshops</span> - <a href="viewTypeActivities.php?typeActivity=TrainingWorkshops">View All</a>
<?php
$activityArray = getActivities("TrainingWorkshops");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($activityArray) . "</b> activities found.</div>";
printActivities($activityArray, "TrainingWorkshops", $displayLimit);
?>
<hr/>
<span class="category_title">Government Assistance</span> - <a href="viewTypeActivities.php?typeActivity=GovernmentAssistance">View All</a>
<?php
$activityArray = getActivities("GovernmentAssistance");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($activityArray) . "</b> activities found.</div>";
printActivities($activityArray, "GovernmentAssistance", $displayLimit);
?>
<hr/>
<span class="category_title">Meeting</span> - <a href="viewTypeActivities.php?typeActivity=Meeting">View All</a>
<?php
$activityArray = getActivities("Meeting");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($activityArray) . "</b> activities found.</div>";
printActivities($activityArray, "Meeting", $displayLimit);
?>
<hr/>
<span class="category_title">Social Media</span> - <a href="viewTypeActivities.php?typeActivity=SocialMedia">View All</a>
<?php
$activityArray = getActivities("SocialMedia");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($activityArray) . "</b> activities found.</div>";
printActivities($activityArray, "SocialMedia", $displayLimit);
?>
<hr/>
<span class="category_title">Press Contact</span> - <a href="viewTypeActivities.php?typeActivity=PressContact">View All</a>
<?php
$activityArray = getActivities("PressContact");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($activityArray) . "</b> activities found.</div>";
printActivities($activityArray, "PressContact", $displayLimit);
?>
<hr/>
<span class="category_title">Publication </span> - <a href="viewTypeActivities.php?typeActivity=Publication">View All</a>
<?php
$activityArray = getActivities("Publication");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($activityArray) . "</b> activities found.</div>";
printActivities($activityArray, "Publication", $displayLimit);
?>
<hr/>
<span class="category_title">Direct Mail / Newsletter</span> - <a href="viewTypeActivities.php?typeActivity=DirectMail">View All</a>
<?php
$activityArray = getActivities("DirectMail");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($activityArray) . "</b> activities found.</div>";
printActivities($activityArray, "DirectMail", $displayLimit);
?>
<hr/>
</td>
</tr>
<tr>
<td valign="top" >
<h2 align="center">Professional Service and Development</h2>
<span class="category_title">Service to Professional Society</span> - <a href="viewTypeActivities.php?typeActivity=ServiceToProfessionalSociety">View All</a>
<?php
$serviceArray = getServices("ServiceToProfessionalSociety");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($serviceArray) . "</b> services found.</div>";
printServices($serviceArray, "ServiceToProfessionalSociety", $displayLimit);
?>
<hr/>
<span class="category_title">Service to Host Institution</span> - <a href="viewTypeActivities.php?typeActivity=ServiceToHostInstitution">View All</a>
<?php
$serviceArray = getServices("ServiceToHostInstitution");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($serviceArray) . "</b> services found.</div>";
printServices($serviceArray, "ServiceToHostInstitution", $displayLimit);
?>
<hr/>
<span class="category_title">Service to Community</span> - <a href="viewTypeActivities.php?typeActivity=ServiceToCommunity">View All</a>
<?php
$serviceArray = getServices("ServiceToCommunity");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($serviceArray) . "</b> services found.</div>";
printServices($serviceArray, "ServiceToCommunity", $displayLimit);
?>
<hr/>
<span class="category_title">Training/Certification/Education</span> - <a href="viewTypeActivities.php?typeActivity=TrainingCertificationEducation">View All</a>
<?php
$serviceArray = getServices("TrainingCertificationEducation");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($serviceArray) . "</b> services found.</div>";
printServices($serviceArray, "TrainingCertificationEducation", $displayLimit);
?>
<hr/>
<span class="category_title">Conference Attendance</span> - <a href="viewTypeActivities.php?typeActivity=ConferenceAttendanceParticipation">View All</a>
<?php
$serviceArray = getServices("ConferenceAttendanceParticipation");
echo "<div align=\"right\" style=\"padding-right:25px; font-size:10px;\">Showing All of <b>" . count($serviceArray) . "</b> services found.</div>";
printServices($serviceArray, "ConferenceAttendanceParticipation", $displayLimit);
?>
</td>
</tr>
</table>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "Home";
$bg = array('jumbotron.jpg', 'jumbotron_2.jpg', 'jumbotron_3.jpg', 'jumbotron_4.jpg', 'jumbotron_5.jpg', 'jumbotron_6.jpg' ); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
require_once("rss/rsslib.php");
$url = "http://www.flpublicarchaeology.org/blog/feed/";
include('_header.php');
?>
<!-- page-content begins -->
<div class="container">
<div class="row">
<div class="jumbotron-main col-md-10 col-md-push-1 col-sm-12 hidden-xs" style="background: url(images/<?php echo $selectedBg; ?>) 40% no-repeat;">
</div>
</div><!-- /.row -->
<!-- Row -->
<div class="row">
<div class="col-md-4 col-sm-6 ">
<h2>Announcements</h2>
<div class="box-tab announcements-box">
<ul>
<li><a href="http://www.smithsonianmag.com/videos/category/3play_processed_94/underwater-archaeology-in-pensacola-bay/">UWF Archaeology featured on the Smithsonian website</a></li>
<li><a href="/documents/teacherOpportunities.pdf">Upcoming Teacher Opportunities</a></li>
<img class="scale" src="images/scale.png" width="34" height="100"/>
</ul>
</div>
<h2>Latest from the Blog</h2>
<section class="box-tab">
<?php echo RSS_Links($url, 3); ?>
</section>
</div> <!-- /.col -->
<div class="col-md-4 col-sm-6">
<h2>What is FPAN?</h2>
<div class="box-dash">
The Florida Public Archaeology Network's mission is to promote and facilitate the conservation,
study and public understanding of Florida's archaeological heritage through <a href="regions.php">regional centers</a>
throughout the state, each of which has its own website. To learn more about a region and to visit their site,
have a look at our <a href="regions.php">region map.</a>
</div>
<div class="callout-box regions">
<h1>Our Regions</h1>
<p>We operate through eight regional centers throughout the state.</p>
<a href="regions.php" class="btn btn-primary">Find yours!</a>
</div>
</div> <!-- /.col -->
<!-- Upcoming Events Box -->
<div class="col-md-4 col-md-push-0 col-sm-8 col-sm-push-2">
<h2>Upcoming Events</h2>
<div class="box-tab events-box">
<?php echoUpcomingEventsBox($regionsArray,6); ?>
</div>
</div> <!-- /.col -->
<!--<div class="col-md-4 col-md-pull-4 col-sm-6">
</div> /.col -->
</div><!-- /.row -->
<div class="row ">
<div class="col-md-4">
<div class="callout-box workshops">
<h1>Training Workshops</h1>
<p>Programs, workshops,
and informational presentations on a variety of topics. We can help out!
</p>
<a href="/workshops" class="btn btn-primary">Learn more</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="callout-box darc">
<h1>Destination: Archaeology</h1>
<p>Visit our museum in Pensacola!
</p>
<a href="http://destinationarchaeology.org" target="_blank" class="btn btn-primary">Learn more</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="callout-box resources">
<h1>Educational Resources</h1>
<p>Lesson plans and more to help you bring archaeology into the classroom.</p>
<a href="/resources" class="btn btn-primary">Learn more </a>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
<div class="row">
<div class="ad-box">
<div class="col-sm-6">
<a href="http://fpan.us/civilwar" target="_blank">
<img src="images/dcwButton.png" alt="Destination: Civil War" class="ad img-responsive">
</a>
</div>
<div class="col-sm-6">
<a href="http://destinationarchaeology.org" target="_blank">
<img src="images/darcButton.png" alt="Destination Archaeology Resource Center" class="ad img-responsive">
</a>
</div>
</div>
</div>
</div><!-- /.page-content /.container-fluid -->
<?php include('_footer.php'); ?><file_sep><?php include 'header.php' ?>
<nav>
<ul id="menu">
<li><a href="#">Add Activities</a>
<ul>
<li><a href="#">Activities and Events </a>
<ul>
<li><a href="publicOutreach.php?new=true">Public Outreach</a></li>
<li><a href="trainingWorkshops.php?new=true">Training / Workshops</a></li>
<li><a href="governmentAssistance.php?new=true">Government Assistance</a></li>
<li><a href="meeting.php?new=true">Meeting</a></li>
<li><a href="socialMedia.php?new=true">Social Media</a></li>
<li><a href="pressContact.php?new=true">Press Contact</a></li>
<li><a href="publication.php?new=true">Publication</a></li>
<li><a href="directMail.php?new=true">Direct Mail / Newsletter</a></li>
</ul>
</li>
<li><a href="#">Professional Service and Development</a>
<ul>
<li><a href="serviceToProfessionalSociety.php?new=true">Service to Professional Society</a></li>
<li><a href="serviceToHostInstitution.php?new=true">Service to Host Institution</a></li>
<li><a href="serviceToCommunity.php?new=true">Service to Community</a></li>
<li><a href="trainingCertificationEducation.php?new=true">Training / Certification / Education</a></li>
<li><a href="conferenceAttendanceParticipation.php?new=true">Conference Attendance / Participation</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="viewActivities.php">View Activities</a>
<ul>
<li><a href="#">Activities and Events</a>
<ul>
<li><a href="viewTypeActivities.php?typeActivity=PublicOutreach">Public Outreach</a></li>
<li><a href="viewTypeActivities.php?typeActivity=TrainingWorkshops">Training / Workshops</a></li>
<li><a href="viewTypeActivities.php?typeActivity=GovernmentAssistance">Government Assistance</a></li>
<li><a href="viewTypeActivities.php?typeActivity=Meeting">Meeting</a></li>
<li><a href="viewTypeActivities.php?typeActivity=SocialMedia">Social Media</a></li>
<li><a href="viewTypeActivities.php?typeActivity=PressContact">Press Contact</a></li>
<li><a href="viewTypeActivities.php?typeActivity=Publication">Publication</a></li>
<li><a href="viewTypeActivities.php?typeActivity=DirectMail">Direct Mail / Newsletter</a></li>
</ul>
</li>
<li><a href="#">Professional Service and Development</a>
<ul >
<li><a href="viewTypeActivities.php?typeActivity=ServiceToProfessionalSociety">Service to Professional Society</a></li>
<li><a href="viewTypeActivities.php?typeActivity=ServiceToHostInstitution">Service to Host Institution</a></li>
<li><a href="viewTypeActivities.php?typeActivity=ServiceToCommunity">Service to Community</a></li>
<li><a href="viewTypeActivities.php?typeActivity=TrainingCertificationEducation">Training / Certification / Education</a></li>
<li><a href="viewTypeActivities.php?typeActivity=ConferenceAttendanceParticipation">Conference Attendance / Participation</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="reporst.php">Generate Reports</a></li>
<li><a href="admin.php">Options</a></li>
</ul>
</nav>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
include 'header.php';
//Define table name for this form
$table = 'SocialMedia';
//if this is a new event, clear any potential leftover form data
if($_GET['new'])
$_SESSION['formVars'] = "";
//If event ID is supplied in URL, this event is being edited. Gather info from database and populate form.
if($_GET['id']){
setupEdit($_GET['id'], $table);
}
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true)
confirmSubmit($table);
//Form has been submitted but not confirmed. Display input values to check for accuracy
if(isset($_POST['submit'])&&!isset($_POST['confirmSubmission'])){
firstSubmit($_POST);
}elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="socialMedia" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Social Media</h2>
<p>This form is intended to be used for tracking statistics by month ONLY. <br/>
Entering data for any other time period will skew results.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Month / Year </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text" required="required">
/
<label for="element_1_1">MM</label>
</span><span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text" required="required">
<a class="red">*</a>
<label for="element_1_3">YYYY</label>
</span> </li>
<h3>Facebook</h3>
<li id="li_2" >
<label class="description" for="element_2">Current Total "Likes" </label>
<div>
<input id="element_2" name="fbLikes" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['fbLikes']; ?>" required="required"/>
<a class="red">*</a></div>
</li>
<li >
<label class="description" for="element_3">Monthly Posts</label>
<div>
<input id="element_3" name="fbPosts" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['fbPosts']; ?>" required="required"/>
<a class="red">*</a></div>
<p class="guidelines" id="guide_3"><small>Number of Facebook posts made during this month only.</small></p>
</li>
<li >
<label class="description" for="element_3">Monthly Reach </label>
<div>
<input id="element_3" name="fbReach" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['fbReach']; ?>" required="required"/>
<a class="red">*</a></div>
<p class="guidelines" id="guide_3"><small>Number of Facebook users reached this month only. <a href="images/fbReachGuide.png" target="_blank"> What's this? </a></small></p>
</li>
<h3> Twitter </h3>
<li >
<label class="description" for="element_4">Current Total Followers </label>
<div>
<input id="element_4" name="twitterFollowers" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['twitterFollowers']; ?>" required="required"/>
<a class="red">*</a></div>
</li>
<li id="li_5" >
<label class="description" for="element_5">Monthly Tweets</label>
<div>
<input id="element_5" name="twitterTweets" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['twitterTweets']; ?>" required="required"/>
<a class="red">*</a></div>
<p class="guidelines" id="guide_5"><small>Number of tweets made during this month only.</small></p>
</li>
<h3>Blog</h3>
<li id="li_6" >
<label class="description" for="element_6">Total Blog Posts (this month) </label>
<div>
<input id="element_6" name="blogPosts" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['blogPosts']; ?>"/>
</div>
<p class="guidelines" id="guide_6"><small>Total number of entries made via blog this month. If your region does not feature a blog, please leave this blank.</small></p>
</li>
<li id="li_7" >
<label class="description" for="element_6">Total Blog Visitors (this month) </label>
<div>
<input id="element_6" name="blogVisitors" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['blogVisitors']; ?>"/>
</div>
<p class="guidelines" id="guide_6"><small>Total number of unique visitors to your blog this month. If your region does not feature a blog, please leave this blank.</small></p>
</li>
<li id="li_2" >
<label class="description" for="element_2">Comments </label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium" onKeyDown="limitText(this.form.comments,this.form.countdown,2080);"
onKeyUp="limitText(this.form.comments,this.form.countdown,2080);" ><?php echo $formVars['comments']; ?></textarea>
<br/>
<font size="1">(Maximum characters: 2080)<br>
You have
<input readonly type="text" name="countdown" size="3" value="2080">
characters left.</font> </div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close if ?>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body></html><file_sep><?php
$upcomingEvents = mysqli_query($dblink, "SELECT * FROM $table
WHERE eventDateTimeStart >= CURDATE()
ORDER BY eventDateTimeStart ASC;");
?>
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th class="sm_header"><h1>Upcoming Events</h1> </th>
</tr>
<tr>
<td class="sm_mid">
<?php
if(mysqli_num_rows($upcomingEvents) != 0){
$numEvents = 5;
while(($event = mysqli_fetch_array($upcomingEvents)) && ($numEvents > 0)){
$timestampStart = strtotime($event['eventDateTimeStart']);
$eventDate = date('M, j', $timestampStart);
$linkDate = date('m/d/Y', $timestampStart);
$eventTimeStart = date('g:i a', $timestampStart);
echo "<p class=\"small\"><strong style=\"font-size:12px;\">" . $eventDate . " @ " . "</strong>"
. $eventTimeStart;
if($event['eventTimeEnd'] != null){
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventTimeEnd = date('g:i a', $timestampEnd);
echo " - " . $eventTimeEnd;
}
echo "<br/>";
echo "<a href=\"http://flpublicarchaeology.org/nwrc/eventDetail.php?eventID=$event[eventID]&eventDate=$linkDate\" target=\"_blank\"><em>" . stripslashes($event['title']) . "</em></a></p>";
$numEvents--;
}
}
else
echo '<p style="font-size:12px;" align="center">No events currently scheduled. <br/> Check back soon!</p>';
?>
</td>
</tr>
<tr>
<td class="sm_bottom"></td>
</tr>
</table>
<div align="right" style="padding-right:15px; width:220px; margin-left:720px;">
<div align="center">
<a href="http://unearthingflorida.org" target="_blank"><img src="http://destinationarchaeology.org/images/UnearthingFLoridaLogo.jpg" width="220" height="71" alt="Unearthing FL" /></a><br/>
<a href="http://www.nextexithistory.com" target="_blank"><img src="http://destinationarchaeology.org/images/NEH_logo.png" width="180" height="106" alt="Next Exit History" style="padding-top:5px;" /></a><br/>
<a href="http://www.flpublicarchaeology.org/civilwar" target="_blank"><img src="http://flpublicarchaeology.org/images/dcw.png" alt="Destination: Civil War" /></a>
<!--- TripAdvisor Widget -->
<div id="TA_virtualsticker532" class="TA_virtualsticker">
<ul id="W5qc6UFXE" class="TA_links xDGxNXnZy2">
<li id="SUubw82H" class="5flDFH49HUV">
<a target="_blank" href="http://www.tripadvisor.com/">
<img src="http://www.tripadvisor.com/img/cdsi/img2/branding/tripadvisor_sticker_logo_88x55-18961-2.png" alt="TripAdvisor"/>
</a>
</li>
</ul>
</div>
<script src="http://www.jscache.com/wejs?wtype=virtualsticker&uniq=532&lang=en_US&locationId=4601694"></script>
<!--- End TripAdvisor Widget -->
<p> </p>
</div>
<file_sep><?php
/**
* Supports showing slideshows of images in an album.
* <ul>
* <li>Plugin Option 'slideshow_size' -- Size of the images</li>
* <li>Plugin Option 'slideshow_mode' -- The player to be used</li>
* <li>Plugin Option 'slideshow_effect' -- The cycle effect</li>
* <li>Plugin Option 'slideshow_speed' -- How fast it runs</li>
* <li>Plugin Option 'slideshow_timeout' -- Transition time</li>
* <li>Plugin Option 'slideshow_showdesc' -- Allows the show to display image descriptions</li>
* </ul>
*
* The theme files <var>slideshow.php</var>, <var>slideshow.css</var>, and <var>slideshow-controls.png</var> must reside in the theme
* folder. If you are creating a custom theme, copy these files form the "default" theme of the Zenphoto
* distribution. Note that the Colorbox mode does not require these files as it is called on your theme's image.php and album.php direclty
* via the slideshow button. The Colorbox plugin must be enabled and setup for these pages.
*
* <b>NOTE:</b> The jQuery Cycle and the jQuery Colorbox modes do not support movie and audio files.
* In Colorbox mode there will be no slideshow button on the image page if that current image is a movie/audio file.
*
* Content macro support:
* Use [SLIDESHOW <albumname> <true/false for control] for showing a slideshow within image/album descriptions or Zenpage article and page contents.
* The slideshow size options must fit the space
* Notes:
* <ul>
* <li>The slideshow scripts must be enabled for the pages you wish to use it on.</li>
* <li>Use only one slideshow per page to avoid CSS conflicts.</li>
* <li>Also your theme might require extra CSS for this usage, especially the controls.</li>
* <li>This only creates a slideshow in jQuery mode, no matter how the mode is set.</li>
* </ul>
*
* @author <NAME> (acrylian), <NAME> (sbillard), <NAME> (dpeterson)
* @package plugins
* @subpackage media
*/
$plugin_is_filter = 9 | THEME_PLUGIN | ADMIN_PLUGIN;
$plugin_description = gettext("Adds a theme function to call a slideshow either based on jQuery (default) or Colorbox.");
$plugin_author = "<NAME> (acrylian), <NAME> (sbillard), <NAME> (dpeterson)";
$plugin_disable = (extensionEnabled('slideshow2')) ? sprintf(gettext('Only one slideshow plugin may be enabled. <a href="#%1$s"><code>%1$s</code></a> is already enabled.'), 'slideshow2') : '';
$option_interface = 'slideshow';
global $_zp_gallery, $_zp_gallery_page;
if ($_zp_gallery_page == 'slideshoe.php' || getOption('slideshow_' . $_zp_gallery->getCurrentTheme() . '_' . stripSuffix($_zp_gallery_page))) {
zp_register_filter('theme_head', 'slideshow::header_js');
}
zp_register_filter('content_macro', 'slideshow::macro');
//if (!OFFSET_PATH) {
//}
/**
* slideshow
*
*/
class slideshow {
function slideshow() {
global $_zp_gallery;
if (OFFSET_PATH == 2) {
//setOptionDefault('slideshow_size', '595');
setOptionDefault('slideshow_width', '595');
setOptionDefault('slideshow_height', '595');
setOptionDefault('slideshow_mode', 'jQuery');
setOptionDefault('slideshow_effect', 'fade');
setOptionDefault('slideshow_speed', '1000');
setOptionDefault('slideshow_timeout', '3000');
setOptionDefault('slideshow_showdesc', '');
setOptionDefault('slideshow_colorbox_transition', 'fade');
// incase the flowplayer has not been enabled!!!
setOptionDefault('slideshow_colorbox_imagetype', 'sizedimage');
setOptionDefault('slideshow_colorbox_imagetitle', 1);
cacheManager::deleteThemeCacheSizes('slideshow');
cacheManager::addThemeCacheSize('slideshow', NULL, getOption('slideshow_width'), getOption('slideshow_height'), NULL, NULL, NULL, NULL, NULL, NULL, NULL, true);
}
}
function getOptionsSupported() {
$options = array(gettext('Mode') => array('key' => 'slideshow_mode', 'type' => OPTION_TYPE_SELECTOR,
'order' => 0,
'selections' => array(gettext("jQuery Cycle") => "jQuery", gettext("jQuery Colorbox") => "colorbox"),
'desc' => gettext('<em>jQuery Cycle</em> for slideshow using the jQuery Cycle plugin<br /><em>jQuery Colorbox</em> for slideshow using Colorbox (Colorbox plugin required).<br />NOTE: The jQuery Colorbox mode is attached to the link the printSlideShowLink() function prints and can neither be called directly nor used on the slideshow.php theme page.')),
gettext('Speed') => array('key' => 'slideshow_speed', 'type' => OPTION_TYPE_TEXTBOX,
'order' => 1,
'desc' => gettext("Speed of the transition in milliseconds."))
);
foreach (getThemeFiles(array('404.php', 'themeoptions.php', 'theme_description.php', 'slideshow.php', 'functions.php', 'password.php', 'sidebar.php', 'register.php', 'contact.php')) as $theme => $scripts) {
$list = array();
foreach ($scripts as $script) {
$list[$script] = 'slideshow_' . $theme . '_' . stripSuffix($script);
}
$opts[$theme] = array('key' => 'slideshow_' . $theme . '_scripts', 'type' => OPTION_TYPE_CHECKBOX_ARRAY,
'checkboxes' => $list,
'desc' => gettext('The scripts for which the slideshow is enabled. {Should have been set by the themes!}')
);
}
$options = array_merge($options, $opts);
switch (getOption('slideshow_mode')) {
case 'jQuery':
$options = array_merge($options, array(gettext('Slide width') => array('key' => 'slideshow_width', 'type' => OPTION_TYPE_TEXTBOX,
'order' => 5,
'desc' => gettext("Width of the images in the slideshow.")),
gettext('Slide height') => array('key' => 'slideshow_height', 'type' => OPTION_TYPE_TEXTBOX,
'order' => 6,
'desc' => gettext("Height of the images in the slideshow.")),
gettext('Cycle Effect') => array('key' => 'slideshow_effect', 'type' => OPTION_TYPE_SELECTOR,
'order' => 2,
'selections' => array(gettext('fade') => "fade", gettext('shuffle') => "shuffle", gettext('zoom') => "zoom", gettext('slide X') => "slideX", gettext('slide Y') => "slideY", gettext('scroll up') => "scrollUp", gettext('scroll down') => "scrollDown", gettext('scroll left') => "scrollLeft", gettext('scroll right') => "scrollRight"),
'desc' => gettext("The cycle slide effect to be used.")),
gettext('Timeout') => array('key' => 'slideshow_timeout', 'type' => OPTION_TYPE_TEXTBOX,
'order' => 3,
'desc' => gettext("Milliseconds between slide transitions (0 to disable auto advance.)")),
gettext('Description') => array('key' => 'slideshow_showdesc', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 4,
'desc' => gettext("Check if you want to show the image’s description below the slideshow."))
));
break;
case 'colorbox':
$options = array_merge($options, array(gettext('Colorbox transition') => array('key' => 'slideshow_colorbox_transition', 'type' => OPTION_TYPE_SELECTOR,
'order' => 2,
'selections' => array(gettext('elastic') => "elastic", gettext('fade') => "fade", gettext('none') => "none"),
'desc' => gettext("The Colorbox transition slide effect to be used.")),
gettext('Colorbox image type') => array('key' => 'slideshow_colorbox_imagetype', 'type' => OPTION_TYPE_SELECTOR,
'order' => 3,
'selections' => array(gettext('full image') => "fullimage", gettext('sized image') => "sizedimage"),
'desc' => gettext("The image type you wish to use for the Colorbox. If you choose “sized image” the slideshow width value will be used for the longest side of the image.")),
gettext('Colorbox image title') => array('key' => 'slideshow_colorbox_imagetitle', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 4,
'desc' => gettext("If the image title should be shown at the bottom of the Colorbox."))
));
if (getOption('slideshow_colorbox_imagetype') == 'sizedimage') {
$options = array_merge($options, array(gettext('Slide width') => array('key' => 'slideshow_width', 'type' => OPTION_TYPE_TEXTBOX,
'order' => 3.5,
'desc' => gettext("Width of the images in the slideshow."))
));
}
break;
}
return $options;
}
function handleOption($option, $currentValue) {
}
static function getPlayer($album, $controls = false, $width = NULL, $height = NULL) {
$albumobj = NULL;
if (!empty($album)) {
$albumobj = newAlbum($album, NULL, true);
}
if (is_object($albumobj) && $albumobj->loaded) {
$returnpath = $albumobj->getLink();
return slideshow::getShow(false, false, $albumobj, NULL, $width, $height, false, false, false, $controls, $returnpath, 0);
} else {
return '<div class="errorbox" id="message"><h2>' . gettext('Invalid slideshow album name!') . '</h2></div>';
}
}
static function getShow($heading, $speedctl, $albumobj, $imageobj, $width, $height, $crop, $shuffle, $linkslides, $controls, $returnpath, $imagenumber) {
global $_zp_gallery, $_zp_gallery_page;
setOption('slideshow_' . $_zp_gallery->getCurrentTheme() . '_' . stripSuffix($_zp_gallery_page), 1);
if (!$albumobj->isMyItem(LIST_RIGHTS) && !checkAlbumPassword($albumobj)) {
return '<div class="errorbox" id="message"><h2>' . gettext('This album is password protected!') . '</h2></div>';
}
$slideshow = '';
$numberofimages = $albumobj->getNumImages();
// setting the image size
if ($width) {
$wrapperwidth = $width;
} else {
$width = $wrapperwidth = getOption("slideshow_width");
}
if ($height) {
$wrapperheight = $height;
} else {
$height = $wrapperheight = getOption("slideshow_height");
}
if ($numberofimages == 0) {
return '<div class="errorbox" id="message"><h2>' . gettext('No images for the slideshow!') . '</h2></div>';
}
$option = getOption("slideshow_mode");
// jQuery Cycle slideshow config
// get slideshow data
$showdesc = getOption("slideshow_showdesc");
// slideshow display section
$validtypes = array('jpg', 'jpeg', 'gif', 'png', 'mov', '3gp');
$slideshow .= '
<script type="text/javascript">
// <!-- <![CDATA[
$(document).ready(function(){
$(function() {
var ThisGallery = "' . html_encode($albumobj->getTitle()) . '";
var ImageList = new Array();
var TitleList = new Array();
var DescList = new Array();
var ImageNameList = new Array();
var DynTime=(' . (int) getOption("slideshow_timeout") . ');
';
$images = $albumobj->getImages(0);
if ($shuffle) {
shuffle($images);
}
for ($imgnr = 0, $cntr = 0, $idx = $imagenumber; $imgnr < $numberofimages; $imgnr++, $idx++) {
if (is_array($images[$idx])) {
$filename = $images[$idx]['filename'];
$album = newAlbum($images[$idx]['folder']);
$image = newImage($album, $filename);
} else {
$filename = $images[$idx];
$image = newImage($albumobj, $filename);
}
$ext = slideshow::is_valid($filename, $validtypes);
if ($ext) {
if ($crop) {
$img = $image->getCustomImage(NULL, $width, $height, $width, $height, NULL, NULL, NULL, NULL);
} else {
$maxwidth = $width;
$maxheight = $height;
getMaxSpaceContainer($maxwidth, $maxheight, $image);
$img = $image->getCustomImage(NULL, $maxwidth, $maxheight, NULL, NULL, NULL, NULL, NULL, NULL);
}
$slideshow .= 'ImageList[' . $cntr . '] = "' . $img . '";' . "\n";
$slideshow .= 'TitleList[' . $cntr . '] = "' . js_encode($image->getTitle()) . '";' . "\n";
if ($showdesc) {
$desc = $image->getDesc();
$desc = str_replace("\r\n", '<br />', $desc);
$desc = str_replace("\r", '<br />', $desc);
$slideshow .= 'DescList[' . $cntr . '] = "' . js_encode($desc) . '";' . "\n";
} else {
$slideshow .= 'DescList[' . $cntr . '] = "";' . "\n";
}
if ($idx == $numberofimages - 1) {
$idx = -1;
}
$slideshow .= 'ImageNameList[' . $cntr . '] = "' . urlencode($filename) . '";' . "\n";
$cntr++;
}
}
$slideshow .= "\n";
$numberofimages = $cntr;
$slideshow .= '
var countOffset = ' . $imagenumber . ';
var totalSlideCount = ' . $numberofimages . ';
var currentslide = 2;
function onBefore(curr, next, opts) {
if (opts.timeout != DynTime) {
opts.timeout = DynTime;
}
if (!opts.addSlide)
return;
var currentImageNum = currentslide;
currentslide++;
if (currentImageNum == totalSlideCount) {
opts.addSlide = null;
return;
}
var relativeSlot = (currentslide + countOffset) % totalSlideCount;
if (relativeSlot == 0) {relativeSlot = totalSlideCount;}
var htmlblock = "<span class=\"slideimage\"><h4><strong>" + ThisGallery + ":</strong> ";
htmlblock += TitleList[currentImageNum] + " (" + relativeSlot + "/" + totalSlideCount + ")</h4>";
';
if ($linkslides) {
if (MOD_REWRITE) {
$slideshow .= 'htmlblock += "<a href=\"' . pathurlencode($albumobj->name) . '/"+ImageNameList[currentImageNum]+"' . getOption('mod_rewrite_image_suffix') . '\">";';
} else {
$slideshow .= 'htmlblock += "<a href=\"index.php?album=' . pathurlencode($albumobj->name) . '&image="+ImageNameList[currentImageNum]+"\">";';
}
}
$slideshow .= ' htmlblock += "<img src=\"" + ImageList[currentImageNum] + "\"/>";';
if ($linkslides) {
$slideshow .= ' htmlblock += "</a>";';
}
$slideshow .= 'htmlblock += "<p class=\"imgdesc\">" + DescList[currentImageNum] + "</p></span>";';
$slideshow .= 'opts.addSlide(htmlblock);';
$slideshow .= '}';
$slideshow .= '
function onAfter(curr, next, opts){
';
if (!$albumobj->isMyItem(LIST_RIGHTS)) {
$slideshow .= '
//Only register at hit count the first time the image is viewed.
if ($(next).attr("viewed") != 1) {
$.get("' . FULLWEBPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/slideshow/slideshow-counter.php?album=' . pathurlencode($albumobj->name) . '&img="+ImageNameList[opts.currSlide]);
$(next).attr("viewed", 1 );
}
';
}
$slideshow .='}';
$slideshow .='
$("#slides").cycle({
fx: "' . getOption("slideshow_effect") . '",
speed: "' . getOption("slideshow_speed") . '",
timeout: DynTime,
next: "#next",
prev: "#prev",
cleartype: 1,
before: onBefore,
after: onAfter
});
$("#speed").change(function () {
DynTime = this.value;
return false;
});
$("#pause").click(function() { $("#slides").cycle("pause"); return false; });
$("#play").click(function() { $("#slides").cycle("resume"); return false; });
});
}); // Documentready()
// ]]> -->
</script>
<div id="slideshow" style="height:' . ($wrapperheight + 40) . 'px; width:' . $wrapperwidth . 'px;">
';
// 7/21/08dp
if ($speedctl) {
$slideshow .= '<div id="speedcontrol">'; // just to keep it away from controls for sake of this demo
$minto = getOption("slideshow_speed");
while ($minto % 500 != 0) {
$minto += 100;
if ($minto > 10000) {
break;
} // emergency bailout!
}
$dflttimeout = (int) getOption("slideshow_timeout");
/* don't let min timeout = speed */
$thistimeout = ($minto == getOption("slideshow_speed") ? $minto + 250 : $minto);
$slideshow .= 'Select Speed: <select id="speed" name="speed">';
while ($thistimeout <= 60000) { // "around" 1 minute :)
$slideshow .= "<option value=$thistimeout " . ($thistimeout == $dflttimeout ? " selected='selected'>" : ">") . round($thistimeout / 1000, 1) . " sec</option>";
/* put back timeout to even increments of .5 */
if ($thistimeout % 500 != 0) {
$thistimeout -= 250;
}
$thistimeout += ($thistimeout < 1000 ? 500 : ($thistimeout < 10000 ? 1000 : 5000));
}
$slideshow .= '</select> </div>';
}
if ($controls) {
$slideshow .= '
<div id="controls">
<div>
<a href="#" id="prev" title="' . gettext("Previous") . '"></a>
<a href="' . html_encode($returnpath) . '" id="stop" title="' . gettext("Stop and return to album or image page") . '"></a>
<a href="#" id="pause" title="' . gettext("Pause (to stop the slideshow without returning)") . '"></a>
<a href="#" id="play" title="' . gettext("Play") . '"></a>
<a href="#" id="next" title="' . gettext("Next") . '"></a>
</div>
</div>
';
}
$slideshow .= '
<div id="slides" class="pics">
';
if ($cntr > 1)
$cntr = 1;
for ($imgnr = 0, $idx = $imagenumber; $imgnr <= $cntr; $idx++) {
if ($idx >= $numberofimages) {
$idx = 0;
}
if (is_array($images[$idx])) {
$folder = $images[$idx]['folder'];
$dalbum = newAlbum($folder);
$filename = $images[$idx]['filename'];
$image = newImage($dalbum, $filename);
$imagepath = FULLWEBPATH . ALBUM_FOLDER_EMPTY . $folder . "/" . $filename;
} else {
$folder = $albumobj->name;
$filename = $images[$idx];
//$filename = $animage;
$image = newImage($albumobj, $filename);
$imagepath = FULLWEBPATH . ALBUM_FOLDER_EMPTY . $folder . "/" . $filename;
}
$ext = slideshow::is_valid($filename, $validtypes);
if ($ext) {
$imgnr++;
$slideshow .= '<span class="slideimage"><h4><strong>' . $albumobj->getTitle() . gettext(":") . '</strong> ' . $image->getTitle() . ' (' . ($idx + 1) . '/' . $numberofimages . ')</h4>';
if ($ext == "3gp") {
$slideshow .= '</a>
<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="352" height="304" codebase="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="' . pathurlencode(internalToFilesystem($imagepath)) . '"/>
<param name="autoplay" value="false" />
<param name="type" value="video/quicktime" />
<param name="controller" value="true" />
<embed src="' . pathurlencode(internalToFilesystem($imagepath)) . '" width="352" height="304" autoplay="false" controller"true" type="video/quicktime"
pluginspage="http://www.apple.com/quicktime/download/" cache="true"></embed>
</object>
<a>';
} elseif ($ext == "mov") {
$slideshow .= '</a>
<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="640" height="496" codebase="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="' . pathurlencode(internalToFilesystem($imagepath)) . '"/>
<param name="autoplay" value="false" />
<param name="type" value="video/quicktime" />
<param name="controller" value="true" />
<embed src="' . pathurlencode(internalToFilesystem($imagepath)) . '" width="640" height="496" autoplay="false" controller"true" type="video/quicktime"
pluginspage="http://www.apple.com/quicktime/download/" cache="true"></embed>
</object>
<a>';
} else {
if ($linkslides)
$slideshow .= '<a href="' . html_encode($image->getLink()) . '">';
if ($crop) {
$img = $image->getCustomImage(NULL, $width, $height, $width, $height, NULL, NULL, NULL, NULL);
} else {
$maxwidth = $width;
$maxheight = $height;
getMaxSpaceContainer($maxwidth, $maxheight, $image);
$img = $image->getCustomImage(NULL, $maxwidth, $maxheight, NULL, NULL, NULL, NULL, NULL, NULL);
}
$slideshow .= '<img src="' . html_encode(pathurlencode($img)) . '" alt="" />';
if ($linkslides)
$slideshow .= '</a>';
}
if ($showdesc) {
$desc = $image->getDesc();
$desc = str_replace("\r\n", '<br />', $desc);
$desc = str_replace("\r", '<br />', $desc);
$slideshow .= '<p class="imgdesc">' . $desc . '</p>';
}
$slideshow .= '</span>';
}
}
$slideshow .= '
</div>
</div>
';
return $slideshow;
}
static function macro($macros) {
$macros['SLIDESHOW'] = array(
'class' => 'function',
'params' => array('string', 'bool*', 'int*', 'int*'),
'value' => 'slideshow::getPlayer',
'owner' => 'slideshow',
'desc' => gettext('provide the album name as %1 and (optionally) <code>true</code> (or <code>false</code>) as %2 to show (hide) controls. Hiding the controls is the default. Width(%3) and height(%4) may also be specified to override the defaults.')
);
return $macros;
}
static function header_js() {
$theme = getCurrentTheme();
$css = SERVERPATH . '/' . THEMEFOLDER . '/' . internalToFilesystem($theme) . '/slideshow.css';
if (file_exists($css)) {
$css = WEBPATH . '/' . THEMEFOLDER . '/' . $theme . '/slideshow.css';
} else {
$css = WEBPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/slideshow/slideshow.css';
}
?>
<script src="<?php echo FULLWEBPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER ?>/slideshow/jquery.cycle.all.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?php echo $css; ?>" />
<?php
}
/**
* Returns the file extension if the item passed is displayable by the player
*
* @param mixed $image either an image object or the filename of an image.
* @param array $valid_types list of the types we will accept
* @return string;
*/
static function is_valid($image, $valid_types) {
if (is_object($image))
$image = $image->filename;
$ext = getSuffix($image);
if (in_array($ext, $valid_types)) {
return $ext;
}
return false;
}
}
if ($plugin_disable) {
enableExtension('slideshow', 0);
}
if (extensionEnabled('slideshow')) {
$slideshow_instance = 0;
/**
* Prints a link to call the slideshow (not shown if there are no images in the album)
* To be used on album.php and image.php
* A CSS id names 'slideshowlink' is attached to the link so it can be directly styled.
*
* If the mode is set to "jQuery Colorbox" and the Colorbox plugin is enabled this link starts a Colorbox slideshow
* from a hidden HTML list of all images in the album. On album.php it starts with the first always, on image.php with the current image.
*
* @param string $linktext Text for the link
* @param string $linkstyle Style of Text for the link
*/
function printSlideShowLink($linktext = NULL, $linkstyle = Null) {
global $_zp_gallery, $_zp_current_image, $_zp_current_album, $_zp_current_search, $slideshow_instance, $_zp_gallery_page;
if (is_null($linktext)) {
$linktext = gettext('View Slideshow');
}
if (empty($_GET['page'])) {
$pagenr = 1;
} else {
$pagenr = sanitize_numeric($_GET['page']);
}
$slideshowhidden = '';
$numberofimages = 0;
if (in_context(ZP_SEARCH)) {
$imagenumber = '';
$imagefile = '';
$albumnr = 0;
$slideshowlink = rewrite_path(_PAGE_ . '/slideshow', "index.php?p=slideshow");
$slideshowhidden = '<input type="hidden" name="preserve_search_params" value="' . html_encode($_zp_current_search->getSearchParams()) . '" />';
} else {
if (in_context(ZP_IMAGE)) {
$imagenumber = imageNumber();
$imagefile = $_zp_current_image->filename;
} else {
$imagenumber = '';
$imagefile = '';
}
if (in_context(ZP_SEARCH_LINKED)) {
$albumnr = -$_zp_current_album->getID();
$slideshowhidden = '<input type="hidden" name="preserve_search_params" value="' . html_encode($_zp_current_search->getSearchParams()) . '" />';
} else {
$albumnr = $_zp_current_album->getID();
}
if ($albumnr) {
$slideshowlink = rewrite_path(pathurlencode($_zp_current_album->getFileName()) . '/' . _PAGE_ . '/slideshow', "index.php?p=slideshow&album=" . urlencode($_zp_current_album->getFileName()));
} else {
$slideshowlink = rewrite_path(_PAGE_ . '/slideshow', "index.php?p=slideshow");
$slideshowhidden = '<input type="hidden" name="favorites_page" value="1" />' . "\n" . '<input type="hidden" name="title" value="' . $_myFavorites->instance . '" />';
}
}
$numberofimages = getNumImages();
$option = getOption('slideshow_mode');
switch ($option) {
case 'jQuery':
if ($numberofimages > 1) {
?>
<form name="slideshow_<?php echo $slideshow_instance; ?>" method="post" action="<?php echo zp_apply_filter('getLink', $slideshowlink, 'slideshow.php', NULL); ?>">
<?php echo $slideshowhidden; ?>
<input type="hidden" name="pagenr" value="<?php echo html_encode($pagenr); ?>" />
<input type="hidden" name="albumid" value="<?php echo $albumnr; ?>" />
<input type="hidden" name="numberofimages" value="<?php echo $numberofimages; ?>" />
<input type="hidden" name="imagenumber" value="<?php echo $imagenumber; ?>" />
<input type="hidden" name="imagefile" value="<?php echo html_encode($imagefile); ?>" />
<?php if (!empty($linkstyle)) echo '<p style="' . $linkstyle . '">'; ?>
<a class="slideshowlink" id="slideshowlink_<?php echo $slideshow_instance; ?>" href="javascript:document.slideshow_<?php echo $slideshow_instance; ?>.submit()"><?php echo $linktext; ?></a>
<?php if (!empty($linkstyle)) echo '</p>'; ?>
</form>
<?php
}
$slideshow_instance++;
break;
case 'colorbox':
$theme = $_zp_gallery->getCurrentTheme();
$script = stripSuffix($_zp_gallery_page);
if (!getOption('colorbox_' . $theme . '_' . $script)) {
setOptionDefault('colorbox_' . $theme . '_' . $script, 1);
$themes = $_zp_gallery->getThemes();
?>
<div class="errorbox"><?php printf(gettext('Slideshow not available because colorbox is not enabled on %1$s <em>%2$s</em> pages.'), $themes[$theme]['name'], $script); ?></div>
<?php
break;
}
if ($numberofimages > 1) {
if ((in_context(ZP_SEARCH_LINKED) && !in_context(ZP_ALBUM_LINKED)) || in_context(ZP_SEARCH) && is_null($_zp_current_album)) {
$images = $_zp_current_search->getImages(0);
} else {
$images = $_zp_current_album->getImages(0);
}
$count = '';
?>
<script type="text/javascript">
$(document).ready(function() {
$("a[rel='slideshow']").colorbox({
slideshow: true,
loop: true,
transition: '<?php echo getOption('slideshow_colorbox_transition'); ?>',
slideshowSpeed: <?php echo getOption('slideshow_speed'); ?>,
slideshowStart: '<?php echo gettext("start slideshow"); ?>',
slideshowStop: '<?php echo gettext("stop slideshow"); ?>',
previous: '<?php echo gettext("prev"); ?>',
next: '<?php echo gettext("next"); ?>',
close: '<?php echo gettext("close"); ?>',
current: '<?php printf(gettext('image %1$s of %2$s'), '{current}', '{total}'); ?>',
maxWidth: '98%',
maxHeight: '98%',
photo: true
});
});
</script>
<?php
foreach ($images as $image) {
if (is_array($image)) {
$suffix = getSuffix($image['filename']);
} else {
$suffix = getSuffix($image);
}
$suffixes = array('jpg', 'jpeg', 'gif', 'png');
if (in_array($suffix, $suffixes)) {
$count++;
if (is_array($image)) {
$albobj = newAlbum($image['folder']);
$imgobj = newImage($albobj, $image['filename']);
} else {
$imgobj = newImage($_zp_current_album, $image);
}
if (in_context(ZP_SEARCH_LINKED) || $_zp_gallery_page != 'image.php') {
if ($count == 1) {
$style = '';
} else {
$style = ' style="display:none"';
}
} else {
if ($_zp_current_image->filename == $image) {
$style = '';
} else {
$style = ' style="display:none"';
}
}
switch (getOption('slideshow_colorbox_imagetype')) {
case 'fullimage':
$imagelink = getFullImageURL($imgobj);
break;
case 'sizedimage':
$imagelink = $imgobj->getCustomImage(getOption("slideshow_width"), NULL, NULL, NULL, NULL, NULL, NULL, false, NULL);
break;
}
$imagetitle = '';
if (getOption('slideshow_colorbox_imagetitle')) {
$imagetitle = html_encode(getBare($imgobj->getTitle()));
}
?>
<a href="<?php echo html_encode(pathurlencode($imagelink)); ?>" rel="slideshow"<?php echo $style; ?> title="<?php echo $imagetitle; ?>"><?php echo $linktext; ?></a>
<?php
}
}
}
break;
}
}
/**
* Gets the slideshow using the {@link http://http://www.malsup.com/jquery/cycle/ jQuery plugin Cycle}
*
* NOTE: The jQuery mode does not support movie and audio files anymore. If you need to show them please use the Flash mode.
* Also note that this function is not used for the Colorbox mode!
*
* @param bool $heading set to true (default) to emit the slideshow breadcrumbs in flash mode
* @param bool $speedctl controls whether an option box for controlling transition speed is displayed
* @param obj $albumobj The object of the album to show the slideshow of. If set this overrides the POST data of the printSlideShowLink()
* @param obj $imageobj The object of the image to start the slideshow with. If set this overrides the POST data of the printSlideShowLink(). If not set the slideshow starts with the first image of the album.
* @param int $width The width of the images (jQuery mode). If set this overrides the size the slideshow_width plugin option that otherwise is used.
* @param int $height The heigth of the images (jQuery mode). If set this overrides the size the slideshow_height plugin option that otherwise is used.
* @param bool $crop Set to true if you want images cropped width x height (jQuery mode only)
* @param bool $shuffle Set to true if you want random (shuffled) order
* @param bool $linkslides Set to true if you want the slides to be linked to their image pages (jQuery mode only)
* @param bool $controls Set to true (default) if you want the slideshow controls to be shown (might require theme CSS changes if calling outside the slideshow.php page) (jQuery mode only)
*
*/
/**
* Prints the slideshow using the {@link http://http://www.malsup.com/jquery/cycle/ jQuery plugin Cycle}
*
* Two ways to use:
* a) Use on your theme's slideshow.php page and called via printSlideShowLink():
* If called from image.php it starts with that image, called from album.php it starts with the first image (jQuery only)
* To be used on slideshow.php only and called from album.php or image.php.
*
* b) Calling directly via printSlideShow() function (jQuery mode)
* Place the printSlideShow() function where you want the slideshow to appear and set create an album object for $albumobj and if needed an image object for $imageobj.
* The controls are disabled automatically.
*
* NOTE: The jQuery mode does not support movie and audio files anymore. If you need to show them please use the Flash mode.
* Also note that this function is not used for the Colorbox mode!
*
* @param bool $heading set to true (default) to emit the slideshow breadcrumbs in flash mode
* @param bool $speedctl controls whether an option box for controlling transition speed is displayed
* @param obj $albumobj The object of the album to show the slideshow of. If set this overrides the POST data of the printSlideShowLink()
* @param obj $imageobj The object of the image to start the slideshow with. If set this overrides the POST data of the printSlideShowLink(). If not set the slideshow starts with the first image of the album.
* @param int $width The width of the images (jQuery mode). If set this overrides the size the slideshow_width plugin option that otherwise is used.
* @param int $height The heigth of the images (jQuery mode). If set this overrides the size the slideshow_height plugin option that otherwise is used.
* @param bool $crop Set to true if you want images cropped width x height (jQuery mode only)
* @param bool $shuffle Set to true if you want random (shuffled) order
* @param bool $linkslides Set to true if you want the slides to be linked to their image pages (jQuery mode only)
* @param bool $controls Set to true (default) if you want the slideshow controls to be shown (might require theme CSS changes if calling outside the slideshow.php page) (jQuery mode only)
*
*/
function printSlideShow($heading = true, $speedctl = false, $albumobj = NULL, $imageobj = NULL, $width = NULL, $height = NULL, $crop = false, $shuffle = false, $linkslides = false, $controls = true) {
global $_myFavorites, $_zp_conf_vars;
if (!isset($_POST['albumid']) AND ! is_object($albumobj)) {
return '<div class="errorbox" id="message"><h2>' . gettext('Invalid linking to the slideshow page.') . '</h2></div>';
}
//getting the image to start with
if (!empty($_POST['imagenumber']) AND ! is_object($imageobj)) {
$imagenumber = sanitize_numeric($_POST['imagenumber']) - 1; // slideshows starts with 0, but zp with 1.
} elseif (is_object($imageobj)) {
$imagenumber = $imageobj->getIndex();
} else {
$imagenumber = 0;
}
// set pagenumber to 0 if not called via POST link
if (isset($_POST['pagenr'])) {
$pagenumber = sanitize_numeric($_POST['pagenr']);
} else {
$pagenumber = 1;
}
// getting the number of images
if (!empty($_POST['numberofimages'])) {
$numberofimages = sanitize_numeric($_POST['numberofimages']);
} elseif (is_object($albumobj)) {
$numberofimages = $albumobj->getNumImages();
} else {
$numberofimages = 0;
}
if ($imagenumber < 2 || $imagenumber > $numberofimages) {
$imagenumber = 0;
}
//getting the album to show
if (!empty($_POST['albumid']) && !is_object($albumobj)) {
$albumid = sanitize_numeric($_POST['albumid']);
} elseif (is_object($albumobj)) {
$albumid = $albumobj->getID();
} else {
$albumid = 0;
}
if (isset($_POST['preserve_search_params'])) { // search page
$search = new SearchEngine();
$params = sanitize($_POST['preserve_search_params']);
$search->setSearchParams($params);
$searchwords = $search->getSearchWords();
$searchdate = $search->getSearchDate();
$searchfields = $search->getSearchFields(true);
$page = $search->page;
$returnpath = getSearchURL($searchwords, $searchdate, $searchfields, $page);
$albumobj = new AlbumBase(NULL, false);
$albumobj->setTitle(gettext('Search'));
$albumobj->images = $search->getImages(0);
} else {
if (isset($_POST['favorites_page'])) {
$albumobj = $_myFavorites;
$returnpath = $_myFavorites->getLink($pagenumber);
} else {
$albumq = query_single_row("SELECT title, folder FROM " . prefix('albums') . " WHERE id = " . $albumid);
$albumobj = newAlbum($albumq['folder']);
if (empty($_POST['imagenumber'])) {
$returnpath = $albumobj->getLink($pagenumber);
} else {
$image = newImage($albumobj, sanitize($_POST['imagefile']));
$returnpath = $image->getLink();
}
}
}
echo slideshow::getShow($heading, $speedctl, $albumobj, $imageobj, $width, $height, $crop, $shuffle, $linkslides, $controls, $returnpath, $imagenumber);
}
}
?>
<file_sep><?php
$pageTitle = "Education";
include('_header.php');
?>
<div class="page-content container">
<div class="row">
<div class="page-header"><h1>Education</h1></div>
<div class="col-sm-10 col-sm-push-1 box-tab">
<p>Ever wanted to bring your students to a real archaeological facility? Our museum and headquarters classroom is just the place for you! Field trips to the Destination Archaeology Resource Center and lab are designed for 3-12 grade; K-2 grade and adult programs also available. The program lasts approximately 1.5 hours and includes a powerpoint presentation called Introduction to Archaeology, a visit to Archaeology Lab or to a real archaeological site, and a guided tour of the museum exhibit where students will learn about the history and archaeology of Florida. </p>
<div class="text-center">
<div class="image">
<img src="images/kids_museum2.jpg" alt="Kids visiting the Destination Archaeology Resource Center" class="img-responsive">
</div>
</div>
<h3>Planning Your Trip</h3>
<p>Contact DARC staff at 850 595-0050 EXT 107 or email Mike at <a href="mailto:<EMAIL>"><EMAIL></a> with at least two full weeks advance notice prior to the desired date and time of your group’s visit. Have at least two dates in mind prior to calling in case we cannot accommodate your group visit on the date and time you desire due to possible scheduling conflicts. We will try our best to schedule a date and time most convenient for you. Keep in mind that tours are offered Monday-Friday. Once staff has confirmed the date and time of your scheduled trip, a confirmation email will be sent to you with all the tour information. </p>
<h3>Fees</h3>
<p>$2.00 suggested donation per student and chaperone. This donation to the UWF Foundation/FPAN will go to support our educational programs. Teachers and bus drivers are free. Check or cash accepted. </p>
<h3>Capacity</h3>
<p>Groups of at least 10 qualify for an educational program. Due to space limitations, group number cannot exceed 65 persons per visit (including students, parents, chaperones, teachers, and drivers) . If your group exceeds the maximum number we can schedule the group for more than one visit by dividing them and having them arrive on different days or times.</p>
<ul>
<li>10-30 students - Stay in 1 Group</li>
<li>30-65 students - Divide into 2 or 3 Groups</li>
</ul>
<p>If your group has less than 10, you are welcome to visit the museum exhibit during normal operating hours (Monday-Saturday 10 AM – 4 PM) free of charge at your leisure. Although you will not qualify for a field trip we offer several programs throughout the year.</p>
<h3>Tour Length and Time</h3>
<p>Our educational program for groups last approximately 1.5 hours. Tours slots are available Monday – Friday from 10 AM – 11:30 AM or 12:00 PM -1:30 PM. Each program will include 3 sections: An Introduction to Archaeology presentation in the classroom, a visit to a real Archaeology Lab, and a guided tour of the museum exhibit.</p>
<p>For FREE lesson plans visit <a href="http://fpan.us/resources">fpan.us/resources</a></p>
</div>
</div>
</div><!-- /.page-content /.container -->
<?php include('_footer.php'); ?>
<file_sep><?php
$pageTitle = "Then and Now: Life Along the New River";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Then and Now: Life Along the New River</h1></th>
</tr>
<tr>
<td class="table_mid">
<div id="exhibit">
<?php include 'nav.php'?>
<h2 align="center">Trade & Commerce</h2>
<p><strong>The Seminoles’ knowledge of waterways between the Everglades and the New River energized the economy of early Fort Lauderdale.</strong> The relationship between pioneer settlers and the Seminoles in the 1800’s established one of the first businesses in the region, and provided a foundation for trade and commerce on the New River.
<br />
<br />
<img src="images/exhibit27.jpg" style="float:right; margin-left:10px" alt="<NAME>'s sons and unidentified young girl, admiring bicycles outside
of Stranahan's Trading Post.<br/>
Image courtesy of Fort Lauderdale Historical Society" />
In 1894, <NAME> opened the first trading post and general store in the area. At the trading post, Frank, his wife Ivy, and the Seminoles established business and personal connections that survived for decades. For an expedition to Stranahan’s post, Seminole families would travel up the river from the Everglades. The canoes were filled to the brim with people, trade goods, cooking tools, and even the family dog. Ivy would greet the Seminole children at the door, offering them fruit or sweets. While the young ones were occupied playing on the store’s grounds, the Seminoles and Stranahan would conduct business. Frank paid cash for the items that the Seminoles brought to the store.<br />
<img src="images/exhibit28.jpg" style="float:left; margin-right:10px" alt="<NAME> and unidentified Seminoles pose with
a stretched otter hide.<br/>
Image courtesy of Fort Lauderdale Historical Society" />
<br />
<br/>
<br/>
<br/> <br />
<br/>
<br/>
<br/>
<strong>Egret plumes, alligator hides, and otter pelts were among the most valuable goods. The Seminoles would purchase things like calico cloth, woodworking tools, and canned food.</strong>The early trade and commerce of Fort Lauderdale depended on the New River as a gateway to larger markets. In 1911, construction began on a system of canals leading into the new city of Fort Lauderdale and draining the Everglades. At this time, the river began to see an increase in agricultural trade, and warehouses were constructed along its banks to hold the produce that would be shipped to northern markets. Those warehouses have since been replaced by million dollar homes, and river commerce depends on a thriving yacht and marine business. Despite these changes, the river remains an important part of Fort Lauderdale’s economy.</p>
</div>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?>
<file_sep><?php
/**
* When enabled, Zenphoto users will be appear not to be logged-in when viewing gallery pages
*
* @author <NAME> (sbillard)
* @package plugins
* @subpackage development
*/
$plugin_is_filter = 1001 | FEATURE_PLUGIN;
$plugin_description = sprintf(gettext("Treats users as not logged in for gallery pages."), DATA_FOLDER);
$plugin_author = "<NAME> (sbillard)";
if (!OFFSET_PATH) {
zp_register_filter('guest_login_attempt', 'show_not_loggedin::adminLoginAttempt');
zp_register_filter('login_redirect_link', 'show_not_loggedin::loginRedirect');
show_not_loggedin::hideAdmin();
}
class show_not_loggedin {
static function hideAdmin() {
global $_zp_loggedin, $_zp_current_admin_obj, $_showNotLoggedin_real_auth;
if (!OFFSET_PATH && is_object($_zp_current_admin_obj)) {
$_showNotLoggedin_real_auth = $_zp_current_admin_obj;
if (isset($_SESSION)) {
unset($_SESSION['zp_user_auth']);
}
if (isset($_COOKIE)) {
unset($_COOKIE['zp_user_auth']);
}
$_zp_current_admin_obj = $_zp_loggedin = NULL;
}
}
static function adminLoginAttempt($success, $user, $pass, $athority) {
if ($athority == 'zp_admin_auth' && $success) {
header('Location: ' . FULLWEBPATH . '/' . ZENFOLDER . '/admin.php');
exitZP();
}
return $success;
}
static function loginRedirect($link) {
global $_showNotLoggedin_real_auth;
if (is_object($_showNotLoggedin_real_auth)) {
$link = WEBPATH . '/' . ZENFOLDER . '/admin.php';
?>
<div class="error">
<?php echo gettext('show_not_logged-in is active.'); ?>
</div>
<?php
}
return $link;
}
}
?><file_sep><?php
$eventID = isset($_GET["eventID"]) ? $_GET["eventID"] : null;
if($eventID != null)
$events = "SELECT * FROM $table WHERE eventID = '" . mysqli_real_escape_string($dblink, $eventID) . "';";
else
$events = "SELECT * FROM $table WHERE eventDateTimeStart LIKE '" . mysqli_real_escape_string($dblink, $thisDate) . "%' ORDER BY eventDateTimeStart ASC;";
$query = mysqli_query($dblink, $events);
$num_events = 0;
while($event = mysqli_fetch_array($query))
{
if($num_events > 0)
echo "<hr/>";
$timestampStart = strtotime($event['eventDateTimeStart']);
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventTimeStart = date('g:i a', $timestampStart);
$eventTimeEnd = date('g:i a', $timestampEnd);
echo "<h2>". stripslashes($event['title']) . "</h2>";
echo "<p><strong>Time: </strong><em>". $eventTimeStart . " til " . $eventTimeEnd . "</em></p>";
echo "<p><strong>Location: </strong><em> " . stripslashes($event['location']) . "</em></p>";
if($event['description'] != null)
echo "<p><strong>Description:</strong><em> " . nl2br(strip_tags(stripslashes($event['description']))) . " </em></p>";
if($event['link'] != null)
echo '<p><strong>Related link:</strong> <a href="' . $event['link'] . '"> Click Here!</a></p>';
if($event['relation'] == 'sharing')
echo '<p style="font-size:10px;"><em>FPAN is posting this event as a courtesy, we will neither be hosting nor attending this event.</p>';
else
echo "<p><em>FPAN is <strong>". $event['relation']." </strong> this event.</em></p>";
if($event['flyerLink'] != null)
echo '<h3><a href="'.$event['flyerLink'].'" target="_blank">View flyer</a></h3>';
$num_events+=1;
}
?>
<file_sep><?php
$pageTitle = "Then and Now: Life Along the New River";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Then and Now: Life Along the New River</h1></th>
</tr>
<tr>
<td class="table_mid">
<div id="exhibit">
<?php include 'nav.php'?>
<h2 align="center">Baseball</h2>
<p>
<img src="images/exhibit20.jpg" style="float:right; margin-left:10px; margin-bottom:10px;" alt="Members of the Fort Lauderdale baseball team in 1915.<br/>
Image courtesy of Broward County Historical Commission"
/> <strong>At the turn of the twentieth century, people were going crazy for baseball.</strong> The newly incorporated City of Fort Lauderdale was no different. In 1913, a meeting of concerned citizens decided to set aside property for a baseball field. Local businessman, <NAME>, donated land and offered to clear the property and build bleachers. The Fort Lauderdale team, later named The Tarpons, was formed shortly thereafter, and they played their first game on July 4, 1913 against the city of Stuart. From 1898 to 1946, baseball teams were segregated by race, and the Fort Lauderdale squad was no exception.
A group of local African American men created a team known as the Grey Sox whose exposition games against the Tarpons were quite popular. </p>
<p>
<img src="images/exhibit21.jpg" style="float:left; margin-right:10px" alt="The Fort Lauderdale Gray Sox, an all African American baseball team, formed in
1913. <NAME>, front row second from the right, went on to a successful
baseball career and in 2011 was inducted into the Negro League Baseball Hall of
Fame. <br/>
Image courtesy of the Roosevelt Jackson Collection at the Old Dillard Museumn"
/>
<strong>Because of the year-round warm weather, Fort Lauderdale became a popular destination for major and minor league teams.</strong> In the 1920s the Westside Ballpark opened at the North Fork of the New River at Broward Boulevard and replaced Stranahan’s ball field. This four acre park served as a winter training camp for professional teams like the Boston Braves. <br />
<br />
<br/>
</p><p>
<img src="images/exhibit22.jpg" alt="An early game at the Westside Ballpark.
Image courtesy of Broward County Historical Commission, E.H Baker Collection" style="float:right; margin-left:10px" /></p>
<p><br/><br/><br/><br/><br/><br/>Westside Ballpark closed in 1957, and the property now serves as the site for the Fort Lauderdale Parks and Recreation Department.</p>
</div>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?>
<file_sep><?php
include '../admin/dbConnect.php';
//Determine which page days link to based on whether using admin interface
if(!isset($calPage))
$calPage = "eventDetail.php";
//This gets today's date
$date = time();
$day = date('d', $date);
//If month is defined in URL, use that. Else use today's date to determine month
$month = isset($_GET['month']) ? mysqli_real_escape_string($dblink, $_GET['month']) : date('m', $date);
//If year is defined in URL, use that. Else use today's date to determine year.
$year = isset($_GET['year']) ? mysqli_real_escape_string($dblink, $_GET['year']) : date('Y', $date);
//Generate the first day of the month
$first_day = mktime(0,0,0,$month, 1, $year) ;
//Get the month name
$title = date('F', $first_day) ;
//Find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;
//Once we know what day of the week it falls on, we know how many blank days occure before it. If the first day of the week is a Sunday then it would be zero
switch($day_of_week){
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}
//Determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year);
//Query to find dates that have events
$sql = "SELECT * FROM $table WHERE eventDateTimeStart LIKE '$year-$month-%'";
if($findEvents = mysqli_query($dblink, $sql)){
$eventDays = array();
while($event = mysqli_fetch_array($findEvents)){
$timestampDate = strtotime($event['eventDateTimeStart']);
$eventDate = date('Y-m-d', $timestampDate);
array_push($eventDays, $eventDate);
}
}
//Define calendar navigation variables
if($month < 12){
$nextMonth = $month+1;
if($nextMonth < 10)
$nextMonth = "0".$nextMonth;
$next = "month=$nextMonth&year=$year";
}
else{
$nextYear = $year+1;
$next = "month=1&year=$nextYear";
}
if($month > 1){
$prevMonth = $month-1;
if($prevMonth < 10)
$prevMonth = "0".$prevMonth;
$prev = "month=$prevMonth&year=$year";
}
else{
$prevYear = $year-1;
$prev = "month=12&year=$prevYear";
}
if(isset($_GET['eventDate'])){
$eventDate = mysqli_real_escape_string($dblink, $_GET['eventDate']);
$next .= "&eventDate=".$eventDate;
$prev .= "&eventDate=".$eventDate;
}
if(isset($_GET['eventID'])){
$eventID = mysqli_real_escape_string($dblink, $_GET['eventID']);
$next .= "&eventID=$eventID";
$prev .= "&eventID=$eventID";
}
if(isset($_GET['pagenum'])){
$eventID = mysqli_real_escape_string($dblink, $_GET['pagenum']);
$next .= "&pagenum=$pagenum";
$prev .= "&pagenum=$pagenum";
}
?>
<div class="calendar center-block <?php echo $table.'-cal' ?>">
<div class="row">
<div class="col-xs-2">
<?php echo "<h3><a href=\"?$prev\"> < </a></h3> "; ?>
</div>
<div class="col-xs-8">
<?php echo "<h3>" .$title. " " .$year."</h3>" ?>
</div>
<div class="col-xs-2">
<?php echo "<h3><a href=\"?$next\"> > </a></h3>"; ?>
</div>
</div>
<div class="row header center-block">
<div class="col-xs-1">S</div>
<div class="col-xs-1">M</div>
<div class="col-xs-1">T</div>
<div class="col-xs-1">W</div>
<div class="col-xs-1">R</div>
<div class="col-xs-1">F</div>
<div class="col-xs-1">S</div>
</div>
<div class="row center-block">
<?php
//This counts the days in the week, up to 7
$day_count = 1;
//first we take care of those blank days
while ( $blank > 0 ) {
echo "<div class=\"col-xs-1\"></div>";
$blank = $blank-1;
$day_count++;
}
//sets the first day of the month to 1
$day_num = 1;
//count up the days, untill we've done all of them in the month
while ( $day_num <= $days_in_month ){
//Add leading zeros for eventDate if needed
if($day_num < 10)
$eventDate = "$year-$month-0$day_num";
else
$eventDate = "$year-$month-$day_num";
//If this day has events, link to listing of events
if(in_array($eventDate, $eventDays))
echo "<div class=\"col-xs-1 hasEvent\"><a href=\"$calPage?eventDate=$eventDate&month=$month&year=$year\">$day_num</a></div>";
else
echo "<div class=\"col-xs-1 \"> $day_num </div>";
$day_num++;
$day_count++;
//Make sure we start a new row every week
if ($day_count > 7){
echo '</div><div class="row center-block">';
$day_count = 1;
}
}
//Finaly we finish out the table with some blank details if needed
while ( $day_count >1 && $day_count <=7 ){
echo '<div class="col-xs-1"> </div>';
$day_count++;
}
?>
</div><!-- /.row -->
</div><!-- /.calendar -->
<file_sep><?php
$pageTitle = "";
include('_header.php');
?>
<div class="page-content container">
<div class="row">
<div class="page-header">
<h1>Geo-Trail</h1>
</div>
<div class="col-sm-10 col-sm-push-1 box-tab">
<!--<img src="images/darcgeotrail.png" alt="DARC Geotrail Logo" class="img-responsive"> -->
<img src="images/fpangeoman.png" alt="" class="img-responsive">
<p>Are you ready to explore Northwest Florida's archaeology and history? Forget your fedoras and bullwhips, and pick up a GPS device (or download a GPS app to your smartphone)! The DARC Geo-Trail offers everyone an outdoor adventure and chance of discovery...</p>
<h3>Geocaching? What's Geocaching? </h3>
<p>
Geocaching is a worldwide scavenger hunt game. Players try to locate hidden containers, called caches, using GPS enabled devices and share their experiences online. Caches are often hidden very well, but are never buried or placed in areas in need of protection. To learn more about geocaching go to this official <a href="http://www.geocaching.com/articles/Brochures/EN/EN_Geocaching_BROCHURE_online_color.pdf" target="_blank">brochure</a> or visit this <a href="http://www.geocaching.com/guide/default.aspx" target="_blank">website</a>. You can also view this <a href="http://www.youtube.com/watch?v=-4VFeYZTTYs&feature=player_embedded" target="_blank">video</a>. Please follow all basic guidelines and rules when geocaching. </p>
<h3>The DARC Geo-Trail</h3>
<p>A "geotrail" is a series of caches tied together by a common topic or theme. Discover your Florida history through museums and archaeological sites open to the public in the DARC Geo-Trail.</p>
<p>DARC stands for Destination Archaeology Resource Center, the museum at the FPAN Coordinating Center. FPAN has hidden geocaches at participating sites across Northwest Florida to form a geotrail called DARC Geo-Trail. All the sites on this geotrail are connected to Florida archaeology and are featured in the Road Trip Through Florida Archaeology exhibit at the Destination Archaeology! Resource Center in Pensacola, FL.</p>
<h3>Adventure and Discovery</h3>
<img src="images/gps.jpg" alt="GPS unit with map" class="img-responsive">
<p>Players who participate in this geotrail will have the opportunity to visit many different types of archaeological sites at both rural and urban areas while looking for caches.</p>
<p>A few of the places this journey will take you:</p>
<ul>
<li>Ancient earthworks built by Native American civilizations long before Columbus set sail for the Americas… </li>
<li>Plantations that fueled the southern economy and ultimately led the country into Civil War…</li>
<li>Remnants of fortifications once under siege during the American Revolution… </li>
<li>Antebellum industrial areas that powered the economy of Florida …</li>
</ul>
<h3>Chance to Win an Official DARC Geocoin!</h3>
<p>The first 300 participants who record at least 12 sites will receive a traceable, special edition geocoin produced specifically for this geotrail.</p>
<p>To be eligible for the coin, please download the <a href="http://fpan.us/uploads/nwrc/passport.pdf" target="_blank">official DARC Geo-Trail passport</a>. You will need <a href="http://www.get.adobe.com/" target="_blank">Adobe Acrobat</a> to view and print this document. Once you find a geocache, record the name, date, and code word (located on the inside of the logbook) in this passport and take a photo of yourself with the geocache container. The first person to find a geocache will find an FPAN item inside!</p>
<img src="images/geocaching_logo.png" alt="Geocaching.com Logo" class="img-responsive">
<h3> Here’s how it works: </h3>
<ul>
<li>Log onto <a href="http://www.geocaching.com" taget="_blank">www.geocaching.com </a>to retrieve the cordinates and location information for the geocaches. Badsic membership for site is free.</li>
<li>Search for the geocache online by GC code number or use advanced search by user name “DARC Geotrail.” </li>
<li>Locate at least 12 DARC Geo-Trail geocaches and record the code word from each geocache in your passport. Take a picture of yourself with the geocache at the site and post it to the corresponding Geocaching.com page.</li>
<li>Bring in your completed passport to the address below or mail it in for validation. The first 300 people to complete the challenge will receive the coin.*</li>
</ul>
<blockquote>Destination Archaeology Resource Center<br/>
207 East Main Street<br/>
Pensacola, FL 32502<br/>
Phone: 850.595.0050 ext. 107<br/>
</blockquote>
<p>The DARC Geo-Trail is a project of the Florida Public Archaeology Network and University of West Florida. This project is supported by the <a href="http://www.floridastateparks.org/" taget="_blank">Florida Park Service</a> and the <a href="http://www.floridacaching.com/" taget="_blank">Florida Geocaching Association</a>.</p>
<em>*Coins will be awarded on a first-come, first-serve basis as supplies last. Only one coin per person with a valid passport. Once your passport has been validated you will be rewarded with a DARC geocoin. FPAN and UWF are not responsible for any lost, stolen or misdirected passports or mail. All geocaches are officially registered at www.geocaching.com. Participants will need to register at Geocaching.com to retrieve coordinates and other location information for geocaches. Participants must log the find with a photo from the cache location. Basic membership to Geocaching.com is free. </em>
</div>
</div>
</div><!-- /.page-content /.container -->
<?php include('_footer.php'); ?>
<file_sep><?php
$pageTitle = "Programs";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Forest Resources Environmental Policy Special Sites Workshop</h1></th>
</tr>
<tr>
<td>
<p class="center">
<img src="images/forestryTraining.jpg" class="padded"/>
</p>
<p>Professional foresters and logging company personnel frequently come into contact with cultural resources, or “special sites.” This one-day workshop helps forestry professionals to identify historical and archaeological resources they are likely to encounter in the course of their work, including Native American sites, cemeteries, industrial sites, and sites submerged in rivers and streams. Information also includes what to do if a site is found; laws affecting sites on federal, state, and county lands; and how to proactively protect cultural sites.</p>
<hr/>
<p>
<h4> <a href="http://www.flpublicarchaeology.org/programs/">< Go Back to Program List</a></h4>
</p>
</td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?><file_sep><?php
$pageTitle = "Workshops - Human Remains & The Law";
include('../_header.php');
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1> Workshops, <small>Human Remains & The Law</small></h1>
</div>
<div class="col-lg-8 col-lg-push-2 col-sm-10 col-sm-push-1 box-tab box-line row">
<div class="col-sm-12 text-center">
<div class="image">
<img class="img-responsive" src="images/humanRemains_thumb.jpg" >
</div>
</div>
<p>This half-day workshop focuses on Florida and US laws regulating the discovery of human remains and the management of Native American remains within museum collections. Geared toward land managers, this course provides guidance for dealing with inadvertent discoveries of human remains, discusses strategies for managing marked and unmarked cemeteries, presents a brief overview of the Native American Graves Protection and Repatriation Act (NAGPRA), and addresses issues of Native American remains within museum collections.</p>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
$pageTitle = "People - Staff";
include('_header.php');
?>
<!-- page-content begins -->
<div class="container">
<div class="page-header">
<h1 class=""> People, <small>Board of Directors</small> </h1>
</div>
<!-- Row One -->
<div class="row">
<div class="col-sm-6">
<div class="staff-box row">
<div class="col-md-6 col-sm-12">
<img src="images/people/judy_bense.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong>Dr. <NAME>, RPA, Chair</strong>
(Director representing UWF)<br/>
<em>University of West Florida, President</em><br/>
Pensacola<br/>
Term: July 1, 2010 - June 30, 2016
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/worth.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong><NAME></strong>
(Director representing UWF)<br/>
<em>University of West Florida, Archaeology Institute</em><br/>
Pensacola<br/>
Term: Expires June 30, 2015
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/greg_cook.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong><NAME></strong>
(Director representing UWF)<br/>
<em>University of West Florida, Archaeology Institute</em><br/>
Pensacola<br/>
Term: July 1, 2011 - June 30, 2017
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/mary_glowacki.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong>Dr. <NAME></strong>
(ex officio Director as State Archaeologist)<br/>
<em>Division of Historical Resources, Bureau of Archaeological Resoures </em><br/>
Tallahassee<br/>
Term: as long as occupying position of State Archaeologist
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/patty_flynn.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong><NAME></strong>
(Director representing FAS)<br/>
<em>Florida Anthropological Society</em><br/>
Fort Lauderdale<br/>
Term: May 2008 - June 30, 2015
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/paul_jones.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong><NAME></strong>
(Director representing Florida Archaeological Council)<br/>
<em>Florida History LLC</em><br/>
Tampa<br/>
Term: July 1, 2011 - June 30, 2014
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<!-- <div class="col-md-6 col-sm-12 ">
<img src="images/people/paul_jones.jpg" class="img-circle img-responsive center-block" />
</div> -->
<div class="col-sm-12">
<p>
<strong><NAME>) Robbins</strong>
(Director at Large, representing the lay public)<br/>
<em>City of Jacksonville, Recreation and Community Programming</em><br/>
Jacksonville<br/>
Term: July 2011 - July 30, 2015
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
</div><!-- /.col -->
<div class="col-sm-6">
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/lee_hutchinson.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong><NAME></strong>
(Director at Large, in-state)<br/>
<em>ACI</em><br/>
Sarasota<br/>
Term: May 2009 - June 30, 2015
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/robin_moore.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong><NAME> </strong>
(Director at Large, in-state)<br/>
<em>St. Johns County Growth Management</em><br/>
St. Augustine<br/>
Term: July 1, 2011 - June 30, 2016
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/terry_klein.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong><NAME>, RPA </strong>
(Director at Large, out-of-state)<br/>
<em>SRI Foundation</em><br/>
Rio Rancho, New Mexico<br/>
Term: May 2009 - June 30, 2015
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/lynne_goldstein.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong>Dr. <NAME>, RPA</strong>
(Director at Large, out-of-state)<br/>
<em>Michigan State University, Department of Anthropology</em><br/>
East Lansing, Michigan<br/>
Term: July 1, 2011- June 30, 2016
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/bill_lees.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong>Dr. <NAME>, RPA </strong>
(Executive Officer and Secretary to the Board)<br/>
<em>University of West Florida, FPAN</em><br/>
Pensacola<br/>
Term: May 2009 - June 30, 2016
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/elizabeth_benchley.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong>Dr. <NAME>, RPA</strong>
(Staff Advisor to the Board)<br/>
<em>University of West Florida, Archaeology Institute</em><br/>
Pensacola<br/>
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-md-6 col-sm-12 ">
<img src="images/people/hester_davis.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-md-6 col-sm-12">
<p>
<strong><NAME>, RPA </strong>
(Director, emeritus)<br/>
Fayetteville, Arkansas<br/>
</p>
</div> <!-- /.col -->
</div><!-- /.row -->
</div> <!-- /.col -->
</div> <!-- /.row one -->
</div><!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$link = mysql_connect('fpanweb.powwebmysql.com', 'fam_user', ')OKM9ijn');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(fam_events);
?><file_sep><?php
$pageTitle = "Virtual Tours - Ft. Walton Temple Mound";
include '../../dbConnect.php';
include '../header.php';
$flashvars = "file=http://www.flpublicarchaeology.org/resources/videos/destinationArchaeologyTour.flv&screencolor=000000";
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<th class="lg_header"><h1>Virtual Tours</h1></th>
</tr>
<tr>
<td class="lg_mid" style="vertical-align:top">
<h2 align="center">Fort Walton Temple Mound</h2>
<br/>
<div align="center">
<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='620' height='349' id='single1' name='single1'>
<param name='movie' value='../player.swf'>
<param name='allowfullscreen' value='true'>
<param name='allowscriptaccess' value='always'>
<param name='wmode' value='transparent'>
<?php echo "<param name='flashvars' value='$flashvars'>" ?>
<embed
type='application/x-shockwave-flash'
id='single2'
name='single2'
src='../player.swf'
width='600'
height='338'
bgcolor='000000'
allowscriptaccess='always'
allowfullscreen='true'
wmode='transparent'
<?php echo "flashvars='$flashvars'" ?>
/>
</object>
</div>
<p>The large mound and village site within the community of Fort Walton Beach gained the attention of antiquarians and archaeologists well over 100 years ago. This site is the namesake of Fort Walton archaeological culture, which is found over a large territory in Florida and surrounding states and is characterized by impressive mounds and elaborate pottery. Though much of the village site has been built over since its initial rediscovery by archaeologists, the large temple mound remains and is preserved by the City of Fort Walton Beach.</p>
<h3>DID YOU KNOW...</h3>
<ul>
<li>The Fort Walton Temple Mound, built between 800 and 1400 A.D., is a National Historic Landmark.</li>
<li>Exhibits depict 12,000 years of Native American history; the museum features more than 6,000 ceramic artifacts and contains the finest collection of Fort Walton Period ceramics in the Southeastern U.S.</li>
<li>Artifacts from early explorers, settlers, and Civil War soldiers are also on display at three other museums on the site. These include two historic buildings that are included in one admission price.</li>
</ul>
<h4 align="center"><a href="http://fwb.org/museums/">Fort Walton Temple Mound Museum Website</a></h4>
<p align="center"> <a href="https://maps.google.com/maps?oe=utf-8&client=firefox-a&ie=UTF-8&q=heritage+park+and+cultural+center&fb=1&gl=us&hq=heritage+park+and+cultural+center&hnear=0x8890eab279993865:0xf727f89dd4c5f075,Ferry+Pass,+FL&cid=0,0,11164529537921669053&ei=NiyBUezkLqyt0AHB-oHoBQ&ved=0CIUBEPwSMAA"> 139 Miracle Strip Pkwy, Fort Walton Beach, FL 32548</a></p>
</td>
</tr>
</table>
<? include '../calendar.php'; ?>
<? include '../eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include '../footer.php'; ?><file_sep><?php
include 'appHeader.php';
include $header;
if ($submit) {
// required fields in the line below
if (!$old_password || !$new_password || !$conf_new_password){
$msg = "You must complete all fields";
$err = true;
}
else{
//Protect against SQL injection
$old_password = mysql_real_escape_string($old_password);
$new_password = mysql_real_escape_string($new_password);
$conf_new_password = mysql_real_escape_string($conf_new_password);
//Make sure username exists and old password is valid
$sql = "SELECT * FROM users WHERE email = '$_SESSION[email]' AND password = <PASSWORD>('$old_<PASSWORD>', '$_SESSION[aes_key]')";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count != 1){
$msg = "Invalid old password.";
$err = true;
}
//Make sure new passwords patch
if($new_password != $conf_new_password){
$msg = "New passwords do not match.";
$err = true;
}
//If no error so far, change password
if (!$err) {
$sql = "UPDATE users SET password = <PASSWORD>('$new_password', '$_SESSION[aes_key]') WHERE email = '$_SESSION[email]'";
$result=mysql_query($sql);
$msg = "Password successfully changed.";
}
}
}
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Change Password</h1></th>
</tr>
<tr>
<td class="table_mid">
<?
if($err)
$color = "red";
if($msg)
echo "<p align=\"center\" style=\"color:$color;\" class=\"msg\"> $msg </p>";
?>
<form action="<?php echo $php_SELF ?>" method="post">
<table border="0" align="center" cellpadding="3" cellspacing="0" >
<tr>
<td><div align="right">Email:</div></td>
<td><strong><?php echo $_SESSION['email']; ?></strong>
</td>
</tr>
<tr>
<td><div align="right">Old Password:</div></td>
<td><input name="old_password" type="<PASSWORD>" required="Yes" >
</td>
</tr>
<tr>
<td><div align="right" style="color:#900">New Password:</div></td>
<td><input name="new_password" type="<PASSWORD>">
</td>
</tr>
<tr>
<td><div align="right" style="color:#900">Confirm New Password:</div></td>
<td><input name="conf_new_password" type="<PASSWORD>" >
</td>
</tr>
<tr>
<td colspan="2" valign="middle"><div align="center"> <br />
<input name="submit" type="submit" value="Submit" class="navbtn"/>
</div></td>
</tr>
</table>
</form>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include 'adminBox.php'; ?>
</div>
</div>
<!-- End Main div -->
<div class="clearFloat"></div>
<?php include $footer; ?><file_sep><?php
/****************************************************************************************************************/
/********************************** Misc Functions ******************************************/
/****************************************************************************************************************/
//Determine if user has editing priveleges
function isAdmin(){
//Interns/other staff can't edit
if($_SESSION['my_role'] == 3)
return false;
else
return true;
}
//Truncate a given $string up to a $limited number of characters
function truncate($string, $limit, $break=" ", $pad="..."){
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit) return $string;
$string = substr($string, 0, $limit);
if(false !== ($breakpoint = strrpos($string, $break))) {
$string = substr($string, 0, $breakpoint);
}
return $string . $pad;
}
function getTitle($typeActivity){
if($typeActivity == "PublicOutreach"){
$title = "Public Outreach";
}
if($typeActivity == "TrainingWorkshops"){
$title = "Training / Workshops";
}
if($typeActivity == "GovernmentAssistance"){
$title = "Government Assistance";
}
if($typeActivity == "SocialMedia"){
$title = "Social Media";
}
if($typeActivity == "PressContact"){
$title = "Press Contact";
}
if($typeActivity == "Publication"){
$title = "Publication";
}
if($typeActivity == "DirectMail"){
$title = "Direct Mail";
}
if($typeActivity == "ServiceToProfessionalSociety"){
$title = "Service To Professional Society";
}
if($typeActivity == "ServiceToHostInstitution"){
$title = "Service To Host Institution";
}
if($typeActivity == "ServiceToCommunity"){
$title = "Service To Community";
}
if($typeActivity == "TrainingCertificationEducation"){
$title = "Training / Certification / Education";
}
if($typeActivity == "ConferenceAttendanceParticipation"){
$title = "Conference Attendance / Participation";
}
return $title;
}
//Get exact current page URL
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
/****************************************************************************************************************/
/********************************** FPAN Activity Functions ******************************************/
/****************************************************************************************************************/
//Return an array of all FPAN activities that user is allowed to see from specified table
function getActivity($table, $id){
$sql = "SELECT * FROM $table WHERE id='$id' ";
$results = mysql_query($sql);
$results_array = array();
if(mysql_num_rows($results) != 0)
$results_array = mysql_fetch_assoc($results);
//Get staffInvolved array from EmployeeActivity table, also store in a second array for comparison after edits
$sql = "SELECT employeeID FROM EmployeeActivity
WHERE activityID = '$id'";
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results)){
$results_array['staffInvolved'][] = $row['employeeID'];
}
return $results_array;
}
//Print Details of a single activity
function printActivity($activityArray){
echo "<div style=\"text-align:left; margin-left:100px;\">";
//Loop formVars array and print key and value of each element
foreach($activityArray as $key => $value){
if(!in_array($key, $_SESSION['excludeKeys'])){
$varName = ucfirst($key);
$varName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $varName);
echo "<strong>".$varName.": </strong>".$value."<br/>";
}
}
//Display staff involved, if there were any
if($activityArray['staffInvolved']){
$sql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($sql);
echo "<strong>The staff involved:</strong> <br/>";
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName']." ".$employee['lastName'];
if(in_array($employee['id'], $activityArray['staffInvolved']))
echo "<span style=\"margin-left:10px;\">". $employeeName."</span><br/>";
}
}
echo "</div>";
}
//Return an array of all FPAN activities that user is allowed to see from specified table
function getActivities($table, $sortBy="activityDate", $order="DESC"){
//SQL for region-specific activities if user is outreach coordinator/intern/other staff
if(($_SESSION['my_role'] == 2) || ($_SESSION['my_role'] == 3)){
$sql = "SELECT * FROM $table
WHERE submit_id IN (SELECT id FROM Employees
WHERE region = '$_SESSION[my_region]') ";
$sql.= "UNION ";
$sql.= "SELECT * FROM $table WHERE id IN(
SELECT activityID FROM EmployeeActivity
WHERE employeeID IN(
SELECT id FROM Employees
WHERE region = '$_SESSION[my_region]')) ORDER BY $sortBy $order; ";
//SQL for all region activities if user is admin
}elseif(($_SESSION['my_role'] == 1) || ($_SESSION['my_role'] == 5)){
$sql = "SELECT * FROM $table ORDER BY $sortBy $order";
}
$results = mysql_query($sql);
$results_array = array();
if(mysql_num_rows($results) != 0)
while($row = mysql_fetch_assoc($results)){
$results_array[] = $row;
}
return $results_array;
}
//Print a number of activities of a given type
function printActivities($activityArray, $typeActivity, $displayLimit, $canSort=false){
$startLimit = 1;
$tableClass = "\"tablesorter\"";
$tableID = "\"resultsTable\"";
echo "<table class=$tableClass id=$tableID>";
echo "<thead>";
if($typeActivity == "PublicOutreach"){
if($canSort){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"></td>";
echo "<th><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=activityDate\">Date</th>";
echo "<th><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=county\">County</th>";
echo "<th><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=typeActivity\">Activity</th></tr> ";
}else
echo "<tr id=\"head_row\"><td id=\"blank_cell\"> </td><td id=\"blank_cell\"> </td><th>Date</th><th>County</th><th>Activity</th></tr> ";
echo "</thead>";
echo "<tbody>";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View</a> </td><td>";
if(isAdmin()) echo "<a href=\"publicOutreach.php?id=".$activity['id']."\">Edit</a> </td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['county']."</td><td>";
echo $activity['typeActivity']."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
echo "</tbody>";
}
if($typeActivity == "TrainingWorkshops"){
if($canSort){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"></td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=activityDate\">Date</td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=county\">County</td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=typeActivity\">Activity</td></tr> ";
}else
echo "<tr id=\"head_row\"><td id=\"blank_cell\"><td id=\"blank_cell\"> </td><td>Date</td><td>County</td><td>Activity</td></tr> ";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View</a> </td><td>";
if(isAdmin()) echo "<a href=\"trainingWorkshops.php?id=".$activity['id']."\"> Edit </a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['county']."</td><td>";
echo stripslashes($activity['typeActivity'])."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "GovernmentAssistance"){
if($canSort){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"></td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=activityDate\">Date</td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=county\">County</td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=typeOrganization\">Organization</td></tr> ";
}else
echo "<tr id=\"head_row\"><td id=\"blank_cell\"><td id=\"blank_cell\"> </td><td>Date</td><td>County</td><td>Organization</td></tr> ";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View</a> </td><td>";
if(isAdmin()) echo "<a href=\"governmentAssistance.php?id=".$activity['id']."\"> Edit </a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['county']."</td><td>";
echo $activity['typeOrganization']."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "Meeting"){
if($canSort){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"></td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=activityDate\">Date</td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=organization\">Organization</td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=meetingCategory\">Category</td></tr> ";
}else
echo "<tr id=\"head_row\"><td id=\"blank_cell\"><td id=\"blank_cell\"> </td><td>Date</td><td>Organization</td><td>Category</td></tr> ";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View</a> </td><td>";
if(isAdmin()) echo "<a href=\"meeting.php?id=".$activity['id']."\"> Edit </a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['organization']."</td><td>";
echo $activity['meetingCategory']."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "SocialMedia"){
if($canSort){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"></td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=activityDate\">Date</td>";
}else
echo "<tr id=\"head_row\"><td id=\"blank_cell\"><td id=\"blank_cell\"> </td><td>Date</td></tr> ";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View</a> </td><td>";
if(isAdmin()) echo "<a href=\"socialMedia.php?id=".$activity['id']."\">Edit</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date('M, Y', $displayDate)."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "PressContact"){
if($canSort){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"></td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=activityDate\">Date</td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=typeMedia\">Media</td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=typeContact\">Contact</td></tr> ";
}else
echo "<tr id=\"head_row\"><td id=\"blank_cell\"><td id=\"blank_cell\"> </td><td>Date</td><td>Media</td><td>Contact</td></tr> ";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View</a> </td><td>";
if(isAdmin()) echo "<a href=\"pressContact.php?id=".$activity['id']."\">Edit</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['typeMedia']."</td><td>";
echo $activity['typeContact']."</td><tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "Publication"){
if($canSort){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"></td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=activityDate\">Date</td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=typeMedia\">Media</td>";
}else
echo "<tr id=\"head_row\"><td id=\"blank_cell\"><td id=\"blank_cell\"> </td><td>Date</td><td>Media</td></tr> ";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View</a> </td><td>";
if(isAdmin()) echo "<a href=\"publication.php?id=".$activity['id']."\">Edit</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['typeMedia']."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "DirectMail"){
if($canSort){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"></td>";
echo "<td><a href=\"".$_SERVER['PHP_SELF']."?typeActivity=".$typeActivity."&sortBy=activityDate\">Date</td>";
}else
echo "<tr id=\"head_row\"><td id=\"blank_cell\"><td id=\"blank_cell\"> </td><td>Date</td></tr> ";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View</a> </td><td>";
if(isAdmin()) echo "<a href=\"directMail.php?id=".$activity['id']."\">Edit</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
echo "</table>";
}
/****************************************************************************************************************/
/********************************** Professional Service Functions ******************************************/
/****************************************************************************************************************/
//Return an array of all FPAN activities that user is allowed to see from specified table
function getService($table, $id){
$sql = "SELECT * FROM $table WHERE id='$id' ";
$results = mysql_query($sql);
$results_array = array();
if(mysql_num_rows($results) != 0)
$results_array = mysql_fetch_assoc($results);
//Get staffInvolved array from EmployeeActivity table, also store in a second array for comparison after edits
$sql = "SELECT employeeID FROM EmployeeActivity
WHERE activityID = '$id'";
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results)){
$results_array['staffInvolved'][] = $row['employeeID'];
}
return $results_array;
}
//Print Details of a single activity
function printService($serviceArray){
echo "<div style=\"text-align:left; margin-left:100px;\">";
//Loop formVars array and print key and value of each element
foreach($serviceArray as $key => $value){
if(!in_array($key, $_SESSION['excludeKeys'])){
$varName = ucfirst($key);
$varName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $varName);
echo "<strong>".$varName.": </strong>".$value."<br/>";
}
}
//Display staff involved, if there were any
if($serviceArray['staffInvolved']){
$sql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($sql);
echo "<strong>The staff involved:</strong> <br/>";
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName']." ".$employee['lastName'];
if(in_array($employee['id'], $serviceArray['staffInvolved']))
echo "<span style=\"margin-left:10px;\">". $employeeName."</span><br/>";
}
}
echo "</div>";
}
//Return array of all Professional Service events user is allowed to see from specified table
function getServices($table){
//SQL for region-specific activities if user is outreach coordinator/intern/other staff
if(($_SESSION['my_role'] == 2) || ($_SESSION['my_role'] == 3)){
$sql = "SELECT *, $table.id AS service_id
FROM $table
JOIN Employees
ON $table.submit_id = Employees.id
WHERE $table.submit_id IN
(SELECT id FROM Employees WHERE region = '$_SESSION[my_region]')
ORDER BY $table.serviceDate DESC ";
//SQL for all region activities if user is admin
}elseif(($_SESSION['my_role'] == 1) || ($_SESSION['my_role'] == 5)){
$sql = "SELECT *, $table.id AS service_id
FROM $table
JOIN Employees
ON $table.submit_id = Employees.id
ORDER BY serviceDate DESC";
}
$results = mysql_query($sql);
$results_array = array();
if(mysql_num_rows($results) != 0)
while($row = mysql_fetch_assoc($results)){
$results_array[] = $row;
}
return $results_array;
}
//Print a number services of a given type
function printServices($serviceArray, $typeService, $displayLimit){
$startLimit = 1;
$tableClass = "\"summary\"";
echo "<table class=$tableClass>";
if($typeService == "ServiceToProfessionalSociety"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"><td>Date</td><td>Employee</td><td>Society</td><td>Comments</td></tr> ";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View</a> </td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
if(isAdmin()) echo "<a href=\"serviceToProfessionalSociety.php?id=".$service['service_id']."\">Edit</a></td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
echo $employeeName."</td><td>";
echo $service['typeSociety']."</td><td>";
echo truncate(stripslashes($service['comments']), 30, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "ServiceToHostInstitution"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"><td>Date</td><td>Employee</td><td>Comments</td></tr> ";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View</a> </td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
if(isAdmin()) echo "<a href=\"serviceToHostInstitution.php?id=".$service['service_id']."\">Edit</a></td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
echo $employeeName."</td><td>";
echo truncate(stripslashes($service['comments']), 30, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "ServiceToCommunity"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"><td>Date</td><td>Employee</td><td>Comments</td></tr> ";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View</a> </td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
if(isAdmin()) echo "<a href=\"serviceToCommunity.php?id=".$service['service_id']."\">Edit</a></td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
echo $employeeName."</td><td>";
echo truncate(stripslashes($service['comments']), 30, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "TrainingCertificationEducation"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"><td>Date</td><td>Employee</td><td>Type</td><td>Comments</td></tr> ";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View</a> </td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
if(isAdmin()) echo "<a href=\"trainingCertificationEducation.php?id=".$service['service_id']."\">Edit</a></td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
echo $employeeName."</td><td>";
echo $service['typeTraining']."</td><td>";
echo truncate(stripslashes($service['comments']), 30, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "ConferenceAttendanceParticipation"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><td id=\"blank_cell\"><td>Date</td><td>Employee</td><td>Type</td><td>Comments</td></tr> ";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View</a> </td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
if(isAdmin()) echo "<a href=\"conferenceAttendanceParticipation.php?id=".$service['service_id']."\">Edit</a></td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
echo $employeeName."</td><td>";
echo $service['typeConference']."</td><td>";
echo truncate(stripslashes($service['comments']), 30, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
echo "</table>";
}
?><file_sep><?php
//Updated MySQLi commands
/*
$db = new mysqli('fpanweb.powwebmysql.com', 'reports_user', ')OKM9ijn', 'fpan_dev_reports');
if($db->connect_errno > 0){
die('Unable to connect to database [' .$db->connect_error.']');
}
*/
//Outdated MySQL commands
if (!$link) {
$link = @mysql_connect('fpanweb.powwebmysql.com', 'reports_user', ')OKM9ijn');
}else{
mysql_error();
}
mysql_select_db(fpan_dev_reports);
?><file_sep><?php
include 'header.php';
$table = 'TrainingWorkshops';
//if this is a new event, clear any potential leftover form data
if($_GET['new'])
$_SESSION['formVars'] = "";
//If event ID is supplied in URL, this event is being edited. Gather info from database and populate form.
if($_GET['id']){
setupEdit($_GET['id'], $table);
}
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true){
confirmSubmit($table);
}
//Form has been submitted but not confirmed. Display input values to check for accuracy
if(isset($_POST['submit'])&&!isset($_POST['confirmSubmission'])){
firstSubmit($_POST);
}elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="trainingWorkshop" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Training and Workshops</h2>
<p>Please fill out the information below to log this activity.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Start Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text" required="required"> /
<label for="element_1_1">MM</label>
</span>
<span>
<input id="element_1_2" name="day" class="element text" size="2" maxlength="2" value="<?php echo $formVars['day']; ?>" type="text" required="required"> /
<label for="element_1_2">DD</label>
</span>
<span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text" required="required"><a class="red"> *</a>
<label for="element_1_3">YYYY</label>
</span>
<span id="calendar_1">
<img id="cal_img_1" class="datepicker" src="images/calendar.gif" alt="Pick a date.">
</span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</li>
<li id="li_2" >
<label class="description" for="element_2">End Date </label>
<span>
<input id="element_2_1" name="endMonth" class="element text" size="2" maxlength="2" value="<?php echo $formVars['endMonth']; ?>" type="text" >
/
<label for="element_2_1">MM</label>
</span> <span>
<input id="element_2_2" name="endDay" class="element text" size="2" maxlength="2" value="<?php echo $formVars['endDay']; ?>" type="text" >
/
<label for="element_2_2">DD</label>
</span> <span>
<input id="element_2_3" name="endYear" class="element text" size="4" maxlength="4" value="<?php echo $formVars['endYear']; ?>" type="text" >
<label for="element_2_3">YYYY</label>
</span> <span id="calendar_2"> <img id="cal_img_2" class="datepicker" src="images/calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_2_3",
baseField : "element_2",
displayArea : "calendar_2",
button : "cal_img_2",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</li>
<li id="li_12" >
<label class="description" for="element_12">Name of Activity/Event</label>
<div>
<input id="element_12" name="activityName" class="element text" size="40" maxlength="100" value="<?php echo $formVars['activityName']; ?>" type="text" required="required">
<a class="red">*</a></div>
</li>
<li id="li_7" >
<label class="description" for="element_7">Type of Activity</label>
<div>
<select class="element select medium" id="element_7" name="typeActivity" required="required">
<option value="" selected="selected"></option>
<option <?php if($formVars['typeActivity'] == "HADS") echo "selected=\"selected\""; ?> value="HADS" >HADS</option>
<option <?php if($formVars['typeActivity'] == "SSEAS") echo "selected=\"selected\""; ?> value="SSEAS" >SSEAS</option>
<option <?php if($formVars['typeActivity'] == "HART") echo "selected=\"selected\""; ?> value="HART" >HART</option>
<option <?php if($formVars['typeActivity'] == "CRPT") echo "selected=\"selected\""; ?> value="CRPT" >CRPT</option>
<option <?php if($formVars['typeActivity'] == "BSA Merit Badge") echo "selected=\"selected\""; ?> value="BSA Merit Badge" >BSA Merit Badge</option>
<option <?php if($formVars['typeActivity'] == "Forestry") echo "selected=\"selected\""; ?> value="Forestry" >Forestry</option>
<option <?php if($formVars['typeActivity'] == "Park Ranger") echo "selected=\"selected\""; ?> value="Park Ranger" >Park Ranger</option>
<option <?php if($formVars['typeActivity'] == "Teacher In-Service") echo "selected=\"selected\""; ?> value="Teacher In-Service" >Teacher In-Service</option>
<option <?php if($formVars['typeActivity'] == "Project Archaeology") echo "selected=\"selected\""; ?> value="Project Archaeology" >Project Archaeology</option>
<option <?php if($formVars['typeActivity'] == "Advocacy") echo "selected=\"selected\""; ?> value="Advocacy" >Advocacy</option>
<option <?php if($formVars['typeActivity'] == "Local Government") echo "selected=\"selected\""; ?> value="Local Government" >Local Government</option>
<option <?php if($formVars['typeActivity'] == "Social Media") echo "selected=\"selected\""; ?> value="Social Media" >Social Media</option>
<option <?php if($formVars['typeActivity'] == "Other") echo "selected=\"selected\""; ?> value="Other" >Other</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_11" >
<label class="description" for="element_11">Target Audience</label>
<div>
<select class="element select medium" id="element_11" name="audience" required="required">
<option value="" selected="selected"></option>
<option <?php if($formVars['audience'] == "local") echo "selected=\"selected\""; ?> value="local" >local</option>
<option <?php if($formVars['audience'] == "state") echo "selected=\"selected\""; ?> value="state" >state</option>
<option <?php if($formVars['audience'] == "regional") echo "selected=\"selected\""; ?> value="regional" >regional</option>
<option <?php if($formVars['audience'] == "national/international") echo "selected=\"selected\""; ?> value="national/international" >national/international</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_2" >
<label class="description" for="element_10">County </label>
<div>
<select class="element select medium" id="element_10" name="county" required="required">
<option value="" selected="selected"></option>
<option value="N/A" <?php if($formVars['county'] == "N/A") echo 'selected="selected"';?> >N/A</option>
<option value="Alachua" <?php if($formVars['county'] == "Alachua") echo 'selected="selected"';?> >Alachua</option>
<option value="Baker" <?php if($formVars['county'] == "Baker") echo 'selected="selected"';?> >Baker</option>
<option value="Bay" <?php if($formVars['county'] == "Bay") echo 'selected="selected"';?> >Bay</option>
<option value="Bradford" <?php if($formVars['county'] == "Bradford") echo 'selected="selected"';?> >Bradford</option>
<option value="Brevard" <?php if($formVars['county'] == "Brevard") echo 'selected="selected"';?> >Brevard</option>
<option value="Broward" <?php if($formVars['county'] == "Broward") echo 'selected="selected"';?> >Broward</option>
<option value="Calhoun" <?php if($formVars['county'] == "Calhoun") echo 'selected="selected"';?> >Calhoun</option>
<option value="Charlotte" <?php if($formVars['county'] == "Charlotte") echo 'selected="selected"';?> >Charlotte</option>
<option value="Citrus" <?php if($formVars['county'] == "Citrus") echo 'selected="selected"';?> >Citrus</option>
<option value="Clay" <?php if($formVars['county'] == "Clay") echo 'selected="selected"';?> >Clay</option>
<option value="Collier" <?php if($formVars['county'] == "Collier") echo 'selected="selected"';?> >Collier</option>
<option value="Columbia" <?php if($formVars['county'] == "Columbia") echo 'selected="selected"';?> >Columbia</option>
<option value="DeSoto" <?php if($formVars['county'] == "DeSoto") echo 'selected="selected"';?> >DeSoto</option>
<option value="Dixie" <?php if($formVars['county'] == "Dixie") echo 'selected="selected"';?>>Dixie</option>
<option value="Duval" <?php if($formVars['county'] == "Duval") echo 'selected="selected"';?>>Duval</option>
<option value="Escambia" <?php if($formVars['county'] == "Escambia") echo 'selected="selected"';?>>Escambia</option>
<option value="Flagler" <?php if($formVars['county'] == "Flagler") echo 'selected="selected"';?>>Flagler</option>
<option value="Franklin" <?php if($formVars['county'] == "Franklin") echo 'selected="selected"';?>>Franklin</option>
<option value="Gadsden" <?php if($formVars['county'] == "Gadsden") echo 'selected="selected"';?>>Gadsden</option>
<option value="Gilchrist" <?php if($formVars['county'] == "Gilchrist") echo 'selected="selected"';?>>Gilchrist</option>
<option value="Glades" <?php if($formVars['county'] == "Glades") echo 'selected="selected"';?>>Glades</option>
<option value="Gulf" <?php if($formVars['county'] == "Gulf") echo 'selected="selected"';?>>Gulf</option>
<option value="Hamilton" <?php if($formVars['county'] == "Hamilton") echo 'selected="selected"';?>>Hamilton</option>
<option value="Hardee" <?php if($formVars['county'] == "Hardee") echo 'selected="selected"';?>>Hardee</option>
<option value="Hendry" <?php if($formVars['county'] == "Hendry") echo 'selected="selected"';?>>Hendry</option>
<option value="Hernando" <?php if($formVars['county'] == "Hernando") echo 'selected="selected"';?>>Hernando</option>
<option value="Highlands" <?php if($formVars['county'] == "Highlands") echo 'selected="selected"';?>>Highlands</option>
<option value="Hillsborough" <?php if($formVars['county'] == "Hillsborough") echo 'selected="selected"';?>>Hillsborough</option>
<option value="Holmes" <?php if($formVars['county'] == "Holmes") echo 'selected="selected"';?>>Holmes</option>
<option value="Indian River" <?php if($formVars['county'] == "Indian River") echo 'selected="selected"';?>>Indian River</option>
<option value="Jackson" <?php if($formVars['county'] == "Jackson") echo 'selected="selected"';?>>Jackson</option>
<option value="Jefferson" <?php if($formVars['county'] == "Jefferson") echo 'selected="selected"';?>>Jefferson</option>
<option value="Lafayette" <?php if($formVars['county'] == "Lafayette") echo 'selected="selected"';?>>Lafayette</option>
<option value="Lake" <?php if($formVars['county'] == "Lake") echo 'selected="selected"';?> >Lake</option>
<option value="Lee" <?php if($formVars['county'] == "Lee") echo 'selected="selected"';?>>Lee</option>
<option value="Leon" <?php if($formVars['county'] == "Leon") echo 'selected="selected"';?>>Leon</option>
<option value="Levy" <?php if($formVars['county'] == "Levy") echo 'selected="selected"';?>>Levy</option>
<option value="Liberty" <?php if($formVars['county'] == "Liberty") echo 'selected="selected"';?>>Liberty</option>
<option value="Madison" <?php if($formVars['county'] == "Madison") echo 'selected="selected"';?>>Madison</option>
<option value="Manatee" <?php if($formVars['county'] == "Manatee") echo 'selected="selected"';?>>Manatee</option>
<option value="Marion" <?php if($formVars['county'] == "Marion") echo 'selected="selected"';?>>Marion</option>
<option value="Martin"<?php if($formVars['county'] == "Martin") echo 'selected="selected"';?> >Martin</option>
<option value="Miami-Dade" <?php if($formVars['county'] == "Miami-Dade") echo 'selected="selected"';?>>Miami-Dade</option>
<option value="Monroe" <?php if($formVars['county'] == "Monroe") echo 'selected="selected"';?>>Monroe</option>
<option value="Nassau" <?php if($formVars['county'] == "Nassau") echo 'selected="selected"';?>>Nassau</option>
<option value="Okaloosa" <?php if($formVars['county'] == "Okaloosa") echo 'selected="selected"';?>>Okaloosa</option>
<option value="Okeechobee" <?php if($formVars['county'] == "Okeechobee") echo 'selected="selected"';?>>Okeechobee</option>
<option value="Orange" <?php if($formVars['county'] == "Orange") echo 'selected="selected"';?>>Orange</option>
<option value="Osceola" <?php if($formVars['county'] == "Osceola") echo 'selected="selected"';?>>Osceola</option>
<option value="Palm Beach" <?php if($formVars['county'] == "Palm Beach") echo 'selected="selected"';?>>Palm Beach</option>
<option value="Pasco" <?php if($formVars['county'] == "Pasco") echo 'selected="selected"';?>>Pasco</option>
<option value="Pinellas" <?php if($formVars['county'] == "Pinellas") echo 'selected="selected"';?>>Pinellas</option>
<option value="Polk" <?php if($formVars['county'] == "Polk") echo 'selected="selected"';?>>Polk</option>
<option value="Putnam" <?php if($formVars['county'] == "Putnam") echo 'selected="selected"';?>>Putnam</option>
<option value="Saint Johns" <?php if($formVars['county'] == "Saint Johns") echo 'selected="selected"';?>>Saint Johns</option>
<option value="Saint Lucie" <?php if($formVars['county'] == "Saint Lucie") echo 'selected="selected"';?>>Saint Lucie</option>
<option value="Santa Rosa" <?php if($formVars['county'] == "Santa Rosa") echo 'selected="selected"';?>>Santa Rosa</option>
<option value="Sarasota" <?php if($formVars['county'] == "Sarasota") echo 'selected="selected"';?>>Sarasota</option>
<option value="Seminole" <?php if($formVars['county'] == "Seminole") echo 'selected="selected"';?>>Seminole</option>
<option value="Sumter" <?php if($formVars['county'] == "Sumter") echo 'selected="selected"';?>>Sumter</option>
<option value="Suwannee" <?php if($formVars['county'] == "Suwannee") echo 'selected="selected"';?>>Suwannee</option>
<option value="Taylor" <?php if($formVars['county'] == "Union") echo 'selected="selected"';?>>Taylor</option>
<option value="Union" <?php if($formVars['county'] == "Union") echo 'selected="selected"';?>>Union</option>
<option value="Volusia" <?php if($formVars['county'] == "Volusia") echo 'selected="selected"';?>>Volusia</option>
<option value="Wakulla" <?php if($formVars['county'] == "Wakulla") echo 'selected="selected"';?>>Wakulla</option>
<option value="Walton" <?php if($formVars['county'] == "Walton") echo 'selected="selected"';?>>Walton</option>
<option value="Washington" <?php if($formVars['county'] == "Washington") echo 'selected="selected"';?>>Washington</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_3" >
<label class="description" for="element_3">City </label>
<div>
<input id="element_3" name="city" class="element text medium" type="text" maxlength="255" value="<?php echo $formVars['city']; ?>" required="required"/>
<a class="red">*</a></div>
</li>
<li id="li_4" >
<label class="description" for="element_4">Partners</label>
<div>
<input id="element_4" name="partners" class="element text medium" type="text" maxlength="255" value="<?php echo $formVars['partners']; ?>" />
</div>
</li>
<li id="li_5" >
<?php include("staffInvolved.php"); ?>
</li>
<li id="li_8" >
<label class="description" for="element_8">Number of Attendees </label>
<div>
<input id="element_8" name="numberAttendees" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['numberAttendees']; ?>"/>
</div>
</li>
<li id="li_9" >
<label class="description" for="element_9">Amount of Income </label>
<div>
$<input id="element_9" name="amountIncome" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['amountIncome']; ?>"/>
</div>
<p class="guidelines" id="guide_9"><small>Amount of money earned through fees or donations.</small></p>
</li>
<li id="li_10" >
<label class="description" for="element_2">Comments </label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium" onKeyDown="limitText(this.form.comments,this.form.countdown,2080);"
onKeyUp="limitText(this.form.comments,this.form.countdown,2080);"><?php echo $formVars['comments']; ?></textarea><br/>
<font size="1">(Maximum characters: 2080)<br>
You have <input readonly type="text" name="countdown" size="3" value="2080"> characters left.</font>
</div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close else ?>
<div id="footer">
</div>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "About Us - Opportunities";
include('../_header.php');
?>
<!-- page-content begins -->
<div class="container">
<div class="page-header">
<h1>About Us, <small> Opportunities </small></h1>
</div>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h2>Graduate Assistantships</h2>
<div class="box box-tab box-line">
<strong>University of West Florida</strong>
<p>The FPAN Graduate Assistantship in Public Archaeology is offered to an incoming graduate student in Anthropology or Historical Archaeology at UWF. Support includes tuition during fall and spring semesters (summer support may be available), plus a quarter-time assistantship for the first two years and a half-time assistantship for the third year. During the first two years, the student holding this position will work in the public archaeology program for the FPAN Northwest Region under the supervision of FPAN Associate Director Dr. <NAME>. During the third year the student will work directly with FPAN Executive Director Dr. <NAME> on a thesis representing a substantive contribution to the field of public archaeology or to public archaeology programming in Northwest Florida.</p>
<p>Students interested in this Graduate Assistantship should be prepared to make a three year commitment to the Florida Public Archaeology Network culminating in preparation of a thesis focusing on public archaeology. For more information contact Dr. <NAME> via email: <a href="mailto:<EMAIL>"><EMAIL></a> or phone: 850-595-0050 x101. </p>
<p>To be considered for the UWF Graduate Assistantship in Public Archaeology please submit a Statement of Interest to Dr. <NAME> at <a href="mailto:<EMAIL>"><EMAIL></a> that addresses the following: </p>
<ol>
<li>
<em>How will the knowledge and skills gained through this assistantship help you in achieving your career goals?</em>
</li>
<li>
<em>What experience do you have with presenting archaeology (or similar subjects) to a public audience, public speaking or writing, or working with volunteers?</em>
</li>
</ol>
<p>
For more information on the UWF graduate program in Anthropology/Historical Archaeology, visit the <a href="http://uwf.edu/cassh/departments/anthropology-and-archaeology/graduate-programs/ma-anthropologyhistorical-archaeology/" target=="_blank">Division of Annthropology Graduate Programs page</a>.
<p>All application materials, including the Statement of Interest, are due to the UWF Department of Anthropology by <strong>December 1.</strong></p>
</div>
</div><!-- /.col -->
<div class="col-sm-8 col-sm-offset-2">
<h2>Board Positions</h2>
<div class="box box-tab box-line">
<p>
The Florida Public Archaeology Network is advised by a volunteer public board.
The board consists of 11 members, including 3 members from the University of West
Florida (appointed by the University), 1 member appointed by the Florida Archaeological
Council, 1 member appointed by the Florida Anthropological Society, the State
Archaeologist (ex officio), 2 at-large members who are Florida residents, 2 at large
members who are not Florida residents, and 1 at-large Florida resident who represents
the lay public (not an archaeologist). Applications will be accepted at any time for
any of the 5 at large positions; they will be held for consideration during the mid-year
board meeting prior to the exclusion of the current terms. Applications are also
accepted from members of the Florida Archaeological Society and the Florida Archaeological
Council for individuals interested in representing those organizations, but will be
forwarded to the boards of those organizations for consideration when these positions are
reappointed.
</p>
<p>
At their October 31 2013 meeting the FPAN Board of Directors will consider applications
for 1 At-Large In State member of the Board, 1 At-large Out of State member of the Board,
and the At-Large Lay Person member of the Board, with the appointments to be effective on
July 1, 2014.
</p>
<p>
The Florida Archaeological Council will reappoint their representative to the FPAN Board
in May of 2014, with the appointment to be effective on July 1, 2014.
</p>
<p>
For additional information on the duties of the board, consult the
<a href="http://www.flpublicarchaeology.org/documents/FPAN_MOA.pdf">FPAN Memorandum of
Agreement</a>, or contact Dr. <NAME>, Executive Director, at
<a href="mailto:<EMAIL>"><EMAIL></a> or 850-595-0051.
</p>
<p>
To apply, <a href="http://www.flpublicarchaeology.org/documents/BoardApplication.pdf">
complete the application</a> and send to <NAME> at
<a href="mailto:<EMAIL>"><EMAIL></a>
</p>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content /.container -->
<?php include('../_footer.php'); ?>
<file_sep><?php
include 'appHeader.php';
$eventID = isset($_GET['eventID']) ? mysqli_real_escape_string($dblink, $_GET['eventID']) : null;
$dupe = isset($_GET['dupe']) ? mysqli_real_escape_string($dblink, $_GET['dupe']) : null;
//If new event
if($eventID == null){
$newRecord = true;
$pageTitle = "Add an Event";
$buttonText = "Add Event";
//If form failed to submit, repopulate with stored data
if(isset($_SESSION['eventVars'])){
$eventVars = $_SESSION['eventVars'];
$title = stripslashes($eventVars['title']);
$description = stripslashes($eventVars['description']);
$location = stripslashes($eventVars['location']);
$eventDate = $eventVars['eventDate'];
$eventTimeStart = $eventVars['eventTimeStart'];
$eventTimeEnd = $eventVars['eventTimeEnd'];
$relation = $eventVars['relation'];
$link = $eventVars['link'];
$flyerLink = $eventVars['flyerLink'];
}else{
$title = "";
$description = "";
$location = "";
$eventDate = "";
$eventTimeStart = "";
$eventTimeEnd = "";
$relation = "";
$link = "";
$flyerLink = "";
}
//If eventID was specified (event edit)
}else{
$newRecord = false;
$pageTitle = "Edit an Event";
$buttonText = "Update Event";
$sql = "SELECT * FROM $table WHERE eventID = $eventID;";
$result = mysqli_query($dblink,$sql);
$row = mysqli_fetch_array($result);
$title = stripslashes($row['title']);
$description = stripslashes($row['description']);
$location = stripslashes($row['location']);
$timestampDateTimeStart = strtotime($row['eventDateTimeStart']);
$timestampDateTimeEnd = strtotime($row['eventDateTimeEnd']);
$eventDate = date('m/d/Y', $timestampDateTimeStart);
$eventTimeStart = date('g:i a', $timestampDateTimeStart);
$eventTimeEnd = date('g:i a', $timestampDateTimeEnd);
$relation = $row['relation'];
$link = $row['link'];
$flyerLink = $row['flyerLink'];
}
if($dupe){
$pageTitle = "Duplicate an Event";
$buttonText = "Add Event";
}
include $header;
?>
<div class="container-fluid">
<div class="page-header">
<h1><?php echo $pageTitle ?></h1>
</div>
<div class="row">
<div class="col-sm-8">
<?php if(isset($msg)) echo '<div class="alert alert-danger text-center">'.$msg.'</div>'; ?>
<!--********* BEGIN FORM ********-->
<form class="form-horizontal" role="form" action="processEdit.php" method="POST" enctype="multipart/form-data">
<div class="row">
<?php
if(!$newRecord && !$dupe) {
echo '<input type="hidden" name="eventID" value="'.$eventID.'">';
echo '<p class="col-xs-12 text-center"><a class="btn btn-sm btn-primary" href="eventEdit.php?eventID='.$eventID.'&dupe=true">Duplicate this event</a></p>';
}
?>
<div class="form-group">
<div class="col-sm-4">
<label for="eventDate" class="control-label">
Date:
</label>
</div>
<div class="col-sm-6 col-xs-10">
<input class="form-control text-center" type="text" name="eventDate" maxlength="10" value="<?php echo $eventDate; ?>" required="yes" />
</div>
<div class="col-sm-2 col-xs-2 text-left">
<span class="required">*</span>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-5">
<label for="eventTimeStart" class="control-label">
Start Time:
</label>
</div>
<div class="col-sm-5 col-xs-10">
<input class="form-control text-center" type="text" name="eventTimeStart" maxlength="8" value="<?php echo $eventTimeStart; ?>" placeholder="hh:mm am/pm" required="yes" />
</div>
<div class="col-sm-2 col-xs-2 text-left">
<span class="required">*</span>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-5">
<label for="eventTimeEnd" class="control-label">
End Time:
</label>
</div>
<div class="col-sm-5 col-xs-10">
<input class="form-control text-center" type="text" name="eventTimeEnd" maxlength="8" value="<?php echo $eventTimeEnd; ?>" placeholder="hh:mm am/pm" required="yes" />
</div>
<div class="col-sm-2 col-xs-2 text-left">
<span class="required">*</span>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4">
<label for="relation" class="control-label">
FPAN is:
</label>
</div>
<div class="col-sm-7 col-xs-11">
<select class="form-control" name="relation">
<?php
if($relation == "hosting")
echo "<option value=\"hosting\" selected=\"selected\">hosting this event. ";
else
echo "<option value=\"hosting\">hosting this event. ";
if($relation == "co-hosting")
echo "<option value=\"co-hosting\" selected=\"selected\">co-hosting this event. ";
else
echo "<option value=\"co-hosting\">co-hosting this event. ";
if($relation == "attending")
echo "<option value=\"attending\" selected=\"selected\">attending this event. ";
else
echo "<option value=\"attending\">attending this event. ";
if($relation == "sharing")
echo "<option value=\"sharing\" selected=\"selected\">sharing this event. ";
else
echo "<option value=\"sharing\">sharing this event. ";
if($relation == "participating in")
echo "<option value=\"participating in\" selected=\"selected\">participating in this event. ";
else
echo "<option value=\"participating in\">participating in this event. ";
echo "</option>";
?>
</select>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4">
<label for="title" class="control-label">
Title:
</label>
</div>
<div class="col-sm-7 col-xs-10">
<input class="form-control" type="text" name="title" size="44" maxlength="70" value="<?php echo $title?>" required="yes" />
</div>
<div class="col-sm-1 col-xs-2 text-left">
<span class="required">*</span>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4">
<label for="location" class="control-label">
Location:
</label>
</div>
<div class="col-sm-7 col-xs-10">
<input class="form-control" type="text" name="location" size="44" maxlength="90" value="<?php echo $location?>" required="yes"/>
</div>
<div class="col-sm-1 col-xs-2 text-left">
<span class="required">*</span>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4">
<label for="link" class="control-label">
Related Link:
</label>
</div>
<!-- Not Required -->
<div class="col-sm-7 col-xs-12">
<input class="form-control" type="url" name="link" size="44" maxlength="200" value="<?php echo $link?>" />
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4">
<label for="flyerFile" class="control-label">
Flyer (Max 5mb):
</label>
</div>
<!-- Not Required -->
<div class="col-sm-7 col-xs-12">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<?php
if(!$flyerLink)
echo '<input class="form-control" name="flyerFile" type="file" />';
else
echo '<input class="form-control" type="text" name="flyerLink" size="44" maxlength="200" value="'. $flyerLink.'"/>';
?>
</div>
</div><!-- /.form-group -->
<div class="form-group">
<div class="col-xs-12">
<label for="description" class="control-label">
Description:
</label>
<textarea class="form-control" name="description" cols="46" rows="8" maxlength="1200" required="yes"><?php echo $description?></textarea>
</div>
</div><!-- /.form-group -->
<div class="form-group">
<div class="col-xs-12 text-center">
<input type="submit" value="<?php echo $buttonText?>" class="btn btn-primary"/>
<input type="reset" value="Reset" class="btn btn-primary"/> <!-- Doesnt work after first submit because values are stored in PHP array -->
</div>
</div><!-- /.form-group -->
</div> <!-- /.row -->
</form> <!-- /form -->
</div> <!-- /.col -->
<div class="col-sm-4">
<?php include '../events/calendar.php' ?>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container -->
<?php include $footer; ?><file_sep><?php
$pageTitle = "Connect With Us";
include('_header.php');
?>
<div class="page-content container connect">
<div class="page-header"><h1>Connect<small> with Us </small> </h1></div>
<div class="row">
<h2 class="text-center">Social Media <small>by Region</small></h2>
<div class="col-sm-6 col-md-3">
<div class="box-tab nw-tab">
<h2>Northwest</h2>
<h3 class="text-left"><a href="https://www.facebook.com/FPANnorthwest"><i class="fa fa-facebook-square fa-lg"></i> Facebook </a></h3>
<h3 class="text-left"><a href="https://twitter.com/FPANNorthwest"><i class="fa fa-twitter-square fa-lg"></i> Twitter </a></h3>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region nw-btn" href="nwrc"> Northwest Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab nc-tab">
<h2>North Central</h2>
<h3 class="text-left"><a href="https://www.facebook.com/FPANnorthcentral"><i class="fa fa-facebook-square fa-lg"></i> Facebook </a></h3>
<h3 class="text-left"><a href="https://twitter.com/FPANNrthcentral"><i class="fa fa-twitter-square fa-lg"></i> Twitter </a></h3>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region nc-btn" href="ncrc"> North Central Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab ne-tab">
<h2>Northeast</h2>
<h3 class="text-left"><a href="https://www.facebook.com/FPANnortheast"><i class="fa fa-facebook-square fa-lg"></i> Facebook </a></h3>
<h3 class="text-left"><a href="https://twitter.com/FPANNortheast"><i class="fa fa-twitter-square fa-lg"></i> Twitter </a></h3>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region ne-btn" href="ncrc"> Northeast Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab ec-tab">
<h2>East Central</h2>
<h3 class="text-left"><a href="https://www.facebook.com/FPANeastcentral"><i class="fa fa-facebook-square fa-lg"></i> Facebook </a></h3>
<h3 class="text-left"><a href="https://twitter.com/FPANeastcentral"><i class="fa fa-twitter-square fa-lg"></i> Twitter </a></h3>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region ec-btn" href="ecrc"> East Central Region</a> website.</p>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
<div class="row">
<div class="col-sm-6 col-md-3">
<div class="box-tab c-tab">
<h2>Central</h2>
<h3 class="text-left"><a href="https://www.facebook.com/FPANcentral"><i class="fa fa-facebook-square fa-lg"></i> Facebook </a></h3>
<h3 class="text-left"><a href="https://twitter.com/FPANcentral"><i class="fa fa-twitter-square fa-lg"></i> Twitter </a></h3>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region c-btn" href="crc"> Central Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab wc-tab">
<h2>West Central</h2>
<h3 class="text-left"><a href="https://www.facebook.com/FPANwestcentral"><i class="fa fa-facebook-square fa-lg"></i> Facebook </a></h3>
<h3 class="text-left"><a href="https://twitter.com/FPANwestcentral"><i class="fa fa-twitter-square fa-lg"></i> Twitter </a></h3>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region wc-btn" href="wcrc"> West Central Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab sw-tab">
<h2>Southwest</h2>
<h3 class="text-left"><a href="https://www.facebook.com/FPANsouthwest"><i class="fa fa-facebook-square fa-lg"></i> Facebook </a></h3>
<h3 class="text-left"><a href="https://twitter.com/FPANsouthwest"><i class="fa fa-twitter-square fa-lg"></i> Twitter </a></h3>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region sw-btn" href="swrc"> Southwest Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab se-tab">
<h2>Southeast</h2>
<h3 class="text-left"><a href="https://www.facebook.com/FPANsoutheast"><i class="fa fa-facebook-square fa-lg"></i> Facebook </a></h3>
<h3 class="text-left"><a href="https://twitter.com/FPANsoutheast"><i class="fa fa-twitter-square fa-lg"></i> Twitter </a></h3>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region se-btn" href="serc"> Southeast Region</a> website.</p>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content -->
<?php include('_footer.php'); ?>
<file_sep><?php include('_header.php'); ?>
<div class="container">
<div class="page-header text-center name"><NAME></div>
<p class="text-center">Web Designer, Web Developer<br/><a href="mailto:<EMAIL>"><EMAIL></a></p>
<div class="row">
<div class="col-sm-12">
<div class="jumbotron">
<h2>Hi. Looking for a web guy?</h2>
<p>I design responsive websites by hand in <strong>HTML5</strong> & <strong>CSS3</strong> using the<strong>Bootstrap</strong> framework, and develop back-end support in <strong>PHP</strong> & <strong>MySQL</strong>. I also have hands-on experience working in <strong>Objective-C</strong> on <strong>iOS</strong> applications.</p>
<p><a class="btn btn-lg btn-primary" href="contact.php">Let's talk »</a></p>
</div>
</div><!--/.col-->
<div id="resume" class="col-sm-12">
<div class="jumbotron">
<div class="row">
<div class="col-md-6 col-md-push-6 jumbo-top row ">
<div class="col-md-12 col-sm-5 col-xs-12">
<h2>Skills</h2>
<ul>
<li>HTML5</li>
<li>CSS3</li>
<li>PHP</li>
<li>MySQL</li>
<li>Java</li>
<li>JavaScript + jQuery</li>
<li>XML</li>
<li>Objective-C, iOS</li>
</ul>
</div>
<div class="col-md-12 col-sm-7 col-xs-12">
<h2>Education</h2>
<h3>B.S. Information Technology</h3>
<p>
<em>University of West Florida</em>
</p>
<p>Graduated 2008</p>
</div>
</div><!-- /.col /.row -->
<div class="col-md-6 col-md-pull-6">
<h2>Experience</h2>
<h3>Web Architect</h3>
<p><small><em><a href="http://fpan.us/new">Florida Public Archaeology Network</a></em></small></p>
<p><strong>Feb 2010 - Present</strong></p>
<p>
<ul>
<li>Designed, developed, and maintained statewide web-presence of multiple sites with focus on responsive design.</li>
<li>Developed database-driven PHP applications for staff activity reporting.</li>
<li>Developed several iPhone applications to promote archaeology and heritage tourism across the state.</li>
</ul>
</p>
<h3>Web Developer</h3>
<p><small><em>University of West Florida Libraries</em></small></p>
<p><strong>Sep 2008 - Feb 2010</strong></p>
<p>
<ul>
<li>Maintained the libraries’ website and blog.</li>
<li>Developed database-driven web applications in Coldfusion.</li>
<li>Photography, photo restoration, video editing, assisting library patrons with technology needs.</li>
</ul>
</p>
</div><!--/.col-->
</div><!-- /.row -->
<p class="text-center">
<a href="JasonKent_resume.pdf" class="btn btn-primary btn-lg" target="_blank">
Download as PDF »
</a>
</p>
</div><!-- /.jumbotron -->
</div>
<div class="col-sm-12">
<div class="jumbotron">
<h2>Looking for a different skillset?</h2>
<p> I've got one word for you friend: <em>neuroplasticity</em>.</p>
<p> I'm always ready and willing to learn new technologies.</p>
</div>
</div><!--/.col-->
</div><!--/.row-->
</div> <!-- /container -->
<?php include('_footer.php'); ?>
<file_sep><?php
if (!defined('WEBPATH')) die();
require_once('normalizer.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="no" name="apple-mobile-web-app-capable" />
<!-- this will not work right now, links open safari -->
<meta name="format-detection" content="telephone=no">
<meta content="index,follow" name="robots" />
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type" />
<link href="<?php echo $_zp_themeroot ?>/images/homescreen.png" rel="apple-touch-icon" />
<meta content="minimum-scale=1.0, width=device-width, maximum-scale=0.6667, user-scalable=no" name="viewport" />
<link href="<?php echo $_zp_themeroot ?>/css/style.css" rel="stylesheet" type="text/css" />
<script src="<?php echo $_zp_themeroot ?>/javascript/functions.js" type="text/javascript"></script>
<script src="<?php echo $_zp_themeroot ?>/javascript/rotate.js" type="text/javascript"></script>
<title><?php echo getBareGalleryTitle(); ?> > <?php echo getBareAlbumTitle(); ?></title>
<?php zp_apply_filter("theme_head");?>
<title><?php echo getBareGalleryTitle(); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
printRSSHeaderLink('Gallery','Gallery RSS');
$archivepageURL = htmlspecialchars(getGalleryIndexURL());
?>
<script type="application/x-javascript">
addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false);
function hideURLbar(){
window.scrollTo(0,1);
}
</script>
</head>
<body class="portrait">
<script type="text/javascript" language="JavaScript">
updateOrientation();
</script>
<div id="container">
<div id="content">
<div style="margin:5px;">
<h2 align="center"> <?php echo getBareAlbumTitle(); ?> </h2>
<?php printAlbumDesc(true); ?>
</div>
<?php
$first = true;
$image_check = getNumImages();
$main_title = getBareAlbumTitle();
$count = 0;
while (next_album()) {
if ($first) {
echo '<div class="graytitle">' ;
if ($image_check > 0) {
//echo gettext('Sub-Albums');
}else{
//echo $main_title;
}
echo '</div>';
?>
<br/>
<div class="galleryalbum">
<ul class="autolist">
<?php
$first = false;
}
?>
<li class="withimage"> <a href="<?php echo htmlspecialchars(getAlbumLinkURL());?>" class="img">
<?php printCustomAlbumThumbImage(getBareAlbumTitle(), null, 480, 120, 480, 120); ?>
<span class="folder_info">
<?php //Display number of subalbums and photos overlay
/*
$anumber = getNumAlbums();
$inumber = getNumImages();
if ($anumber > 0 || $inumber > 0) {
echo '<em>';
if ($anumber == 0) {
if ($inumber != 0) {
printf(ngettext('%u photo','%u photos', $inumber), $inumber);
}
} else if ($anumber == 1) {
if ($inumber > 0) {
printf(ngettext('1 album, %u photo','1 album, %u photos', $inumber), $inumber);
} else {
printf(gettext('1 album'));
}
} else {
if ($inumber == 1) {
printf(ngettext('%u album, 1 photo','%u albums, 1 photo', $anumber), $anumber);
} else if ($inumber > 0) {
printf(ngettext('%1$u album, %2$s','%1$u albums, %2$s', $anumber), $anumber, sprintf(ngettext('%u photo','%u photos',$inumber),$inumber));
} else {
printf(ngettext('%u album','%u albums', $anumber), $anumber);
}
}
echo '</em>';
} */
?>
</span>
<span class="name"><?php echo getBareAlbumTitle();?></span><span class="arrow_img"></span> </a>
<?php $count++; ?>
</li>
<?php
}
if (!$first) {
echo '<li class="hidden autolisttext"><a class="noeffect" href="#">Load more albums...</a></li>';
echo "</ul></div>";
}
/*
if (getNumImages() > 0) {
echo '<div class="graytitle">' ;
echo getBareAlbumTitle();
echo '</div>';
}*/
?>
<ul class="slideset">
<?php
$firstImage = null;
$lastImage = null;
if ($myimagepage > 1) {
?>
<li class="thumb"><span><em style="background-image:url('<?php echo $_zp_themeroot ?>/images/moreslide_prev.gif');">
<a href="<?php echo htmlspecialchars(getPrevPageURL()); ?>"><?php echo gettext('Next page'); ?></a></em></span></li>
<?php
}
while (next_image(false, $firstPageImages)) {
if (is_null($firstImage)) {
$lastImage = imageNumber();
$firstImage = $lastImage;
} else {
$lastImage++;
}
$iw = 75;
$ih = 75;
$cw = 75;
$ch = 75;
echo '<li class="thumb"><span>';
//begin section added by <NAME>
if (isImageVideo()){
echo '<span class="movie"><a href="' . htmlspecialchars(getImageLinkURL()) . '" title="'
. getAnnotatedImageTitle() . '" style="background:#fff;"></a></span>';
}
//end section added by <NAME>
echo '<em style="background-image:url(' . htmlspecialchars($_zp_current_image->getCustomImage(NULL, $iw, $ih, $cw, $ch, NULL, NULL, true))
. '); "><a href="' . htmlspecialchars(getImageLinkURL()) . '" title="' . getAnnotatedImageTitle()
. '" style="background:#fff;">"'.getImageTitle().'"</a></em></span></li>';
}
if (!is_null($lastImage) && $lastImage < getNumImages()) {
$np = getCurrentPage()+1;
?>
<li class="thumb">
<span><em style="background-image:url('<?php echo $_zp_themeroot ?>/images/moreslide_next.gif');">
<a href="<?php echo htmlspecialchars(getPageURL($np, $np)); ?>"><?php echo gettext('Next page'); ?></a></em>
</span>
</li>
<?php
}
?>
</ul>
</div>
<?php if(is_null($firstImage)) { ?>
<div id="footer"
<?php if($count < 3)
echo 'style="margin-top:100px!important;border-top:1px solid #e1e1e1;list-style:none"';
else if($count < 4)
echo 'style="margin-top:80px!important;border-top:1px solid #e1e1e1;list-style:none"';
?>>
<?php //echo gettext('Theme By <NAME>.'); ?> <?php printZenphotoLink(); ?> </div>
<?php }else{ ?>
<div id="footerbar" <?php if(($lastImage - $firstImage) < 12)
echo 'style="margin-top:76px!important"';
?>>
<div id="foottext">
<?php
if (!is_null($firstImage)) {
echo '<em class="count">';
printf(gettext('Photos %1$u-%2$u of %3$u'), $firstImage, $lastImage, getNumImages());
echo "</em>";
}
?>
</div>
<div id="bottomleftnav">
<?php if (hasPrevPage()) { ?>
<a href="<?php echo htmlspecialchars(getPrevPageURL()); ?>"><img alt="<?php echo gettext('prev page'); ?>" src="<?php echo $_zp_themeroot ?>/images/navleft_f.png"/></a>
<?php } ?>
</div>
<div id="bottomrightnav">
<?php
if (!is_null($lastImage) && $lastImage < getNumImages()) {
$np = getCurrentPage()+1;
?>
<a href="<?php echo htmlspecialchars(getPageURL($np, $np)); ?>"><img alt="<?php echo gettext('next page'); ?>" src="<?php echo $_zp_themeroot ?>/images/navright_f.png"/></a>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
<?php
//Show top nav only if not being viewed through DCW app
$appView = $_GET['appView'];
if(!$appView){
?>
<div id="topbar">
<div id="leftnav">
<?php
$album = $_zp_current_album;
$parent = $album->getParent();
if(empty($parent)){ ?>
<a href="<?php echo htmlspecialchars(getGalleryIndexURL(false));?>">
<img alt="<?php echo gettext('Main Index'); ?>" src="<?php echo $_zp_themeroot ?>/images/home.png"/></a>
<a href="<?php echo htmlspecialchars(getGalleryIndexURL());?>"><?php echo gettext('Home');?></a>
<?php }else{ ?>
<a href="<?php echo htmlspecialchars(getGalleryIndexURL(false));?>">
<img alt="<?php echo gettext('Main Index'); ?>" src="<?php echo $_zp_themeroot ?>/images/home.png"/></a>
<a href="<?php echo htmlspecialchars(getAlbumLinkURL($parent)); ?>">Back</a>
<?php } ?>
</div>
<?php
$nextalbum = getNextAlbum();
if(!empty($nextalbum)){ ?>
<div id="rightnav">
<a href="<?php echo htmlspecialchars(getNextAlbumURL());?>"><?php echo gettext('Next Album');?></a>
</div>
<?php } ?>
</div>
<?php } ?>
</body>
</html>
<file_sep><?php
$pageTitle = "Explore";
$county = isset($_GET['county']) ? $_GET['county'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<!-- ********* ****************** ********** -->
<!-- ********* Explore Baker County ********** -->
<!-- ********* ****************** ********** -->
<?php if($county == 'baker'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Baker County</small></h1>
</div>
<!-- <div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
</div>
</div> -->
<div class="col-md-12">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.bakercountyfl.org/">Baker County</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Columbia County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'columbia'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Columbia County</small></h1>
</div>
<!-- <div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
</div>
</div> -->
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.columbiacountyfla.com/">Columbia County Online</a></li>
<li><a target="_blank" href="http://www.springsrus.com/">Columbia County Tourist Development Council</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/olusteebattlefield/default.cfm">Olustee Battlefield Historic State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/ichetuckneesprings/default.cfm">Ichetucknee Springs State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Dixie County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'dixie'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Dixie County</small></h1>
</div>
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://dixie.fl.gov/">Dixie County Website</a></li>
<li><a target="_blank" href="http://www.dixiecounty.org/">Things to do in Dixie County</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Heritage Trails</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.dep.state.fl.us/gwt/state/nat/default.htm">Nature Coast State Trail-Fanning Springs (Rails-to-Trails)</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Franklin County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'franklin'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Franklin County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.franklincountyflorida.com/">Franklin County Government</a></li>
<li><a target="_blank" href="http://www.saltyflorida.com/">Franklin County Tourist Development Council</a></li>
<li><a target="_blank" href="http://www.cityofapalachicola.com/">City of Apilachicola</a></li>
<li><a target="_blank" href="http://www.apalachicolabay.org/">Apilachicola Bay</a></li>
<li><a target="_blank" href="http://mycarrabelle.com/">City of Carrabelle</a></li>
<li><a target="_blank" href="http://carrabelle.org/">Carrabelle Chamber of Commerce</a></li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://exploresouthernhistory.com/fortgadsden.html">Fort Gadsden</a></li>
</ul>
</div>
<h2>Historic Districts</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.apalachicolabay.org/index.cfm/m/14/">Historic Downtown Apalachicola</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/stgeorgeisland/default.cfm">Dr. <NAME> St. George Island State Park </a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/ormanhouse/default.cfm">Ormon House State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/baldpoint/default.cfm">Bald Point State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/johngorriemuseum/default.cfm">John Gorrie Museum State Park</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.ammfl.org/">Apalachicola Maritime Museum</a></li>
<li><a target="_blank" href="http://crookedriverlighthouse.org/">Crooked River Lighthouse Keeper's House Museum</a></li>
<li><a target="_blank" href="http://www.campgordonjohnston.com/museum.htm">Camp Gordon Johnston Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Gadsden County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'gadsden'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Gadsden County</small></h1>
</div>
<div class="col-sm-8 col-sm-push-2">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.gadsdengov.net/">Gadsden County Website</a></li>
<li><a target="_blank" href="http://www.gadsdenfla.com/">Gadsden County Chamber of Commerce</a></li>
</ul>
</div>
</div>
<!-- ********* ****************** *************** -->
<!-- ********* Explore Hamilton County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'hamilton'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Hamilton County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.hamiltoncountyflorida.com/">Hamilton County Website</a></li>
<li><a target="_blank" href="http://www.hamiltoncountyflorida.com/cd_tdc.aspx">Tourist Development Council</a></li>
<li><a target="_blank" href="http://www.hamiltoncountycoc.com/">Chamber of Commerce</a></li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li>
<a target="_blank" href="http://www.telfordhotel.net/">The Telford Hotel</a>
</li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/stephenfoster/">Stephen Foster Folk Culture Center State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/bigshoals/default.cfm">Big Shoals State Park</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.hamiltoncountyflorida.com/cd_historical.aspx">Hamilton County Historical Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Jefferson County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'jefferson'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Jefferson County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.jeffersoncountyfl.gov/">Jefferson County Website</a></li>
</ul>
</div>
<h2>Historic Tours</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.dixieplantation.org/">Dixie Plantation Tour</a></li>
<li><a target="_blank" href="http://www.historicmonticelloghosttours.com/">Historic District Tour and Historic Monticello Ghost Tours</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/econfinariver/default.cfm">Econfina River State Park</a></li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.monticellofloridaoperahouse.com/home.cfm">Monticello Opera House</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** ****************-->
<!-- ********* Explore Lafayette County ********** -->
<!-- ********* ****************** **************** -->
<?php }elseif($county == 'lafayette'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Lafayette County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li>
<a target="_blank" href="http://www.lafayettecountyflorida.org/index.cfm/referer/content.contentList/ID/532/">Layfayette County Website</a>
</li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.reference.com/browse/adams+bridge"><NAME>ams Bridge</a></li>
<li><a target="_blank" href="http://www.jud10.org/Courthouses/Lafayette/lafayette.htm">Old Lafayette County Courthouse</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/lafayettebluesprings/default.cfm">Lafayette Blue Spring State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Leon County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'leon'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Leon County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://cms.leoncountyfl.gov/">Leon County Website</a></li>
<li><a target="_blank" href="http://www.talgov.com/">City of Tallahassee</a></li>
<li><a target="_blank" href="http://www.visittallahassee.com/">Visit Tallahassee</a></li>
<li><a target="_blank" href="http://www.cocanet.org/">Council on Culture & Arts</a></li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.flhistoriccapitol.gov/">Florida Historic State Capitol</a></li>
<li><a target="_blank" href="http://www.missionsanluis.org/">Mission San Luis</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/lakejackson/default.cfm">Lake Jackson Mounds State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/naturalbridge/">Natural Bridge Battlefield Historic State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/letchworth/default.cfm">Letchworth-Love Mounds State Park</a></li>
<li><a target="_blank" href="http://www.exploresouthernhistory.com/oldfortpark.html">Old Fort Park (Fort Houston)</a></li>
<li><a target="_blank" href="http://www.traillink.com/trail/tallahassee---st-marks-historic-railroad-state-trail.aspx">Tallahassee/St. Marks Railroad (Rails-to-Trails)</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/laketalquin/default.cfm">Lake Talquin State Park</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.museumoffloridahistory.com/">Museum of Florida History</a></li>
<li><a target="_blank" href="http://www.rileymuseum.org/">Riley House Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Liberty County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'liberty'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Liberty County</small></h1>
</div>
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/torreya/">Torreya State Park</a></li>
</ul>
</div>
</div>
<!-- ********* ****************** *************** -->
<!-- ********* Explore Madison County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'madison'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Madison County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.madisoncountyfl.com/">Madison County Website</a></li>
<li><a target="_blank" href="http://www.madisonfl.org/">Chamber of Commerce</a></li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://madisonfl.org/details_enhanced.php?genListingId=337">Wardlaw-Smith-Goza Mansion</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Museums and Cultural Centers</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.treasuresofmadisoncounty.com/">The Treasures of Madison County</a></li>
</ul>
</div>
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/madisonbluespring/default.cfm">Madison Blue Spring State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Suwannee County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'suwannee'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Suwannee County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.suwcounty.org/">Suwannee County Website</a></li>
<li><a target="_blank" href="http://www.suwanneechamber.com/">Chamber of Commerce</a></li>
<li><a target="_blank" href="http://www.visitsuwanneecounty.com/">Visit Suwannee County</a></li>
</ul>
</div>
<h2>Heritage Trails</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.traillink.com/trail/suwannee-river-greenway-at-branford.aspx">Suwannee River Greenway at Branford (Rails-to-Trails)</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/suwanneeriver/default.cfm">Suwannee River State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/troyspring/default.cfm">Troy Spring State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/peacocksprings/default.cfm">Peacock Spring State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/fanningsprings/default.cfm">Fanning Springs State Park</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.suwanneemuseum.org/">Suwannee Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Taylor County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'taylor'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Taylor County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.taylorcountygov.com/">Taylor County Website</a></li>
<li><a target="_blank" href="http://www.taylorcountychamber.com/">Chamber of Commerce</a></li>
<li><a target="_blank" href="http://www.taylorflorida.com/">Tourism Development Council</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.funandsun.com/parks/ForestCapital/forestcapital.html">Cracker Homestead Museum and Forest Capital State Park Museum</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/forestcapital/default.cfm">Forest Capital Museum State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Union County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'union'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Union County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.unioncounty-fl.gov/">Union County Website</a></li>
<li><a target="_blank" href="http://www.northfloridachamber.com/county-union.php">Chamber of Commerce</a></li>
</ul>
</div>
</div>
<!-- ********* ****************** *************** -->
<!-- ********* Explore Wakulla County ********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'wakulla'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Wakulla County</small></h1>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.mywakulla.com/">Wakulla County Website</a></li>
<li><a target="_blank" href="http://cityofstmarks.com/">City of St. Marks</a></li>
<li><a target="_blank" href="http://wakullacountychamber.com/">Chamber of Commerce</a></li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.fws.gov/saintmarks/">St. Marks Lighthouse (St. Marks Wildlife Refuge)</a></li>
<li><a target="_blank" href="http://www.taplines.net/gfa/gfa.html">Sopchoppy GF&A Railroad Depot</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/wakullasprings/default.cfm">Edward Ball Wakulla Springs State Park and Lodge</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/sanmarcos">San Marco de Apalachee Historic State Park</a></li>
<li><a target="_blank" href="http://www.dep.state.fl.us/gwt/guide/regions/panhandleeast/trails/tallahassee_stmarks.htm">Tallahassee/St. Marks Railroad State Park (Rails-to-Trails)</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/ochlockoneeriver/default.cfm">Ochlocknee River State Park</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://flpublicarchaeology.org/ncrc/www.wakullahistory.org">Wakulla County Historical Society Museum and Archives</a></li>
</ul>
</div>
</div><!-- /.col -->
<?php }else{ ?>
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-12 col-md-8 col-md-push-2">
<p>
The North Central Region offers many amazing historical and archaeological sites that you can visit. Click on any county below to discover sites in your area.
<hr/>
<!-- Interactive SVG Map -->
<div id="ncmap" class="center-block"></div>
</p>
<!-- <hr/>
<div class="col-sm-12 text-center">
<div class="image"><img src="" alt="" class="img-responsive" width="400" height="464"></div>
</div> -->
</div>
</div><!-- /.row -->
<?php } ?>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#ncmap').mapSvg({
source: 'images/nc_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //Northwest Region Marker
xy:[78,165],
tooltip:'North Central Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Gadsden' :{popover:'<h3>Gadsden</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=gadsden"> Explore Gadsden County</a></p>'},
'Leon' :{popover:'<h3>Leon</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=leon"> Explore Leon County</a></p>'},
'Liberty' :{popover:'<h3>Liberty</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=liberty"> Explore Liberty County</a></p>'},
'Franklin' :{popover:'<h3>Franklin</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=franklin"> Explore Franklin County</a></p>'},
'Wakulla' :{popover:'<h3>Wakulla</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=wakulla"> Explore Wakulla County</a></p>'},
'Jefferson' :{popover:'<h3>Jefferson</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=jefferson"> Explore Jefferson County</a></p>'},
'Madison' :{popover:'<h3>Madison</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=madison"> Explore Madison County</a></p>'},
'Taylor' :{popover:'<h3>Taylor</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=taylor"> Explore Taylor County</a></p>'},
'Hamilton' :{popover:'<h3>Hamilton</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=hamilton"> Explore Hamilton County</a></p>'},
'Suwannee' :{popover:'<h3>Suwannee</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=suwannee"> Explore Suwannee County</a></p>'},
'Lafayette' :{popover:'<h3>Lafayette</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=lafayette"> Explore Lafayette County</a></p>'},
'Dixie' :{popover:'<h3>Dixie</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=dixie"> Explore Dixie County</a></p>'},
'Columbia' :{popover:'<h3>Columbia</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=columbia"> Explore Columbie County</a></p>'},
'Baker' :{popover:'<h3>Baker</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=baker"> Explore Baker County</a></p>'},
'Union' :{popover:'<h3>Union</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=union"> Explore Union County</a></p>'},
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Presentations";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?> <small>Request a Speaker</small></h1>
</div>
<div class="box-dash">
<div class="col-sm-12 text-center">
<div class="image">
<img src="images/presentations.jpg" alt="Speaker presentations." class="img-responsive" width="300" height="230" />
</div>
</div>
<p>FPAN can help facilitate speakers for meetings of your civic group, community organization,
youth club, or heritage society, and for lecture series and special events. In addition to staff,
we also can draw on the expertise of University of West Florida professors and graduate
students as well as on local professional historians and archaeologists.</p>
<p>Most presentations last about 30-45 minutes with additional time for questions, although
programs usually can be tailored for your needs. Specific topics are dependent on speaker
availability, so book early! There is no charge for presentations, although donations are
gratefully accepted to support FPAN educational programs.</p>
<p>Take a look at our offerings, then <a href="https://casweb.wufoo.com/forms/northwest-speaker-request-form/">
submit the form below</a> and let us
know what you’d like to learn about! If you don’t see what you’re looking for, ask us and we’ll do our
best to accommodate you.</p>
<p class="text-center"><em>Know what you want?</em> <br/> <a class="btn btn-primary"
href="https://casweb.wufoo.com/forms/northwest-speaker-request-form/" target="_blank">Submit a Speaker Request Form</a> </p>
</div>
<h2>Presentation Topics</h2>
<div class="box-tab row">
<div class="col-sm-6">
<ul>
<li><a href="#snf">Shipwrecks of Northwest Florida</a></li>
<li><a href="#sp">Shipwrecks of Pensacola</a></li>
<li><a href="#sbr">Shipwrecks of the Blackwater River</a></li>
<li><a href="#ussm">USS <em>Massachusetts</em>: History and Archaeology of the Nation’s Oldest Battleship</a></li>
<li><a href="#hrt">History is the Real Treasure: The 1733 Spanish Galleon Trail</a></li>
<li><a href="#empt">The Emanuel Point Ships: Florida’s Earliest Shipwrecks Associated with the 1559 </a></li>
<li><a href="#mits">Museums in the Sea: Florida’s Underwater Archaeological Preserves</a></li>
<li><a href="#dhpht">Diving, Historic Preservation, and Heritage Tourism</a></li>
<li><a href="#opip">Our Past in Peril: Florida’s Trouble with Treasure</a></li>
<li><a href="#ttales">Tombstone Tales: Cemeteries, Symbols, and Stories</a></li>
<li><a href="#intro">Introduction to Archaeology</a></li>
<li><a href="#remote">Remote Sensing in Archaeology</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#smack">Talking Smack: The Sailing Vessels of Pensacola’s Red Snapper Fishing Industry</a></li>
<li><a href="#erbd">Exploring Race-Based Differences in the Post-Civil War Red Snapper Fishing Industry</a></li>
<li><a href="#mmm">Mosquitos, Muggles, and Museums: Exploring Florida’s Archaeology with Geocaching</a></li>
<li><a href="#pirates">Pirates! The Last Scourge of the Gulf: An Exhibit</a></li>
<li><a href="#uf">Unearthing Florida</a></li>
<li><a href="#dfah">Dear Friends at Home: Accounts of a Union Soldier in Pensacola</a></li>
<li><a href="#caves">Archaeology and the Use of Caves in Florida</a></li>
<li><a href="#pssbr">Pirates, Slave Smugglers, and Blockade Runners of the Gulf Coast</a></li>
<li><a href="#archnwf">Archaeology of Northwest Florida: A Tour Through our Heritage</a></li>
<li><a href="#deadmans">Deadman's Island: Pensacola Bay's Unique Landform</a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div class="col-sm-12">
<h3 id="snf">Shipwrecks of Northwest Florida</h3>
<p>The Panhandle of Florida is the site of hundreds of historic shipwrecks, the result of
centuries of maritime commerce, conflict, and travel. Three of these wrecks are featured in
this presentation: USS Massachusetts, the nation’s oldest battleship sunk for target practice
off Pensacola; SS Tarpon, a merchant vessel famous for its weekly trips between Mobile
and Panama City until it was lost in a gale; and Vamar, sunk at Port St Joe under mysterious
circumstances during World War II.</p>
</div>
<div class="col-sm-12">
<h3 id="sp">Shipwrecks of Pensacola</h3>
<p>The excellent port of Pensacola was long the focus of European rivalries in the New World
because control of the harbor helped ensure dominance of the northern Gulf Coast.
Shipwrecks litter the bay and surrounding waterways, many of which have been identified
and archaeologically investigated. This presentation describes a variety of Pensacola’s
historic shipwrecks from Pensacola’s Spanish, British, early American, and Industrial
Expansion periods.</p>
</div>
<div class="col-sm-12">
<h3 id="sbr">Shipwrecks of the Blackwater River</h3>
<p>A major tributary of Pensacola Bay, the Blackwater River flows through the pine forests and
fertile uplands of Santa Rosa and Okaloosa Counties. Historically, commerce along the river included
shipyards, brick kilns, and lumber mills, all of which used the river for transport of
supplies and products. The remains of many of the watercraft engaged in these industries
lie hidden in the dark water, some of which have been archaeologically investigated. This
lecture describes these vessels, ranging from lumber schooners to steam tugs to snapper
smacks.</p>
</div>
<div class="col-sm-12">
<h3 id="ussm">USS <em>Massachusetts</em>: History and Archaeology of the Nation’s Oldest Battleship</h3>
<p>Just outside Pensacola Pass lie the remains of our nation’s oldest existing battleship, USS
Massachusetts (BB2). Launched in 1896 as part of the New Steel Navy, the powerful warship
soon was rendered obsolete by naval technological advances. Nevertheless, Massachusetts
had an exciting career of combat, training, and target practice, and now is a massive
artificial reef. This presentation describes the ship and her long life of service to the nation
and to Pensacola.</p>
</div>
<div class="col-sm-12">
<h3 id="hrt">History is the Real Treasure: The 1733 Spanish Galleon Trail</h3>
<p>The Spanish treasure fleet of 1733 wrecked in a violent hurricane along 80 miles of the
Florida Keys. With the discovery of the first shipwreck in the late 1940s and the growth of
scuba diving in the 1950s and 60s enabling treasure hunters to locate most of the rest of
the fleet, these wrecks suffered from haphazard digging and the loss of much information.
Today, these shipwrecks are among the oldest and most vibrant artificial reefs in the Keys.
This lecture describes a State of Florida project to record and interpret the 1733 fleet that
resulted in the production of a booklet and website devoted to telling the story of the fleet
disaster and to promoting the archaeological importance of the sunken ships as tangible
remains of our maritime heritage.</p>
</div>
<div class="col-sm-12">
<h3 id="empt">The Emanuel Point Ships: Florida’s Earliest Shipwrecks Associated with the 1559</h3>
<p>Colonization Attempt by <NAME> at Pensacola
Before the English settled Jamestown and before the Spanish colonized St. Augustine, the
harbor of Pensacola, Florida, was targeted by Spanish authorities as the perfect place to
establish a town on the northern Gulf Coast. Only a few weeks after arrival, however,
<NAME>’s fleet was destroyed by a violent hurricane. Although the land site has
never been identified, two of Luna’s ships have been discovered in Pensacola Bay and have
been archaeologically investigated. This lecture presents this little-known episode of
colonial history as well as the ships and artifacts associated with the Luna expedition.</p>
</div>
<div class="col-sm-12">
<h3 id="mits">Museums in the Sea: Florida’s Underwater Archaeological Preserves</h3>
<p>Clues to Florida’s maritime history are scattered along the state’s coasts, bays, and rivers in
the form of shipwrecks relating to waterborne exploration, commerce, and warfare. This
lecture features Florida’s Museums in the Sea, historic shipwrecks that have been
interpreted for divers and snorkelers as a way to educate citizens and visitors about the
real treasure of Florida’s shipwrecks – their history.</p>
</div>
<div class="col-sm-12">
<h3 id="dhpht">Diving, Historic Preservation, and Heritage Tourism</h3>
<p>Florida’s historic shipwrecks have long been exploited for their perceived tangible value as
mines of (often non-existent) treasure. The real treasure of shipwrecks, however, is their
value as sites of history and heritage, and their potential for heritage tourism. This lecture
describes the issues archaeologists face regarding effective management and protection of
submerged cultural sites, as well as strategies that have been developed for interpretation
and sustainable tourism at underwater archaeological sites.</p>
</div>
<div class="col-sm-12">
<h3 id="opip">Our Past in Peril: Florida’s Trouble with Treasure</h3>
<p>As the scene of several colonial Spanish fleet disasters from the 16th to the 18th centuries,
Florida is at the center of the commercial historic shipwreck salvage industry. Despite
public opinion and laws protecting submerged cultural heritage, treasure hunters still are
engaged in the destruction of underwater historic sites for personal gain. This lecture
describes Florida’s history of treasure hunting, laws regarding commercial salvage of
historic shipwrecks, and the strategies employed by archaeologists and resource managers
to protect historic shipwrecks for the present and future and to promote responsible
visitation.</p>
</div>
<div class="col-sm-12">
<h3 id="ttales">Tombstone Tales: Cemeteries, Symbols, and Stories</h3>
<p>Historic cemeteries are amazing outdoor museums containing vast amounts of information
on markers and tombstones that can be “read’ like historic documents. This presentation
describes the development of the modern cemetery, the kinds of information that can be
learned from inscriptions and symbols on markers, the laws protecting historic cemeteries
in Florida, and ways to protect them for the future.</p>
</div>
<div class="col-sm-12">
<h3 id="intro">Introduction to Archaeology</h3>
<p>What do archaeologists do, exactly? If dinosaurs and rocks come to mind, this is the
presentation for you! Learn about the science of archaeology, its role as part of the field of
anthropology, where archaeologists work, and how they discover and protect our cultural
heritage. Appropriate for all ages, this fun and informative show sets the stage for
understanding how archaeology preserves our past for the present and future.</p>
</div>
<div class="col-sm-12">
<h3 id="remote">Remote Sensing in Archaeology</h3>
<p>Archaeology is a destructive science. Excavation disturbs sites in such a way that they can
never be restored to their original state. To preserve sites as they are found, archaeologists
have various technologies in their archaeological "tool kit" to help study and gather data
from sites without intrusive excavation. This lecture discusses, in basic terms, the kinds of
remote-sensing instruments archaeologists use, both on land and underwater.</p>
</div>
<div class="col-sm-12">
<h3 id="smack">Talking Smack: The Sailing Vessels of Pensacola’s Red Snapper Fishing Industry</h3>
<p>After the end of the American Civil War, industry in Pensacola and Northwest Florida
boomed as money flowed from the North to the South. Among the various industrial
endeavors in the Pensacola area, commercial fishing for red snapper became one of the
most successful. From 1870-1930, the colorful fishermen and beautiful sailing vessels of
the red snapper fishing industry dominated the city’s waterfront. This presentation
discusses the importance of red snapper fishing to the development of Pensacola and
Northwest Florida, in addition to why the industry began and ended so quickly.</p>
</div>
<div class="col-sm-12">
<h3 id="erbd">Exploring Race-Based Differences in the Post-Civil War Red Snapper Fishing Industry</h3>
<p>The booming red snapper fishing industry in Pensacola, Florida, in the years 1870-1930
provided a significant source of employment for racially varied immigrant and local
fishermen. Despite strong similarities in onshore living conditions among racially
categorized “black,” “mulatto,” and “white” fishermen, offshore experiences onboard the
fishing vessels were markedly different. This presentation discusses these differences as
part of the range of individual experience in Post-Civil War Florida.</p>
</div>
<div class="col-sm-12">
<h3 id="mmm">Mosquitos, Muggles, and Museums: Exploring Florida’s Archaeology with Geocaching</h3>
<p>Are you ready to get outside and explore Northwest Florida’s archaeology and history?
Forget your fedoras and bullwhips; pick up a GPS device and go geocaching! Geocaching is
a worldwide scavenger hunt game. Players try to locate hidden containers, called caches,
using GPS devices and share their experiences online. FPAN recently created a series of
geocaches hidden at historic and archaeological sites across northwest Florida to increase
awareness that these places are out there and they are open for you to visit. This
presentation describes how geocaching works, what you need to play, and a unique
geocaching adventure created by FPAN that will take you back in time through northwest
Florida’s history and archaeology.</p>
</div>
<div class="col-sm-12">
<h3 id="pirates">Pirates! The Last Scourge of the Gulf: An Exhibit</h3>
<p>Two centuries ago a massive wave of piracy struck the Gulf of Mexico and terrorized
shipping along the Gulf Coast. Florida was especially dangerous for travelers. <NAME>
and <NAME>, two of the most notorious pirates from this period, had close ties to the
Florida panhandle. One case of piracy even wound up in the court of West Florida in
Pensacola and made newspaper headlines across the nation. This talk examines some of
the broader aspects of piracy during the early 1800s in the Gulf and Caribbean by analyzing
this federal court case held in Pensacola in 1823. </p>
</div>
<div class="col-sm-12">
<h3 id="uf">Unearthing Florida </h3>
<p>With close to 500 years of European history and more than 10,000 years of Native
American history, Florida is host to an array of archaeological sites on land and
underwater. In this presentation the author of the Unearthing Florida radio program will
highlight eight different archaeological sites across the state from prehistoric times to the
Civil War. We will learn about the history and archaeological investigations of these sites,
some of the high-tech tools archaeologists used there, the artifacts they uncovered, and
why the sites are important cultural resources on this statewide journey! </p>
</div>
<div class="col-sm-12">
<h3 id="dfah">Dear Friends at Home: Accounts of a Union Soldier in Pensacola</h3>
<p>During the Union occupation of Pensacola in the Civil War, a Union soldier by the name of
<NAME> wrote 20 letters home to his family in Maine. These letters provide a
wealth of information about West Florida during the Civil War, however, the reader also
gains a strong sense of familiarity with the author. This presentation shows how using primary
documents to learn about history can bring about an intimate knowledge of
people in the past that is rarely found in history books.</p>
</div>
<div class="col-sm-12">
<h3 id="caves">Archaeology and the Use of Caves in Florida</h3>
<p>For thousands of years people have been utilizing caves in the southeastern United States.
These caves have been used for shelter, burials, religious ceremonies, and have been
mined for natural resources by both prehistoric and historic people. In Florida, caves have
produced human remains, cultural materials, and petroglyphs. Many of these caves still
affect our lives through tourism, recreation, and scientific research. This presentation
introduces an archaeological look at the past and present use of caves in Florida.</p>
</div>
<div class="col-sm-12">
<h3 id="pssbr">Pirates, Slave Smugglers, and Blockade Runners of the Gulf Coast</h3>
<p> From the Age of Discovery until the end of the Civil War, the Gulf Coast was known as a region dotted with
numerous bays and inlets, isolated stretches of beach, and sparsely populated islands.
Lack of development and infrastructure, along with inadequate law enforcement and little
cohesive political structure, enabled maritime criminals such as pirates and smugglers to
engage in nefarious activities. This lecture describes the role of Pensacola residents and the
Gulf Coast region in this colorful period of New World history.</p>
</div>
<div class="col-sm-12">
<h3 id="archnwf">Archaeology of Northwest Florida: A Tour Through our Heritage</h3>
<p>This presentation features a virtual tour of the major archaeological discoveries in FPAN's
Northwest Region, the Panhandle of Florida. You'll learn about 16th-century shipwrecks, Native
American encampments and ceremonial centers, a Civil War gun battery, a Spanish fort and mission,
historic cemeteries, and the nation's oldest battleship!</p>
</div>
<div class="col-sm-12">
<h3 id="deadmans">Deadman's Island: Pensacola Bay's Unique Landform</h3>
<p>The area known as Deadman's Island in Pensacola Bay has served as a careening ground,
shipbuilding center, quarantine station, and cemetery. Archaeologists have found remains of
extensive activities, both prehistoric and historic, ranging from shipwrecks to barrel wells
to coffins. Learn about the unique geography of this interesting landform, and why people
have used it for thousands of years.</p>
</div>
<!-- <h3>Maritime Archaeology of the Gulf Islands National Seashore, Fort Pickens Area</h3>
<p>The Fort Pickens Area of Gulf Islands National Seashore includes many archaeological and
historic sites. In addition to military installations built to protect the entrance to Pensacola
Bay, a number of archaeological sites are found in the park such as the second location of
the permanent Spanish settlement of Pensacola, Presidio Isla de Santa Rosa. Several
historic shipwrecks also are within the park boundaries, including the Spanish warship
Rosario, sunk in a storm in 1705, and Catharine, a Norwegian cargo vessel that ran aground
in 1894. This presentation describes the archaeological investigations of these sites as well
as a general history of the Fort Pickens Area.</p>
<h3>Nuestra Señora del Rosario y Santi<NAME>: A Spanish New World Frigate</h3>
<p>Rosario was built in 1696 as a powerful warship for the Spanish navy. As part of the
Windward Fleet, she protected convoys of ships loaded with valuable goods traveling
between Spain and its New World colonies. Throughout her career the ship performed
many duties including hunting pirates and supplying far-flung settlements. The ship was
lost in 1705 while resupplying the colony at Pensacola, then known as Presidio Santa María
de Galve. This presentation describes the ship’s unique history and the archaeological
investigation of the shipwreck.</p> -->
</div>
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Newsletter";
$email = isset($_GET['email']) ? $_GET['email'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle;?></h1>
</div>
<!-- Begin MailChimp Signup Form -->
<div class="col-sm-10 col-sm-push-1">
<form action="//flpublicarchaeology.us3.list-manage.com/subscribe/post?u=7d87dae6d7a4dca514b6c3ddc&id=8c7c7ccdd6" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<h2>Join our mailing list</h2>
<div class="form-group">
<label class="control-label " for="mce-EMAIL">Email Address</label>
<div class="row">
<div class="col-xs-10">
<input type="email" value="<?=$email?>" name="EMAIL" class="form-control" id="mce-EMAIL">
</div>
<div class="col-xs-2">
<span class="required">*</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label" for="mce-FNAME">First Name </label>
<input type="text" value="" name="FNAME" class="form-control" id="mce-FNAME">
</div>
<div class="form-group">
<label class="control-label" for="mce-LNAME">Last Name </label>
<input type="text" value="" name="LNAME" class="form-control" id="mce-LNAME">
</div>
<div class="form-group">
<label class="control-label">County </label>
<ul>
<li><input type="checkbox" value="1" name="group[7593][1]" id="mce-group[7593]-7593-0"><label for="mce-group[7593]-7593-0"> Nassau</label></li>
<li><input type="checkbox" value="2" name="group[7593][2]" id="mce-group[7593]-7593-1"><label for="mce-group[7593]-7593-1"> Clay</label></li>
<li><input type="checkbox" value="4" name="group[7593][4]" id="mce-group[7593]-7593-2"><label for="mce-group[7593]-7593-2"> St. Johns</label></li>
<li><input type="checkbox" value="8" name="group[7593][8]" id="mce-group[7593]-7593-3"><label for="mce-group[7593]-7593-3"> Putnam</label></li>
<li><input type="checkbox" value="16" name="group[7593][16]" id="mce-group[7593]-7593-4"><label for="mce-group[7593]-7593-4"> Duval</label></li>
<li><input type="checkbox" value="32" name="group[7593][32]" id="mce-group[7593]-7593-5"><label for="mce-group[7593]-7593-5"> Flagler</label></li>
<li><input type="checkbox" value="64" name="group[7593][64]" id="mce-group[7593]-7593-6"><label for="mce-group[7593]-7593-6"> Volusia</label></li>
</ul>
</div>
<div class="form-group">
<label class="control-label" >Category </label>
<ul>
<li><input type="checkbox" value="128" name="group[7597][128]" id="mce-group[7597]-7597-0"><label for="mce-group[7597]-7597-0"> Volunteer/Avocational</label></li>
<li><input type="checkbox" value="256" name="group[7597][256]" id="mce-group[7597]-7597-1"><label for="mce-group[7597]-7597-1"> Heritage Professional</label></li>
<li><input type="checkbox" value="512" name="group[7597][512]" id="mce-group[7597]-7597-2"><label for="mce-group[7597]-7597-2"> Land Manager/Planner</label></li>
<li><input type="checkbox" value="1024" name="group[7597][1024]" id="mce-group[7597]-7597-3"><label for="mce-group[7597]-7597-3"> Teacher/Educator</label></li>
<li><input type="checkbox" value="2048" name="group[7597][2048]" id="mce-group[7597]-7597-4"><label for="mce-group[7597]-7597-4"> Other Interested Person</label></li>
</ul>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;">
<input type="text" name="b_7d87dae6d7a4dca514b6c3ddc_8c7c7ccdd6" tabindex="-1" value="">
</div>
<div class="text-center">
<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn btn-primary">
</div>
</form>
</div><!-- /.col -->
<!--End mc_embed_signup-->
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!-- <div class="box-tab col-sm-12">
<h2>Newsletter Archives</h2>
</div>/.col -->
</div><!-- /.col /.row -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Links";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Get Involved</h1></th>
</tr>
<tr>
<td class="table_mid"><div align="center">There are many Organizations you can join to pursue an interest in archaeology. Here are some of our favorites:
</p>
<br/>
<h2 align="center"><strong>Local Organizations:</strong></h2>
<br/>
<p align="center"><a href="http://saaa.shutterfly.com/"><img src="images/logos/saaa.jpg" width="200" height="38" alt="SAAA" /></a><br />
<strong><a href="http://saaa.shutterfly.com/">St. Augustine Archaeological Association</a></strong><br>
<br />
</p>
<p align="center"><a href="http://www.tolomatocemetery.com/"><img src="images/logos/TCPA.png" width="120" height="115" alt="TCPA" /></a><br />
<strong><a href="http://www.tolomatocemetery.com/">Tolomato Cemetery Preservation Association</a></strong><br>
<br />
</p>
<p align="center"><a href="http://www.nsbhistory.org/"><img src="images/logos/NSBmuseum.jpg" width="150" height="41" /></a><br />
<strong><a href="http://www.nsbhistory.org/">Southeast Volusia Historical Society / New Smyrna Museum of History</a></strong></p>
</div>
<br/>
<hr align="center" />
<br/>
<h2 align="center"><strong>State Organizations:</strong></h2>
<br/>
<div align="center">
<p><a href="http://www.fasweb.org/"><img src="images/logos/FAS.png" width="76" height="75" alt="FAS" /></a><br>
<strong><a href="http://www.fasweb.org/">Florida Anthropological Society</a></strong></p>
<br />
<p><a href="http://www.flamuseums.org/"><img src="images/logos/FL Museums.jpg" alt="Florida Association of Museums" width="199" height="62" /></a> <br>
<strong><a href="http://www.flamuseums.org/">Florida Association of Museums</strong></a> </p>
<br />
<p><a href="http://www.floridatrust.org/"><img src="images/logos/FLtrust.jpg" width="84" height="121" alt="FL Trust" /></a> </p>
<p><strong><a href="http://www.floridatrust.org/">Florida Trust</a></strong></p>
</div>
<br/>
<hr align="center" />
<br/>
<h2 align="center"><strong>National & International Organizations:</strong></h2>
<br/>
<div align="center">
<p><a href="http://www.saa.org/"><img src="images/logos/SAA.jpg" width="120" height="91" alt="SAA" /></a><br>
<strong><a href="http://www.saa.org/">Society for American Anthropology</a></strong></p>
<p><a href="http://www.sha.org"><img src="images/logos/SHA.jpg" width="119" height="129" alt="SHA" /></a> <br>
<strong><a href="http://www.sha.org">Society for Historical Archaeology</a></strong></p>
<p><a href="http://www.southeasternarchaeology.org/"><img src="images/logos/SEAC.png" width="120" height="120" alt="SEAC"/></a> <br>
<strong><a href="http://www.southeasternarchaeology.org/">Southeastern Archaeological Conference</a></strong> </p>
<p><a href="http://www.interpnet.com/"><img src="images/logos/NAI.jpg" width="148" height="74" alt="NAI" /></a><br>
<strong><a href="http://www.interpnet.com/">National Association for Interpretation</a></strong></p>
</div>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
include '../admin/dbConnect.php';
include '../_publicFunctions.php';
$table='serc';
?>
<!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>FPAN SE<?php if($pageTitle){echo " - ".$pageTitle;} ?></title>
<meta name="DESCRIPTION" content="FPAN is dedicated to the protection of cultural resources, both on land and underwater, and to involving the public in the study of their past."/>
<meta name="KEYWORDS" content="fpan, florida public archaeology, public archaeology, florida, archaeology, florida archaeology, florida archaeology network"/>
<!-- Favicon -->
<link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
<!-- All Inclusive Stylsheet (Bootstrap, FontAwesome, FPAN Styles, Northeast Region Styles) -->
<link href="../_css/se_style.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Google Analytics Tracking Code -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-7301672-11', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<!-- Nav goes here! -->
<?php include('../_mainNav.php'); ?>
<div class=" center-block visible-xs">
<a href="#menu">
<button type="button" class="btn btn-default btn-menu center-block ">
Southeast Region Menu <span class="glyphicon glyphicon-collapse-down"></span>
</button>
</a>
</div><file_sep><?php
require_once('recaptchalib.php');
$publickey = "<KEY>";
include('_header.php');
?>
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'white'
};
</script>
<div class="container">
<div class="row">
<div class="col-sm-10 col-sm-push-1">
<div class="page-header">Contact me.</div>
</div>
<div class="col-sm-8 col-sm-push-2">
<p class="text-center text-warning"><small>All fields required.</small></p>
<form action="verify.php" method="post" class="row">
<div class="form-group col-sm-7 col-sm-push-1">
<label for="email" class="control-label">Email:</label>
<input name="email" type="email" class="form-control" maxlength="30" placeholder="<EMAIL>" required="required">
</div>
<div class="form-group col-sm-7 col-sm-push-1">
<label for="name" class="control-label">Name:</label>
<input name="name" type="text" class="form-control" maxlength="30" required="required">
</div>
<div class="form-group col-sm-7 col-sm-push-1">
<label for="number" class="control-label">Phone Number:</label>
<input name="number" type="tel" class="form-control" maxlength="12" required="required">
</div>
<div class="form-group col-sm-9 col-sm-push-1">
<label for="desc" class="control-label">Reason for inquiry:</label>
<textarea name="desc" class="form-control" rows="8" maxlength="1000" required="required"></textarea>
</div>
<div class="form-group col-sm-10 col-sm-push-1">
<?php echo recaptcha_get_html($publickey); ?>
</div>
<div class="form-group col-sm-10 col-sm-push-1">
<button type="submit" class="btn btn-lg btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div><!--/.row-->
</div> <!-- /container -->
<?php include('_footer.php'); ?>
<file_sep><?php
$pageTitle = "Documents";
include('../_header.php');
?>
<!-- page-content begins -->
<div class="container">
<div class="page-header">
<h1>Documents</h1>
</div>
<div class="row">
<div class="col-sm-6 col-md-5 col-md-offset-1">
<h3>Brochures</h3>
<div class="box box-tab">
<ul>
<li><a href="FPAN_brochure.pdf" target="_blank">English Brochure</a></li>
<li><a href="FPANspanish.pdf" target="_blank">Spanish Brochure </a></li>
<li><a href="SCUBA_rack_card.pdf" target="_blank">SCUBA Training Programs Insert</a></li>
</ul>
</div>
<h3>Strategic Planning</h3>
<div class="box box-tab">
<ul>
<li><a href="FPANStrategicPlan.pdf" target="_blank">Florida Public Archaeology Network Strategic Plan - June 2010</a></li>
<li>Goals and Objectives <a href="GoalsObjectives.pdf" target="_blank">.pdf </a> | <a href="GoalsObjectives.docx" target="_blank">.docx </a></li>
</ul>
</div>
<h3>Annual Reports</h3>
<div class="box box-tab">
<ul>
<li><a href="annualreports/AnnualReport_1314.pdf" target="_blank">FPAN FY 2013-2014 Stats</a></li>
<li><a href="annualreports/FPANAnnualReportFY20122013.pdf" target="_blank">FPAN FY 2012-2013 Report</a></li>
<li><a href="annualreports/AnnualReport_1213.pdf" target="_blank">FPAN FY 2012-2013 Stats</a></li>
<li><a href="annualreports/FPANAnnualReportFY20112012.pdf" target="_blank">FPAN FY 2011-2012</a></li>
<li><a href="annualreports/FPANAnnualReportFY20102011.pdf" target="_blank">FPAN FY 2010-2011</a></li>
<li><a href="annualreports/FPANAnnualReportFY20092010.pdf" target="_blank">FPAN FY 2009-2010</a></li>
<li><a href="annualreports/FPANFY2006-2007AnnualReport_000.pdf" target="_blank">FPAN FY 2006-2007</a></li>
<li><a href="annualreports/FPANAnnualReportFY20052006.pdf" target="_blank">FPAN FY 2005-2006</a></li>
</ul>
</div>
<h3>Local Government Preservation Program</h3>
<div class="box-tab">
<ul>
<li><a href="LGPPD%20FINAL%20REPORT%20revision%201.pdf" target="_blank">Report </a></li>
<li><a href="Florida_Trust_Database_NF_final_03_07.xls" target="_blank">Excel Spreadsheet </a></li>
<li><a href="Florida%20Trust%20DB%20Final.mdb" target="_blank">Access Database </a></li>
</ul>
</div>
<h3>Connection to Collections</h3>
<div class="box-tab">
<ul>
<li><a href="http://www.flpublicarchaeology.org/documents/FLConntoCollections2011Program.pdf" target="_blank">Statewide Training Program</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-5">
<h3>Administrative</h3>
<div class="box box-tab">
<ul>
<li><a href="FPAN_MOA.pdf" target="_blank">Memorandum of Agreement</a></li>
<li><a href="OrgChart.png" target="_blank">FPAN Organizational Chart</a></li>
<li><a href="LiabilityReleasePrograms.pdf" target="_blank">Liability Release Form - Programs</a></li>
<li><a href="LiabilityReleaseDivingOps.pdf" target="_blank">Liability Release Form - Diving Ops</a></li>
<li><a href="IdentityStandards.pdf" target="_blank">Identity Standards Manual</a></li>
</ul>
</div>
<h3>Board Minutes</h3>
<div class="box box-tab">
<ul>
<li><a href="minutes/BODOct2013.pdf">Oct 31, 2013</a></li>
<li><a href="minutes/BODMay2013StAug.pdf">May 9-10, 2013</a></li>
<li><a href="minutes/BODDec192012.pdf">Dec 19, 2012</a></li>
<li><a href="minutes/BODMay2012Tallahassee.pdf">May 20, 2012</a></li>
<li><a href="minutes/BODDec2011FtLauderdale.pdf">December 11, 2011</a></li>
<li><a href="minutes/BODMay2011Orlando.pdf">May 5-6, 2011</a></li>
<li><a href="minutes/BOD_Feb2011_minutes.pdf">February 3, 2011</a></li>
<li><a href="minutes/BODConfOct112010.pdf" target="_blank">October 11, 2010 - Conf. Call </a></li>
<li><a href="minutes/BODConfCallAug252010.pdf" target="_blank">August 25, 2010</a></li>
<li><a href="minutes/BODMay2010FtMyers.pdf" target="_blank">May 7, 2010</a></li>
<li><a href="minutes/BODDec5StAugustine.pdf" target="_blank">December 5, 2009 </a></li>
<li><a href="minutes/BOD%20Conf%20Call%20Sept%2030%202009.pdf" target="_blank">September 30, 2009 </a></li>
<li><a href="minutes/BOD%20Conf%20Call%20July%2028%202009.pdf" target="_blank">July 28, 2009 </a></li>
<li><a href="minutes/BOD May 8 2009 PNS-LG.pdf" target="_blank">May 8, 2009 </a></li>
<li><a href="minutes/BODMay22008Ybor.pdf" target="_blank">May 2, 2008 </a></li>
<li><a href="minutes/ConfCallFeb52008.pdf" target="_blank">February 5, 2008</a></li>
<li><a href="minutes/ConfCallJune142007CentralReg.pdf" target="_blank">June 14, 2007</a></li>
<li><a href="minutes/BODSebringMay112007.pdf" target="_blank">May 11, 2007 </a></li>
<li><a href="minutes/BODOct272006Shortened.pdf" target="_blank">October 27, 2006</a></li>
<li><a href="minutes/20060410.pdf" target="_blank">April 10, 2006</a></li>
<li><a href="minutes/20060512.pdf" target="_blank">May 12, 2006</a></li>
</ul>
</div>
</div><!-- /.col -->
</div>
<div class="row"
<div class="col-md-10 col-md-offset-1">
<h3>Quarterly Reports</h3>
<div class="box box-tab">
<div class="row">
<div class="col-sm-6">
<div class="expandable-panel" id="cp-1">
<div class="expandable-panel-heading">
<h3>Northwest<span class="icon-close-open"></span></h3>
</div>
<div class="expandable-panel-content">
<strong>FY 2009-2010</strong>
<ul>
<li><a href="quarterlyreports/NW_3Q_0910.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NW_4Q_0910.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2010-2011</strong>
<ul>
<li><a href="quarterlyreports/NW_1Q_1011.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/NW_2Q_1011.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NW_3Q_1011.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NW_4Q_1011.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2011-2012</strong>
<ul>
<li><a href="quarterlyreports/NW_1Q_1112.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/NW_2Q_1112.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NW_3Q_1112.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NW_4Q_1112.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2012-2013</strong>
<ul>
<li><a href="quarterlyreports/NW_2Q_1213.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NW_3Q_1213.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NW_4Q_1213.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2013-2014</strong>
<ul>
<li><a href="quarterlyreports/NW_1Q_1314.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/NW_2Q_1314.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NW_3Q_1314.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NW_4Q_1314.pdf" target="_blank">4th Quarter</a></li>
</ul>
</div><!-- /.expandable-panel-content -->
</div><!-- /.expandable-panel cp-1 -->
<div class="expandable-panel" id="cp-2">
<div class="expandable-panel-heading">
<h3>North Central<span class="icon-close-open"></span></h3>
</div>
<div class="expandable-panel-content">
<strong>FY 2010-2011</strong>
<ul>
<li><a href="quarterlyreports/NC_1Q_1011.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/NC_2Q_1011.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NC_3Q_1011.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NC_4Q_1011.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2011-2012</strong>
<ul>
<li><a href="quarterlyreports/NC_1Q_1112.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/NC_2Q_1112.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NC_3Q_1112.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NC_4Q_1112.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2012-2013</strong>
<ul>
<li><a href="quarterlyreports/NC_2Q_1213.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NC_3Q_1213.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NC_4Q_1213.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2013-2014</strong>
<ul>
<li><a href="quarterlyreports/NC_1Q_1314.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/NC_2Q_1314.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NC_3Q_1314.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NC_4Q_1314.pdf" target="_blank">4th Quarter</a></li>
</ul>
</div><!-- /.expandable-panel-content -->
</div><!-- /.expandable-panel cp-2 -->
<div class="expandable-panel" id="cp-3">
<div class="expandable-panel-heading">
<h3>Northeast<span class="icon-close-open"></span></h3>
</div>
<div class="expandable-panel-content">
<strong>FY 2009-2010</strong>
<ul>
<li><a href="quarterlyreports/NE_3Q_0910.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NE_4Q_0910.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2010-2011</strong>
<ul>
<li><a href="quarterlyreports/NE_1Q_1011.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/NE_2Q_1011.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NE_3Q_1011.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NE_4Q_1011.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2011-2012</strong>
<ul>
<li><a href="quarterlyreports/NE_1Q_1112.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/NE_2Q_1112.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NE_3Q_1112.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NE_4Q_1112.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2012-2013</strong>
<ul>
<li><a href="quarterlyreports/NE_2Q_1213.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NE_3Q_1213.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NE_4Q_1213.pdf" target="_blank">4th Quarter</a></li>
</ul>
<ul>
<li><a href="quarterlyreports/NE_1Q_1314.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/NE_2Q_1314.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/NE_3Q_1314.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/NE_4Q_1314.pdf" target="_blank">4th Quarter</a></li>
</ul>
</div><!-- /.expandable-panel-content -->
</div><!-- /.expandable-panel cp-3 -->
<div class="expandable-panel" id="cp-4">
<div class="expandable-panel-heading">
<h3>Central<span class="icon-close-open"></span></h3>
</div>
<div class="expandable-panel-content">
<strong>FY 2009-2010</strong>
<ul>
<li><a href="quarterlyreports/C_3Q_0910.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/C_4Q_0910.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2010-2011</strong>
<ul>
<li><a href="quarterlyreports/C_1Q_1011.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/C_2Q_1011.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/C_3Q_1011.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/C_4Q_1011.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2011-2012</strong>
<ul>
<li><a href="quarterlyreports/C_1Q_1112.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/C_2Q_1112.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/C_3Q_1112.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/C_4Q_1112.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2012-2013</strong>
<ul>
<li><a href="quarterlyreports/C_2Q_1213.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/C_3Q_1213.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/C_4Q_1213.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2013-2014</strong>
<ul>
<li><a href="quarterlyreports/C_1Q_1314.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/C_WC_2Q_1314.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/C_WC_3Q_1314.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/C_WC_4Q_1314.pdf" target="_blank">4th Quarter</a></li>
</ul>
</div><!-- /.expandable-panel-content -->
</div><!-- /.expandable-panel cp-4 -->
</div><!-- /.col -->
<div class="col-sm-6">
<div class="expandable-panel" id="cp-5">
<div class="expandable-panel-heading">
<h3>West Central<span class="icon-close-open"></span></h3>
</div>
<div class="expandable-panel-content">
<strong>FY 2009-2010</strong>
<ul>
<li><a href="quarterlyreports/WC_3Q_0910.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/WC_4Q_0910.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2010-2011</strong>
<ul>
<li><a href="quarterlyreports/WC_1Q_1011.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/WC_2Q_1011.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/WC_3Q_1011.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/WC_4Q_1011.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2011-2012</strong>
<ul>
<li><a href="quarterlyreports/WC_1Q_1112.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/WC_2Q_1112.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/WC_3Q_1112.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/WC_4Q_1112.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2012-2013</strong>
<ul>
<li><a href="quarterlyreports/WC_2Q_1213.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/WC_3Q_1213.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/WC_4Q_1213.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2013-2014</strong>
<ul>
<li><a href="quarterlyreports/WC_1Q_1314.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/C_WC_2Q_1314.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/C_WC_3Q_1314.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/C_WC_4Q_1314.pdf" target="_blank">4th Quarter</a></li>
</ul>
</div><!-- /.expandable-panel-content -->
</div><!-- /.expandable-panel cp-5 -->
<div class="expandable-panel" id="cp-6">
<div class="expandable-panel-heading">
<h3>East Central<span class="icon-close-open"></span></h3>
</div>
<div class="expandable-panel-content">
<strong>FY 2009-2010</strong>
<ul>
<li><a href="quarterlyreports/EC_3Q_0910.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/EC_4Q_0910.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2010-2011</strong>
<ul>
<li><a href="quarterlyreports/EC_1Q_1011.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/EC_2Q_1011.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/EC_3Q_1011.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/EC_4Q_1011.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2011-2012</strong>
<ul>
<li><a href="quarterlyreports/EC_1Q_1112.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/EC_2Q_1112.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/EC_3Q_1112.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/EC_4Q_1112.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2012-2012</strong>
<ul>
<li><a href="quarterlyreports/EC_2Q_1213.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/EC_3Q_1213.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/EC_4Q_1213.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2013-2014</strong>
<ul>
<li><a href="quarterlyreports/EC_1Q_1314.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/EC_2Q_1314.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/EC_3Q_1314.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/EC_4Q_1314.pdf" target="_blank">4th Quarter</a></li>
</ul>
</div><!-- /.expandable-panel-content -->
</div><!-- /.expandable-panel cp-6 -->
<div class="expandable-panel" id="cp-7">
<div class="expandable-panel-heading">
<h3>Southeast<span class="icon-close-open"></span></h3>
</div>
<div class="expandable-panel-content">
<strong>FY 2009-2010</strong>
<ul>
<li><a href="quarterlyreports/SE_3Q_0910.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/SE_4Q_0910.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2010-2011</strong>
<ul>
<li><a href="quarterlyreports/SE_1Q_1011.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/SE_2Q_1011.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/SE_3Q_1011.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/SE_4Q_1011.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2011-2012</strong>
<ul>
<li><a href="quarterlyreports/SE_1Q_1112.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/SE_2Q_1112.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/SE_3Q_1112.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/SE_4Q_1112.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2012-2013</strong>
<ul>
<li><a href="quarterlyreports/SE_2Q_1213.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/SE_3Q_1213.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/SE_4Q_1213.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2013-2014</strong>
<ul>
<li><a href="quarterlyreports/SE_1Q_1314.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/SE_2Q_1314.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/SE_3Q_1314.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/SE_4Q_1314.pdf" target="_blank">4th Quarter</a></li>
</ul>
</div><!-- /.expandable-panel-content -->
</div><!-- /.expandable-panel cp-7 -->
<div class="expandable-panel" id="cp-8">
<div class="expandable-panel-heading">
<h3>Southwest<span class="icon-close-open"></span></h3>
</div>
<div class="expandable-panel-content">
<strong>FY 2009-2010</strong>
<ul>
<li><a href="quarterlyreports/SW_3Q_0910.pdf" target="_blank">3rd Quarter</a></li>
</ul>
<strong>FY 2010-2011</strong>
<ul>
<li><a href="quarterlyreports/SW_1Q_1011.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/SW_3Q_1011.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/SW_4Q_1011.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2011-2012</strong>
<ul>
<li><a href="quarterlyreports/SW_1Q_1112.pdf" target="_blank">1st Quarter</a></li>
<li><a href="quarterlyreports/SW_2Q_1112.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/SW_3Q_1112.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/SW_4Q_1112.pdf" target="_blank">4th Quarter</a></li>
</ul>
<strong>FY 2012-2013</strong>
<ul>
<li><a href="quarterlyreports/SW_2Q_1213.pdf" target="_blank">2nd Quarter</a></li>
</ul>
<strong>FY 2013-2014</strong>
<ul>
<li><a href="quarterlyreports/SW_2Q_1314.pdf" target="_blank">2nd Quarter</a></li>
<li><a href="quarterlyreports/SW_3Q_1314.pdf" target="_blank">3rd Quarter</a></li>
<li><a href="quarterlyreports/SW_4Q_1314.pdf" target="_blank">4th Quarter</a></li>
</ul>
</div><!-- /.expandable-panel-content -->
</div><!-- /.expandable-panel cp-8 -->
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
$pageTitle = "Volunteer";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-tab">
<img class="img-responsive center-block" src="images/volunteers.jpg" alt="Volunteers help out in the FPAN Archaeology lab">
<p class="text-center"><strong>FPAN Archaeology Lab Volunteer Program</strong></p>
<p class="text-center">
207 East Main Street<br>
Pensacola, FL 32502<br>
(850) 595-0050
</p>
<p class="text-center"><strong>Fall 2014 Lab Volunteer Hours</strong></p>
<p class="text-center"> <em>Most Mondays & Wednesdays from 10am-4pm</em></p>
<p class="text-center"> Check <a href="http://flpublicarchaeology.org/nwrc/eventList.php">Event Calendar</a> for specific days</p>
<p>FPAN is seeking enthusiastic volunteers of all ages to help rough sort artifacts recovered from local archaeological sites. Volunteers work inside our air-conditioned lab to rough sort artifacts recovered from local archaeological sites. Volunteers work with small screens, trays, brushes, magnets and other lab tools to clean and sort artifacts. Once artifacts have been cleaned, they are sorted into groups of like materials (i.e. brick, glass, shell, ceramics, stone, etc.) No experience is needed, but all volunteers are given a brief orientation by a professional archaeologist their first day.</p>
<p>The volunteer program is perfect for students who need volunteer hours for scholarships, individuals and groups interested in a unique way to experience local history and archaeology, as well as all of those who have dreamed of getting their hands dirty participating in real archaeological work. All ages are encouraged to participate; however, anyone under 17 years of age must be accompanied by an adult. Individuals, families and groups as large as 12 can be accommodated.</p>
<p> The lab is located inside the FPAN Coordinating Center at 207 E. Main St. in downtown Pensacola, next to The Fish House restaurant.</p>
<p>Contact us at <a href="mailto:<EMAIL>"><EMAIL></a> or <a href="tel:850-595-0050" value="+18505950050" target="_blank">850-595-0050</a>, Ext. 103 to sign up to volunteer on a specific day. Volunteers are not required to commit to more than one day at a time. </p>
</div><!-- /.box-tab -->
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><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, user-scalable=no">
<title>Florida Public Archaeology Network<?php if($pageTitle){echo " - ".$pageTitle;} ?></title>
<!-- Bootstrap -->
<link href="/_css/bootstrap.min.css" rel="stylesheet">
<!-- FontAwesome -->
<link href="/_css/font-awesome.min.css" rel="stylesheet">
<!-- FPAN Styles -->
<link href="/_css/style.css" rel="stylesheet">
<!-- FPAN Admin Section Styles -->
<link href="style.css" rel="stylesheet">
<!-- Favicon -->
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
<!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<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="index.php"> FPAN Admin</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav">
<!-- Main Nav items -->
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Events<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="eventEdit.php">Add Event</a></li>
<li><a href="eventList.php">View/Edit Events</a></li>
<li><a href="eventList.php?archive=true">Archive</a></li>
</ul>
</li><!-- /region menu for xs screens -->
<li><a href="upload.php">Uploads</a></li>
<li><a target="_blank" href="/mollify">File Sharing</a>
<li><a target="_blank" href="https://login.mailchimp.com/">Newsletter</a></li>
<li><a href="index.php?logout=1">Logout</a></li>
<!-- /main nav items -->
</ul>
</div><!-- /.navbar-collapse -->
</nav>
<file_sep><?php
$pageTitle = "Then and Now: Life Along the New River";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Then and Now: Life Along the New River</h1></th>
</tr>
<tr>
<td class="table_mid">
<div id="exhibit">
<?php include 'nav.php'?>
<h2 align="center">Real Estate</h2>
<p>
<img src="images/exhibit12.jpg" style="float:right; margin-left:10px" alt="Late 1890's photograph of the New River showing a family home and loading dock.<br/>
Image courtesy of Fort Lauderdale Historical Society" />
<strong>For thousands of years, people have called the banks of the New River home.</strong> Archaeology sites demonstrate that the Tequesta lived along these waterways prehistorically. Historic accounts start with a 1790s Spanish record of Surles and Frankee Lewis, a Bahamian family living on the south shore of the river. By 1824, Marylander <NAME> had established a plantation just east of the forks of the New River, named “Coonti-hatchee” by the local Seminoles. His property included a cypress log house and a twenty-nine acre farm where he raised corn, sugarcane, citrus, coconuts and livestock. <br />
</p>
<p><br />
</p>
<p> </p>
<p>
<img src="images/exhibit13.jpg" style="float:left; margin-right:10px" alt="A 1911 advertisement for real estate along the New River<br/>
Image courtesy of Broward County Historical Commission." /></p>
<p><strong>The “modern” city of Fort Lauderdale began in the 1890s.</strong> Intrepid pioneers began to filter in from northern climates and populate the area along New River. Instead of garages and barns, these residents had a dock. Fort Lauderdale became known as a “riverport,” where vegetables and fruits were barged down the North New River Canal and New River to be crated and shipped north via rail. By the 1920s, agriculture gave way to real estate and tourism as the new economic mainstays. The Las Olas Causeway, linking the mainland to the beach, was completed in 1917 and opened the beach for development. <br />
<br />
</p>
<p>
<img src="images/exhibit14.jpg" style="float:left; margin-right:10px" alt="In the early 1950s, Gill Construction made the dream of “ocean access” more affordable
with the construction of the Lauderdale Isles subdivision.
Imange courtesy of the Fort Lauderdale Historical Society, Gene Hyde Collection." /></p>
<p> </p>
<p>
By the mid-1920s, the mangrove swamps that lined eastern Las Olas Boulevard were being considered for development. <NAME>, Sr. developed a method of dredging the mangrove swamps and using the muck to make linear islands such as the Venice Subdivision. These “finger isles” had a central road flanked by empty lots and, eventually, waterfront houses. In this way, the extent of waterfront property along the New River was greatly multiplied. Canal construction for real estate purposes continued until the 1950s, even as far inland as State Road 7.</p>
<p> </p>
<p><strong>One hundred years after its incorporation, Fort Lauderdale’s riverfront property remains the most desirable real estate in the city.</strong> </p>
<p style="font-size:10px;">Contributions to the text by <NAME>, Fort Lauderdale Centennial Historian.</p>
</div></td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?>
<file_sep><?php
$pageTitle = "People - Staff";
include('_header.php');
?>
<!-- page-content begins -->
<div class="container">
<div class="page-header">
<h1> People, <small>Staff</small> </h1>
</div>
<!-- Row One -->
<div class="row">
<h2> Coordinating Center Staff</h2>
<div class="col-sm-6">
<div class="staff-box row">
<div class="col-sm-6 ">
<img src="images/people/bill_lees.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-sm-6">
<p>
<strong>Dr. <NAME>, RPA</strong>
<em>Executive Director</em><br/>
(850) 595-0051<br/>
<a href="mailto:<EMAIL>"><EMAIL></a><br/>
<strong onclick="javascript:showElement('bill_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="bill_bio" class="hidden">
Dr. Lees has been Executive Director of FPAN since 2005. He is a Registered Professional Archaeologist
and a member of the Florida Archaeological Council. He has a Bachelor of Science in Anthropology from
the University of Tulsa and a Master’s and Doctorate in Anthropology with a specialization in Historical
Archaeology from Michigan State University. Dr. Lees is the current president of the Society of Historical
Archaeology, is a member of the Florida Historical Commission, and sits on the Florida National Register
Review Board. He has previously served as president of the Plains Anthropological Society, the Society of
Professional Archaeologists, and the Register of Professional Archaeologists. Throughout his career he has
focused on public archaeology and historical archaeology in the Great Plains and Southeastern US, with
specialization in the Antebellum Period and the Civil War.
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/people/della.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong>Dr. <NAME>, RPA</strong>
<em>Associate Director</em><br/>
(850) 595-0050 Ext: 102<br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('della_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="della_bio" class="hidden bio">
Dr <NAME> graduated from the University of West Florida with a Bachelor's degree in Anthropology
and a Master's degree in Historical Archaeology. She also has a Master's in International Relations from Troy
University, and a Ph.D. in Anthropology from Florida State University. Della is certified as a Scuba Instructor
with the National Association of Underwater Instructors (NAUI). She worked with the Pensacola Shipwreck Survey,
West Florida Historic Preservation, Inc., Florida Bureau of Archaeological Research, and the government of the
Cayman Islands before joining FPAN. Della is an officer and elected board member of the Advisory Council on
Underwater Archaeology and is a member of the Register of Professional Archaeologists. Della's research
interests include public interpretation of maritime cultural resources, both on land and under water, and
training of avocationals in archaeological methods and practices. Her specialties are maritime archaeology,
colonial seafaring and public archaeology.
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/people/cheryl.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Office and Contracts Manager</em><br/>
(850) 595-0050 <br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('cheryl_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="cheryl_bio" class="hidden bio">
Cheryl is a graduate of the University of West Florida with a Bachelor's degree in Marketing. She worked
8 years in New Orleans in marketing before returning to Pensacola in 1989 to work at UWF.
</p>
</div>
</div><!-- /.row -->
</div> <!-- /.col -->
<div class="col-md-6 col-sm-6">
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/people/jason.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Web Architect</em><br/>
(850) 595-0050 Ext: 105 <br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('jason_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="jason_bio" class="hidden bio">
Jason graduated from the University of West Florida with a Bachelor's degree in Information Technology
with a minor in Computer Information Systems in 2008. He worked as Web Developer for the UWF Libraries
after graduation for some time before joining FPAN in 2010.
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/people/mike.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Manager, Destination Archaeology Resource Center</em><br/>
(850) 595-0050 Ext: 107 <br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('mike_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="mike_bio" class="hidden bio">
<NAME> is the manager of the Destination Archaeology Resource Center. He is also a regular writer
for the Unearthing Florida radio program broadcast on NPR member stations across the state of Florida.
Mike received his B.A. in history from the University of West Florida and is currently seeking a Masters
degree in the UWF Public History graduate program with a museum studies specialization. Mike has spent
nearly a decade in the museum field, is a Certified Guide with the National Association of Interpretation,
and has worked with several organizations on heritage interpretative projects and programs across the
state including the Florida Anthropological Society, Florida Division of Historical Resources, Florida
State Parks, U.S. Forest Service and the National Park Service. He has curated a number of museum exhibits
on a range of diverse topics from piracy in the Gulf of Mexico to the roles women played in Northwest
Florida during the Great Depression. He currently serves on FPAN's Archaeological Tourism Task Force and
on the Trail of Florida Indian Heritage Board of Directors. His research interests include Mississippian
period southeastern Native Americans, maritime history of the Gulf of Mexico during Florida's Territorial
Period, public history, and public archaeology.
</p>
</div>
</div><!-- /.row -->
</div> <!-- /.col -->
</div> <!-- /.row one -->
<a id="regionStaff"></a>
<div class="row">
<div class="col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<h2> Regional Staff</h2>
<div class="box-dash">
<p>
To see staff members in other regions, please visit the corresponding regional website:
<div class="row">
<div class="col-sm-6">
<ul class="btn-list text-center">
<li><a href="/nwrc/contact.php" class="btn nw-btn btn-lg btn-region active" role="button">Northwest</a></li>
<li><a href="/ncrc/contact.php" class="btn nc-btn btn-lg btn-region active">North Central</a></li>
<li><a href="/nerc/contact.php" class="btn ne-btn btn-lg btn-region active">Northeast</a></li>
<li><a href="/ecrc/contact.php" class="btn ec-btn btn-lg btn-region active">East Central</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul class="btn-list text-center">
<li><a href="/crc/contact.php" class="btn c-btn btn-lg btn-region active">Central</a></li>
<li><a href="/wcrc/contact.php" class="btn wc-btn btn-lg btn-region active">West Central</a></li>
<li><a href="/swrc/contact.php" class="btn sw-btn btn-lg btn-region active">Southwest</a></li>
<li><a href="/serc/contact.php" class="btn se-btn btn-lg btn-region active">Southeast</a></li>
</ul>
</div>
</div>
</p>
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row two -->
</div><!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Then and Now: Life Along the New River";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Then and Now: Life Along the New River</h1></th>
</tr>
<tr>
<td class="table_mid">
<div id="exhibit">
<?php include 'nav.php'?>
<h2 align="center">Education</h2>
<p>Fort Lauderdale’s first school was built in 1899 on the south bank of the New River at Andrews Ave. Nine students attended the one-room schoolhouse. They were taught by <NAME>, who was paid $40 a month. Unlike the school buses of today, wagons transported these New River students to school.
<br />
<strong><br />
<img src="images/exhibit9.jpg" style="float:right; margin-left:10px" alt="The original Colored School, built in 1924, is now the Old Dillard School Museum.<br/>
Photo and caption courtesy of the Old Dillard Museum." /><br/>
While education was freely available for white children, it wasn’t until eight years later that an elementary school was built for African Americans.</strong> Known as the “Colored School”, this building was replaced in 1924 with a larger structure that allowed African American students to complete up to their 10th grade education. The Dillard School, as it was renamed in 1930, was located in the neighborhood now called Dorsey-Riverbend.</p>
<p> </p>
<p>
<img src="images/exhibit10.jpg" style="float:left; margin-right:10px" alt="The first Dillard High School Band, 1946. Band director <NAME>, in front. <br/>
Photo and caption courtesy of the Old Dillard Museum." />
</p>
<p> </p>
<p>In 1927, City officials had restricted African Americans to homes in this area and even limited their ability to travel into other neighborhoods after dark. The Dillard School operated on a shortened school year with classes in session from Easter to Thanksgiving, so children ages 9 and up could work in the agricultural fields. Children would walk ten miles to Margate to pick green beans all day. Recognizing that the shorter school year and labor demands did not permit the African American students to get an equal education, the
Dillard School’s Principal Walker encouraged students to protest the length of the school year. In 1941, students boycotted classes until the regular September school term began. Nevertheless, the School Board did not reverse their unequal school year policies until 1947 when forced to do so by a federal court. The Broward County Schools remained segregated until 1961 nearly 40 years after the first African American school had opened. <br />
<br />
<strong>Today the banks of the New River are lined by institutes of learning</strong> that cater to all of Ft. Lauderdale’s communities. The headquarters of Broward County Schools is located on the south bank of the New River blocks from that first 1899 school. Broward College and the Fort Lauderdale campus of Florida Atlantic University are both located within a few blocks of the New River. These institutions have been educating and serving the community for over twenty years.</p>
</div>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?>
<file_sep><?php
/****************************************************************************************************************/
/******************************************** Report Functions **********************************************/
/****************************************************************************************************************/
//Setup initial blank array with proper structure for summary report
function getEmptyEventSummaryArray(){
$emptyEventSummaryArray = array("nwrc" => array(), "ncrc" => array(),
"nerc" => array(), "wcrc" => array(),
"crc" => array(), "ecrc" => array(),
"serc" => array(), "swrc" => array());
foreach(getRegionArray() as $region){
foreach(getTypeActivityArray() as $typeActivity){
$emptyEventSummaryArray[$region][$typeActivity] = array("numEvents" => "", "numAttendees" => "", "counties" => "");
}
}
return $emptyEventSummaryArray;
}
//Set up associative array of regions and all associated ActivityIDs for each region
function getRegionActivityIDArray(){
$db = new mysqli('fpanweb.powwebmysql.com', 'reports_user', ')OKM9ijn', 'fpan_dev_reports');
//Get ActivityIDs for each region
$regionActivityIDs= array('nwrc'=>'','ncrc'=>'','nerc'=>'','wcrc'=>'','crc'=>'','wcrc'=>'','ecrc'=>'','swrc'=>'','serc'=>'');
foreach(getRegionArray() as $region){
$sql = "SELECT activityID FROM EmployeeActivity WHERE employeeID IN
(SELECT employeeID FROM EmployeeRegion WHERE region = '$region');";
$result = $db->query($sql) or die('There was an error running the query [' .$db->error. ']');
while($row = $result->fetch_assoc())
$regionActivityIDs[$region][] = $row['activityID'];
$result->free();
}
$sql="";
$db->close();
return $regionActivityIDs;
}
/**********************************************************************************************/
// Get total event numbers for given date range for all regions
/**********************************************************************************************/
function rangedEventSummaryByRegion($startDate, $endDate, $regionActivityIDs){
$db = new mysqli('fpanweb.powwebmysql.com', 'reports_user', ')OKM9ijn', 'fpan_dev_reports');
if($db->connect_errno > 0){
die('Unable to connect to database [' .$db->connect_error.']');
}
//Set up initial region arrays
$regionArray = getRegionArray();
//Loop for each region
foreach($regionArray as $region){
//prepare activityIDarray
$activityIDArray = join(',',$regionActivityIDs[$region]);
//intialize activity type arrays
$typeActivityArray = getTypeActivityArray();
$numberActivityTypes = count($typeActivityArray);
$sql="";
//Loop for each activity type
foreach($typeActivityArray as $typeActivity){
$sql .= "SELECT '$typeActivity' AS 'typeActivity', COUNT(*) AS 'numEvents'
FROM $typeActivity
WHERE id IN ($activityIDArray)
AND activityDate BETWEEN '$startDate' AND '$endDate' ";
//decrement activity counter and add UNION sql if not last type
if($numberActivityTypes -- > 1)
$sql .= " UNION ALL ";
} //end activity type loop
$result = $db->query($sql) or die('There was an error running the query [' .$db->error. ']');
//Fill array Activity Type and Number of Events
while($row = $result->fetch_assoc()){
foreach(getTypeActivityArray() as $typeActivity){
if($row['typeActivity'] == $typeActivity){
if($typeActivity == "SocialMedia")
$eventSummaryArray[$region][$typeActivity]['numEvents'] = NULL;
else
$eventSummaryArray[$region][$typeActivity]['numEvents'] = number_format($row['numEvents']);
}
}
}
$result->free();
$sql = "";
//**********************************************************************************************
//Get number of attendess for public outreach, training/workshop, social media, directmail
//**********************************************************************************************
$sql = "SELECT 'PublicOutreach' AS 'typeActivity', SUM(numberAttendees) AS 'numAttendees'
FROM PublicOutreach
WHERE id IN ($activityIDArray)
AND activityDate BETWEEN '$startDate' AND '$endDate'
UNION ALL
SELECT 'TrainingWorkshops' AS 'typeActivity', SUM(numberAttendees) AS 'numAttendees'
FROM TrainingWorkshops
WHERE id IN ($activityIDArray)
AND activityDate BETWEEN '$startDate' AND '$endDate'
UNION ALL
SELECT 'SocialMedia' as 'typeActivity', SUM(totalReach) AS 'numAttendees'
FROM
(SELECT fbReach+twitterFollowers+blogVisitors AS totalReach
FROM SocialMedia
WHERE activityDate BETWEEN '$startDate' AND '$endDate'
AND submit_id IN (SELECT employeeID FROM EmployeeRegion WHERE region = '$region')) AS derivedTable
UNION ALL
SELECT 'DirectMail' AS 'typeActivity', SUM(numberOfContacts) AS 'numAttendees'
FROM DirectMail
WHERE id IN ($activityIDArray)
AND activityDate BETWEEN '$startDate' AND '$endDate' ";
//Fill array with Number of attendees info
$result = $db->query($sql) or die('There was an error running the query [' .$db->error. ']');
while($row = $result->fetch_assoc()){
foreach(getTypeActivityArray() as $typeActivity){
if($row['typeActivity'] == $typeActivity){
$eventSummaryArray[$region][$typeActivity]['numAttendees'] = number_format($row['numAttendees']);
}
}
}
$sql = "";
//**********************************************************************************************
//Get list of counties involved in public outreach, training/workshop, govt assistance, meetings
//**********************************************************************************************
$countyActivities = array("PublicOutreach", "TrainingWorkshops", "GovernmentAssistance", "Meeting");
foreach($countyActivities as $typeActivity){
$sql = "SELECT DISTINCT county as 'county'
FROM $typeActivity
WHERE id IN ($activityIDArray)
AND activityDate BETWEEN '$startDate' AND '$endDate'; ";
//Fill array with county
$result = $db->query($sql) or die('There was an error running the query [' .$db->error. ']');
while($row = $result->fetch_assoc()){
if($row['county'])
$eventSummaryArray[$region][$typeActivity]['counties'][] = $row['county'];
}
$sql = "";
}//end COUNTIES loop
}//end REGION loop
$db->close();
return $eventSummaryArray;
}
/**********************************************************************/
//Return array of totals of volunteer data within date range for summary
/**********************************************************************/
function volunteerSummary($startDate, $endDate, $regionActivityIDs){
$db = new mysqli('fpanweb.powwebmysql.com', 'reports_user', ')OKM9ijn', 'fpan_dev_reports');
$sql="";
$regionCount = 7;
foreach(getRegionArray() as $region){
$activityIDArray = join(',',$regionActivityIDs[$region]);
$sql.= "SELECT '$region' AS 'Region',
SUM(numberVolunteers) AS 'numberVolunteers',
SUM(volunteerHours) AS 'volunteerHours'
FROM `PublicOutreach`
WHERE id IN ($activityIDArray)
AND PublicOutreach.activityDate
BETWEEN '$startDate' AND '$endDate'";
if($regionCount-- > 0)
$sql.= " UNION ALL ";
}
$result = $db->query($sql) or die('There was an error running the query [' .$db->error. ']');
while(($resultArray[] = $result->fetch_assoc()) || array_pop($resultArray)){
$lastValue = array_pop($resultArray);
if(is_numeric($lastValue)){
$newValue = number_format($lastValue);
array_push($resultArray, $newValue);
}else
array_push($resultArray, $lastValue);
}
$db->close;
return $resultArray;
}
/**********************************************************************/
//Return array of totals of attendee data within date range for summary
/**********************************************************************/
function attendeeSummary($startDate, $endDate, $regionActivityIDs){
$db = new mysqli('fpanweb.powwebmysql.com', 'reports_user', ')OKM9ijn', 'fpan_dev_reports');
$sql="";
$regionCount = 7;
foreach(getRegionArray() as $region){
$activityIDArray = join(',',$regionActivityIDs[$region]);
$sql.= "SELECT '$region' AS 'Region',
SUM(numberAttendees) AS 'numberAttendees',
'PublicOutreach' AS 'eventType'
FROM `PublicOutreach`
WHERE id IN ($activityIDArray)
AND PublicOutreach.activityDate
BETWEEN '$startDate' AND '$endDate'
UNION ALL
SELECT '$region' AS 'Region',
SUM(numberAttendees) AS 'numberAttendees',
'TrainingWorkshops' AS 'eventType'
FROM `TrainingWorkshops`
WHERE id IN ($activityIDArray)
AND TrainingWorkshops.activityDate
BETWEEN '$startDate' AND '$endDate'";
if($regionCount-- > 0)
$sql.= " UNION ALL ";
}
$result = $db->query($sql) or die('There was an error running the query [' .$db->error. ']');
while(($resultArray[] = $result->fetch_assoc()) || array_pop($resultArray)){
$lastValue = array_pop($resultArray);
if(is_numeric($lastValue)){
$newValue = number_format($lastValue);
array_push($resultArray, $newValue);
}else
array_push($resultArray, $lastValue);
}
$result->free();
$db->close();
return $resultArray;
}
?>
<file_sep><?php
include 'appHeader.php';
include $header;
//initialized some vars
$rowsperpage = 15; // number of events to show per page
if(isset($_GET['archive'])){
$archive = $_GET['archive'];
$archiveURL = "&archive=true";
$pageHeader = "Events Archive";
}else{
$archive = null;
$archiveURL = null;
$pageHeader = "Upcoming Events";
}
// ********** Setup SQL queries ********** //
//If eventDate is define in URL, show only events for that day
if(isset($_GET['eventDate'])){
$eventDate = $_GET['eventDate'];
$sql = "SELECT * FROM $table WHERE eventDateTimeStart LIKE '$eventDate%' ORDER BY eventDateTimeStart ASC;";
//if eventDate is not set, show all upccoming events
}else{
// find out how many rows are in the table
if($archive==true){
$sql = "SELECT COUNT(*) FROM $table
WHERE eventDateTimeStart <= CURDATE()";
}else{
$sql = "SELECT COUNT(*) FROM $table
WHERE eventDateTimeStart >= CURDATE()";
}
$result = mysqli_query($dblink, $sql);
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
}else{
$currentpage = 1;
}
if ($currentpage > $totalpages)
$currentpage = $totalpages;
if ($currentpage < 1)
$currentpage = 1;
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
if($archive==true){
$sql = "SELECT * FROM $table
WHERE eventDateTimeStart <= CURDATE()
ORDER BY eventDateTimeStart DESC
LIMIT $offset, $rowsperpage";
}else{
$sql = "SELECT * FROM $table
WHERE eventDateTimeStart >= CURDATE()
ORDER BY eventDateTimeStart ASC
LIMIT $offset, $rowsperpage";
}
}
function showEvents(){
global $dblink, $sql, $archiveURL;
// ******** Run dem queries, print results ********* //
$listEvents = mysqli_query($dblink, $sql);
//If events found, print out events
if(mysqli_num_rows($listEvents) != 0){
echo "<hr/>";
while($event = mysqli_fetch_array($listEvents)){
$timestampStart = strtotime($event['eventDateTimeStart']);
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventDate = date('F j', $timestampStart);
$eventTimeStart = date('g:ia', $timestampStart);
$eventTimeEnd = date('g:ia', $timestampEnd);
?>
<div class="row event-list">
<p class="col-md-4 text-center">
<strong><span class="event-date"><?php echo $eventDate?></span> <span class="event-separator">@</span><br/>
<?php echo $eventTimeStart ?> <span class="event-separator">til</span> <?php echo $eventTimeEnd;?></strong>
</p>
<p class="col-md-4 text-center">
<?php echo stripslashes($event['title']) ?>
</p>
<div class="col-md-4 text-center event-controls">
<a class="btn btn-sm btn-primary" href="eventEdit.php?eventID=<?php echo $event['eventID'];?>" ><i class="fa fa-edit fa-lg"></i></a>
<a class="btn btn-sm btn-primary" href="eventEdit.php?eventID=<?php echo $event['eventID'];?>&dupe=true" ><i class="fa fa-copy fa-lg"></i></a>
<a class="btn btn-sm btn-primary" href="processEdit.php?eventID=<?php echo $event['eventID']; ?>&del=true<?php echo$archiveURL ?>" onclick="return confirm('Are you sure you want to delete this event?');"><i class="fa fa-trash-o fa-lg"></i></a>
</div>
</div>
<hr/>
<?php
}//end while
}else{
echo '<p class="text-center">No events are currently in the archive.</p>';
}
}
function showPaginationLinks(){
global $totalpages, $currentpage, $archiveURL;
/****** build the pagination links ******/
if($totalpages > 1){
echo "<ul class=\"pagination pagination-sm\">";
// range of num links to show on either side of current page
$range = 1;
// if not on page 1, show back links
if ($currentpage > 1) {
echo "<li><a href='{$_SERVER['PHP_SELF']}?currentpage=1$archiveURL'> « </a></li>";
// get previous page num
$prevpage = $currentpage - 1;
echo "<li><a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage$archiveURL'> < </a></li>";
}
// if on page 1, disable back links
if ($currentpage == 1) {
echo "<li class=\"disabled\"><a href=''> « </a></li>";
echo "<li class=\"disabled\"><a href=''> < </a></li>";
}
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
echo "<li class=\"active page-link\"><a class=\"btn btn-primary btn-md\" href=''> $x </a></li>";
// if not current page...
} else {
// make it a link
echo "<li class=\"page-link\"><a class=\"btn btn-primary btn-md\" href='{$_SERVER['PHP_SELF']}?currentpage=$x$archiveURL'>$x</a></li>";
}
}
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
echo "<li> <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage$archiveURL'> > </a></li>";
echo "<li> <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages$archiveURL'> » </a></li>";
} // end if
if ($currentpage == $totalpages) {
echo "<li class=\"disabled\"> <a href=''>></a> </li>";
echo "<li class=\"disabled\"> <a href=''>»</a> </li>";
}
echo "</ul>";
}
/****** end build pagination links ******/
}
?>
<div class="container">
<div class="page-header">
<h1><?php echo $pageHeader ?></h1>
</div>
<div class="row">
<div class="col-sm-8">
<?php
// echo current date if selected
if(isset($_GET['eventDate'])){
$printDate = date('M d, Y', strtotime($_GET['eventDate']));
echo "<h3><small> All Events for</small> $printDate </h3>";
}
?>
<div class="row box box-line box-tab">
<?php
//set class (color, styling) for success or error message
$class = ($err == 1 ? "alert-danger" : "alert-success");
//if there is an error or success message, display it
if(isset($msg))
echo "<div class=\"col-xs-6 col-xs-offset-3 text-center alert $class\"> $msg </div>";
?>
<div class="row">
<div class="col-sm-12 text-center">
<?php
if($archive==true)
echo '<p>All past events are displayed here and will remain on the calendar however,
past events will not be visible on the "Upcoming Events" page.</p>';
showPaginationLinks();
showEvents();
showPaginationLinks();
?>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.row -->
</div><!-- /.col -->
<div class="col-sm-4">
<?php include '../events/calendar.php'; ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include $footer ?><file_sep><div id="calendar-component">
<?php
include '../admin/dbConnect.php';
//Determine which page days link to based on whether using admin interface
$calPage = stristr($_SERVER['REQUEST_URI'], 'admin') ? "eventList.php" : "eventDetail.php";
/********* Lots of Calendar Init stuff here *******/
//This gets today's date
$date = time();
$day = date('d', $date);
//TODO:this is a hack
$table = 'nwrc';
//If month is defined in URL, use that. Else use today's date to determine month
$month = isset($_GET['month']) ? mysqli_real_escape_string($dblink, $_GET['month']) : date('m', $date);
//If year is defined in URL, use that. Else use today's date to determine year.
$year = isset($_GET['year']) ? mysqli_real_escape_string($dblink, $_GET['year']) : date('Y', $date);
//Generate the first day of the month
$first_day = mktime(0,0,0,$month, 1, $year) ;
//Get the month name
$title = date('F', $first_day) ;
//Find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;
//Once we know what day of the week it falls on, we know how many blank days occure before it. If the first day of the week is a Sunday then it would be zero
switch($day_of_week){
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}
//Determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year);
//Query to find dates that have events
$sql = "SELECT * FROM $table WHERE eventDateTimeStart LIKE '$year-$month-%'";
if($findEvents = mysqli_query($dblink, $sql)){
$eventDays = array();
while($event = mysqli_fetch_array($findEvents)){
$timestampDate = strtotime($event['eventDateTimeStart']);
$eventDate = date('Y-m-d', $timestampDate);
array_push($eventDays, $eventDate);
}
}
//Define calendar navigation variables
////Next
if($month < 12){
$nextMonth = $month+1;
if($nextMonth < 10)
$nextMonth = "0".$nextMonth;
$next = " data-month=$nextMonth data-year=$year";
}
else{
$nextYear = $year+1;
$next = " data-month=1 data-year=$nextYear";
}
////Prev
if($month > 1){
$prevMonth = $month-1;
if($prevMonth < 10)
$prevMonth = "0".$prevMonth;
$prev = " data-month=$prevMonth data-year=$year";
}
else{
$prevYear = $year-1;
$prev = " data-month=12 data-year=$prevYear";
}
?>
<div class="calendar center-block <?php echo $table.'-cal' ?>">
<div class="row">
<div class="col-xs-2">
<a href="#" id="prevMonth" data-table="<?=$table?>" <?=$prev?>> <h3> < </h3> </a>
</div>
<div class="col-xs-8">
<?php echo "<h3>" .$title. " " .$year."</h3>" ?>
</div>
<div class="col-xs-2">
<a href="#" id="nextMonth" data-table="<?=$table?>" <?=$next?>> <h3> > </h3></a>
</div>
</div>
<div class="row header center-block">
<div class="col-xs-1">S</div>
<div class="col-xs-1">M</div>
<div class="col-xs-1">T</div>
<div class="col-xs-1">W</div>
<div class="col-xs-1">R</div>
<div class="col-xs-1">F</div>
<div class="col-xs-1">S</div>
</div>
<div class="row center-block">
<?php
//This counts the days in the week, up to 7
$day_count = 1;
//first we take care of those blank days
while ( $blank > 0 ) {
echo "<div class=\"col-xs-1\"></div>";
$blank = $blank-1;
$day_count++;
}
//sets the first day of the month to 1
$day_num = 1;
//count up the days, untill we've done all of them in the month
while ( $day_num <= $days_in_month ){
//Add leading zeros for eventDate if needed
if($day_num < 10)
$eventDate = "$year-$month-0$day_num";
else
$eventDate = "$year-$month-$day_num";
//If this day has events, link to listing of events
if(in_array($eventDate, $eventDays))
echo "<div class=\"col-xs-1 hasEvent\">".
"<a href=\"$calPage?eventDate=$eventDate&month=$month&year=$year\" ".
"data-eventdate=$eventDate ".
"data-month=$month ".
"data-year=$year ".
">$day_num</a>".
"</div>";
else
echo "<div class=\"col-xs-1 \"> $day_num </div>";
$day_num++;
$day_count++;
//Make sure we start a new row every week
if ($day_count > 7){
echo '</div><div class="row center-block">';
$day_count = 1;
}
}
//Finaly we finish out the table with some blank details if needed
while ( $day_count >1 && $day_count <=7 ){
echo '<div class="col-xs-1"> </div>';
$day_count++;
}
?>
</div><!-- /.row -->
</div><!-- /.calendar -->
</div><!-- /.calendar-component -->
<file_sep><?php if (!defined('WEBPATH')) die();
require_once('normalizer.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="no" name="apple-mobile-web-app-capable" />
<!-- this will not work right now, links open safari -->
<meta name="format-detection" content="telephone=no">
<meta name="apple-touch-fullscreen" content="YES" />
<meta content="index,follow" name="robots" />
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type" />
<link href="<?php echo $_zp_themeroot ?>/images/homescreen.png" rel="apple-touch-icon" />
<meta content="minimum-scale=1.0, width=device-width, maximum-scale=0.6667, user-scalable=no" name="viewport" />
<link href="<?php echo $_zp_themeroot ?>/css/style.css" rel="stylesheet" type="text/css" />
<script src="<?php echo $_zp_themeroot ?>/javascript/functions.js" type="text/javascript"></script>
<script src="<?php echo $_zp_themeroot ?>/javascript/rotate.js" type="text/javascript"></script>
<title><?php echo getBareImageTitle();?> | <?php echo getBareGalleryTitle(); ?> > <?php echo getBareAlbumTitle(); ?></title>
<?php zp_apply_filter("theme_head"); ?>
<title><?php echo getBareGalleryTitle(); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php $archivepageURL = htmlspecialchars(getGalleryIndexURL()); ?>
<script type="application/x-javascript">
addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false);
function hideURLbar(){
window.scrollTo(0,1);
}
</script>
</head>
<body style="-webkit-touch-callout:inherit;" class="portrait">
<script type="text/javascript" language="JavaScript">
updateOrientation();
</script>
<div id="photoBox" class="fullScreen">
<?php
if (!isImagePhoto($_zp_current_image)) {
ob_start();
printCustomSizedImage(getImageTitle(), null, 604, null, null, null, null, null, null, photoImg_p);
$embedding_youtube = ob_get_contents();
ob_end_clean();
$embedding_youtube = str_replace('width="640" height="518"','width="250" height="202"',$embedding_youtube);
echo $embedding_youtube;
} else {
$ls = isLandscape();
printCustomSizedImage(getImageTitle(), null, $ls?604:453, null, null, null, null, null, null, $ls?photoImg_l:photoImg_p);
}
?>
<div id="photoCaption"><?php printImageTitle(true); ?> </div>
<?php
$img = $_zp_current_image->getPrevImage();
if ($img) {
?>
<a href="<?php echo htmlspecialchars(getPrevImageURL()); ?>" id="left" style="-webkit-touch-callout:none;">
<img id="left" src="<?php echo $_zp_themeroot ?>/images/arrow_left.png"></a>
<?php } ?>
<?php
$img = $_zp_current_image->getNextImage();
if ($img) {
?>
<a href="<?php echo htmlspecialchars(getNextImageURL()); ?>" id="right" style="-webkit-touch-callout:none;">
<img id="right" src="<?php echo $_zp_themeroot ?>/images/arrow_right.png"></a>
<?php } ?>
<a href="<?php echo htmlspecialchars(getAlbumLinkURL())."?appView=true"; ?>" id="photoBack" style="-webkit-touch-callout:none;"><?php printAlbumTitle();?> </a>
</div>
</body>
</html>
<file_sep><?php
$pageTitle = "Upcoming Events";
include('_header.php');
include('../events/eventList.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1>Upcoming Events</h1>
</div>
<div class="col-sm-8">
<p class="box-dash text-center">If you’d like to advertise your heritage event through FPAN, please see our <a href="../criteria.php">advertising statement and criteria.</a></p>
<?php
// echo current date if selected
if(isset($_GET['eventDate'])){
$printDate = date('M d, Y', strtotime($_GET['eventDate']));
echo "<h3><small> All Events for</small> $printDate </h3>";
}
?>
<div class="box-line box-tab">
<div class="row">
<div class="col-sm-12 text-center">
<?php
showPaginationLinks();
showEvents();
showPaginationLinks();
?>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.box -->
</div><!-- /.col -->
<div class="col-sm-4">
<?php include '../events/calendar.php'; ?>
</div>
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Volunteer";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-dash">
<div class="text-center">
<div class="image center-block" style="max-width:400px;">
<img src="images/volunteer.jpg" alt="" class="img-responsive" >
<p></p>
</div>
</div>
<p>The FPAN East Central office periodically needs volunteers to assist in two on-going projects: The Brevard County Historic Cemetery Recording Project (BCHCRP) and the Orange County Historic Cemetery Recording Project (OCHCRP). Both of these projects seek to record historic cemeteries for the Florida Master Site File, the state’s database for all cultural resources, as well as conduct some research about the sites themselves. Volunteers can assist in researching sites, helping to record sites, helping prepare reports, and assisting in some wider research geared towards public education about these cultural resources. No experience is necessary. If interested, please <a href="mailto:<EMAIL>">contact us</a>.</p>
</div><!-- /.box-tab -->
<h2>Get Involved</h2>
<div class="box-tab">
<p>There are many Organizations you can join to pursue an interest in archaeology. Here are some of our favorites:</p>
<h3>State Organizations</h3>
<ul>
<li><a href="http://www.fasweb.org/">Florida Anthropological Society</a></li>
<li><a href="http://www.flamuseums.org/">Florida Association of Museums</a></li>
<li><a href="http://www.floridatrust.org/">Florida Trust</a></li>
</ul>
<h3>National & International Organizations</h3>
<ul>
<li><a href="http://www.saa.org/">Society for American Anthropology</a></li>
<li><a href="http://www.sha.org/">Society for Historical Archaeology</a></li>
<li><a href="http://www.southeasternarchaeology.org/">Southeastern Archaeological Conference</a></li>
<li><a href="http://www.interpnet.com/">National Association for Interpretation</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep>
<div class="row header center-block">
<div class="col-xs-1">S</div>
<div class="col-xs-1">M</div>
<div class="col-xs-1">T</div>
<div class="col-xs-1">W</div>
<div class="col-xs-1">R</div>
<div class="col-xs-1">F</div>
<div class="col-xs-1">S</div>
</div>
<div class="row center-block">
<?php
//This counts the days in the week, up to 7
$day_count = 1;
//first we take care of those blank days
while ( $blank > 0 ) {
echo "<div class=\"col-xs-1\"></div>";
$blank = $blank-1;
$day_count++;
}
//sets the first day of the month to 1
$day_num = 1;
//count up the days, untill we've done all of them in the month
while ( $day_num <= $days_in_month ){
//Add leading zeros for eventDate if needed
if($day_num < 10)
$eventDate = "$year-$month-0$day_num";
else
$eventDate = "$year-$month-$day_num";
//If this day has events, link to listing of events
if(in_array($eventDate, $eventDays))
echo "<div class=\"col-xs-1 hasEvent\">".
"<a href=\"$calPage?eventDate=$eventDate&month=$month&year=$year\" ".
"data-eventDate=$eventDate ".
"data-month=$month ".
"data-year=$year ".
">$day_num</a>".
"</div>";
else
echo "<div class=\"col-xs-1 \"> $day_num </div>";
$day_num++;
$day_count++;
//Make sure we start a new row every week
if ($day_count > 7){
echo '</div><div class="row center-block">';
$day_count = 1;
}
}
//Finaly we finish out the table with some blank details if needed
while ( $day_count >1 && $day_count <=7 ){
echo '<div class="col-xs-1"> </div>';
$day_count++;
}
?>
</div><!-- /.row -->
<file_sep> <!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Upcoming Events</h1></th>
</tr>
<tr>
<td class="table_mid">
<div style="margin-left:40px; margin-right:40px;">
<br/><br/>
<?php
$upcomingEvents = mysql_query("SELECT * FROM $table
WHERE eventDateTimeStart >= CURDATE()
ORDER BY eventDateTimeStart ASC;");
if(mysql_num_rows($upcomingEvents) != 0 ){
while($event = mysql_fetch_array($upcomingEvents))
{
$timestampStart = strtotime($event['eventDateTimeStart']);
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventDate = date('l, F j, Y', $timestampStart);
$eventTimeStart = date('g:i a', $timestampStart);
$eventTimeEnd = date('g:i a', $timestampEnd);
echo "<p><strong class=\"color\" style=\"font-size:16px;\">". stripslashes($event['title']) . "</strong></p>";
echo "<p><strong>". $eventDate . " @ ".$eventTimeStart."</strong></p>";
//echo "<p><strong>Location:</strong><em> " . $event['location'] . "</em></p>";
echo "<p align=\"center\"><a href=\"eventDetail.php?eventID=" . $event['eventID'] . "&eventDate=". $eventDate . "\">View Details</a></p>";
echo "<hr/>";
}
}else
echo '<p align="center">No events currently scheduled. Check back soon!</p>';
?>
</div>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include 'calendar.php'; ?>
</div>
</div>
<div class="clearFloat"></div><file_sep><?php
$pageTitle = "iPhone Apps";
include('../_header.php');
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1><?php echo $pageTitle ?></h1>
</div>
<div class="col-sm-8 col-sm-push-2 ">
<div class="box-tab">
<h2>Destination: Civil War</h2>
<img src="images/DCW_screens.png" alt="" class="center-block">
<p>Delve into the story of the Civil War by exploring heritage sites throughout Florida! The Destination: Civil War app guides users to public places throughout the state and offers quick and easy access to site information, site histories and photographs. See what sites are near you or see what's out there in other areas of the state.</p>
<div class="text-center">
<a target="_blank" href="http://itunes.apple.com/us/app/destination-civil-war/id504889090?ls=1&mt=8" class="btn btn-primary">Download Now!</a>
</div>
</div>
<div class="box-tab">
<h3>FPAN Mobile</h3>
<img src="images/FPAN_mobile_screens.png" alt="" class="center-block">
<p>FPAN Mobile is our FPAN wide iPhone app that helps you get in contact with FPAN representatives in your region and see what kind of events are going on in your neck of the woods. See upcoming events and if one catches your eye, add it to your calendar! </p>
<div class="text-center">
<a target="_blank" href="http://itunes.apple.com/us/app/fpan-mobile/id478009860?mt=8&ls=1" class="btn btn-primary">Download Now!</a>
</div>
</div>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
$pageTitle = "Newsletter";
$email = isset($_GET['email']) ? $_GET['email'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle;?></h1>
</div>
<!-- Begin MailChimp Signup Form -->
<div class="col-sm-10 col-sm-push-1">
<form action="//fpan.us9.list-manage.com/subscribe/post?u=775c759e3cce2b3dea45e47c9&id=3a6e8a73bc" role="form"
method="post" class="" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate >
<h2>Join our mailing list</h2>
<div class="form-group">
<label class="control-label " for="mce-EMAIL">Email Address</label>
<div class="row">
<div class="col-xs-10">
<input type="email" value="<?=$email?>" name="EMAIL" class="form-control" id="mce-EMAIL">
</div>
<div class="col-xs-2">
<span class="required">*</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label" for="mce-FNAME">First Name </label>
<input type="text" value="" name="FNAME" class="form-control" id="mce-FNAME">
</div>
<div class="form-group">
<label class="control-label" for="mce-LNAME">Last Name </label>
<input type="text" value="" name="LNAME" class="form-control" id="mce-LNAME">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_775c759e3cce2b3dea45e47c9_3a6e8a73bc" tabindex="-1" value=""></div>
<div class="text-center"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn btn-primary"></div>
</form>
</div><!-- /.col -->
<!--End mc_embed_signup-->
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!-- <div class="box-tab col-sm-12">
<h2>Newsletter Archives</h2>
</div>/.col -->
</div><!-- /.col /.row -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep> <!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Upcoming Events</h1></th>
</tr>
<tr>
<td class="table_mid">
<div style="margin-left:40px; margin-right:40px;">
<?php
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM nwrc
WHERE eventDateTimeStart >= CURDATE()";
$result = mysql_query($sql, $link);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 6;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT * FROM nwrc
WHERE eventDateTimeStart >= CURDATE()
ORDER BY eventDateTimeStart ASC
LIMIT $offset, $rowsperpage";
$upcomingEvents = mysql_query($sql, $link);
// while there are rows to be fetched...
if(mysql_num_rows($upcomingEvents) != 0 ){
while($event = mysql_fetch_array($upcomingEvents))
{
$timestampStart = strtotime($event['eventDateTimeStart']);
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventDate = date('l, F j, Y', $timestampStart);
$eventTimeStart = date('g:i a', $timestampStart);
$eventTimeEnd = date('g:i a', $timestampEnd);
echo "<p><strong class=\"color\" style=\"font-size:16px;\">". stripslashes($event['title']) . "</strong></p>";
echo "<p><strong>". $eventDate . " @ ".$eventTimeStart."</strong></p>";
//echo "<p><strong>Location:</strong><em> " . $event['location'] . "</em></p>";
echo "<p align=\"center\"><a href=\"eventDetail.php?eventID=" . $event['eventID'] . "&eventDate=". $eventDate . "\">View Details</a></p>";
echo "<hr/>";
}
}else
echo '<p align="center">No events currently scheduled. Check back soon!</p>';
// end while
echo "<h4 align=\"center\">";
/****** build the pagination links ******/
// range of num links to show
$range = 1;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a>";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo "[<b>$x</b>]";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
echo "</h4>";
?>
</div>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include 'calendar.php'; ?>
</div>
</div>
<div class="clearFloat"></div><file_sep><?php
$pageTitle = "Explore";
$county = isset($_GET['county']) ? $_GET['county'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<!-- ********* ****************** ************** -->
<!-- ********* Explore Alachua County ********** -->
<!-- ********* ****************** ************** -->
<?php if($county == 'alachua'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Alachua<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/alachua.jpg" alt="" class="img-responsive">
<p>Learn about some of Gainesville’s past residents with an audio tour of the Historic Evergreen Cemetery.</p>
</div>
</div>
<p>Alachua County was established in 1824. This county houses a variety of museums and historic locations. Here, you have the opportunity to learn about Florida’s past at the Florida Museum of Natural History or discover the “Talking Walls” at the historic Haile Homestead.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.alachuacounty.us/Pages/AlachuaCounty.aspx">Alachua County</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.flmnh.ufl.edu/">Florida Museum of Natural History</a></li>
<li><a target="_blank" href="http://www.mathesonmuseum.org/">Matheson Historical Center </a></li>
<li><a target="_blank" href="http://www.hawthorneflorida.org/museum.htm">Hawthorne Historical Museum</a> </li>
<li><a target="_blank" href="http://www.visitgainesville.com/attractions/micanopy-historical-society-museum/">Micanopy Historical Society Museum</a> </li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/dudleyfarm/default.cfm">Dudley Farm Historic State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/paynesprairie">Payne’s Prairie Preserve State Park </a></li>
<li><a target="_blank" href="http://www.cityofgainesville.org/GOVERNMENT/CityDepartmentsNZ/NatureOperationsDivision/Ongoing/tabid/85/Default.aspx">Morningside Nature Center</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.ufl.edu/about-uf/history/">University of Florida campus</a></li>
<li><a target="_blank" href="http://www.hailehomestead.org/">Haile House Plantation</a></li>
<li><a target="_blank" href="http://www.gvlculturalaffairs.org/website/facilities/facilities.html">The Historic Thomas Center </a></li>
<li><a target="_blank" href="http://www.thiswondrousplace.org/audio-tours/">Evergreen Cemetery</a> </li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.afn.org/~archer/index.html">Archer Historical Society</a></li>
<li><a target="_blank" href="http://www.visitgainesville.com/arts-culture-history/">Visit Gainesville</a> </li>
<li><a target="_blank" href="http://classics.ufl.edu/other-resources/aia/">The Gainesville Society of the Archaeological Institute of America</a> </li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** ****************** -->
<!-- ********* Explore Bradford County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'bradford'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Bradford<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/bradford.jpg" alt="" class="img-responsive">
<p>Historic Call Street in Starke, Florida.</p>
</div>
</div>
<p>Alachua County was established in 1824. This county houses a variety of museums and historic locations. Here, you have the opportunity to learn about Florida’s past at the Florida Museum of Natural History or discover the “Talking Walls” at the historic Haile Homestead.</p>
<p>In 1858 New River County was established. The name would change to Bradford County three years later, named for Confederate Civil War officer Captain <NAME>. Today, Bradford plays host to heritage sites such as the Woman’s Club of Starke and the Call Street Historic District.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.bradfordcountyfl.gov/">Bradford County</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a href="http://www.bradfordhistory.com/default.asp" target="_blank">Bradford County Historical Society Museum</a></li>
<li><a target="_blank" href="http://www.sfcollege.edu/centers/andrews/?section=about">Eugene L. Matthews Historical Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.flheritage.com/preservation/markers/markers.cfm?ID=bradford">Woman’s Club of Starke</a></li>
<li>Call Street Historic District</li>
<p>Bordered by Jefferson, Cherry, Madison, and Temple Streets Starke, Florida</p>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** **************** -->
<!-- ********* Explore Citrus County ************* -->
<!-- ********* ****************** **************** -->
<?php }elseif($county == 'citrus'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Citrus<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/citrus.jpg" alt="" class="img-responsive">
<p>Learn about one of Florida’s most intriguing prehistoric sites at the Crystal River Archaeological State Park museum.</p>
</div>
</div>
<p>Citrus County was formally created in 1887, but its history dates much further back. Citrus County is home to the Crystal River Archaeological State Park which is a U.S. National Historic Landmark. This county also contains the Citrus County Coastal Heritage Museum as well as Fort Cooper State Park for visitors to experience.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.bocc.citrus.fl.us/">Citrus County</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.cccourthouse.org/crystalriver.php">Citrus County Coastal Heritage Museum</a></li>
<li><a href="http://www.cccourthouse.org/">Old Court House Heritage Museum</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a href="http://www.floridastateparks.org/crystalriverpreserve/" target="_blank">Crystal River Preserve State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/crystalriverarchaeological/default.cfm">Crystal River Archaeological State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/fortcooper/default.cfm">Fort Cooper State Park </a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.nxtbook.com/nxtbooks/milesmedia/floridablackheritage">Florida Black Heritage Trail</a></li>
<li><a target="_blank" href="http://www.floralcityhc.org/">The Floral City Historic District</a></li>
<li><a target="_blank" href="http://www.floridadesototrail.com/trail_map.html">The Florida De Soto Trail</a></li>
<li><a target="_blank" href="http://floridacourthouses.net/Citrus/citrus.html">The Old Citrus County Courthouse</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/yuleesugarmill/default.cfm">Yulee Sugar Mill Ruins State Historic Site</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://citruscountyhistoricalsociety.org/index.php">Citrus County Historical Society</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** ******************* -->
<!-- ********* Explore Gilchrist County ************* -->
<!-- ********* ****************** ******************* -->
<?php }elseif($county == 'gilchrist'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Gilchrist<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/gilchrist.jpg" alt="" class="img-responsive">
<p>Paddle steamer "City of Hawkinsville of Tampa" moored at a dock on the Suwannee River, Florida.</p>
</div>
</div>
<p>Although established formally in 1925 and being Florida’s newest county, the history of Gilchrist County dates far back beyond this point. Gilchrist County enables visitors to experience the historic City of Hawkinsville State Archaeological Preserve as well as other sites that represent the heritage of this county.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.gilchrist.fl.us/">Gilchrist County</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a href="http://www.exploresouthernhistory.com/fortfanning.html" target="_blank">Fort Fanning City Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/fanningsprings/default.cfm">Fanning Springs State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Shipwrecks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.museumsinthesea.com/hawkinsville/index.htm">City of Hawkinsville</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Hernando County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'hernando'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Hernando<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/hernando.jpg" alt="" class="img-responsive">
<p>Postcard for Weeki Wachee Spring, on Florida's gulf coast scenic highway.</p>
</div>
</div>
<p>Hernando County is home to a great group of diverse attractions. Visitors to this county can enjoy the wonders that Weeki Wachee State Park has to offer as well as explore the Brooksville Historical Train Depot. The Brookeville Raid, held on the 3rd weekend of January every year, is also a great attraction to experience in Hernando County, boasting the largest Civil War reenactment in the state.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.co.hernando.fl.us/">Hernando County</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.hernandohistoricalmuseumassoc.com/">Hernando Heritage Museum</a></li>
<li><a target="_blank" href="http://www.naturecoastcoalition.com/pdfs/hernando.pdf">Chinsegut Hill, Lake Lindsey, Chinsegut Nature Center</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://weekiwachee.com/">Weeki Wachee State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a href="http://www.flheritage.com/facts/reports/places/index.cfm?fuseaction=FullImage&id=941" target="_blank">William Sherman Jennings House</a></li>
<li><a target="_blank" href="http://www.brooksvillehistoricaltraindepot.com/">Brooksville Historical Train Depot</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.hernandohistoricalmuseumassoc.com/raid">Brooksville Raid</a></li>
<li><a target="_blank" href="http://www.hernandohistoricalmuseumassoc.com/">Hernando Historical Museum Association</a></li>
<li><a target="_blank" href="http://hernandopreservation.bravehost.com/">Historic Hernando Preservation Society</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Lake County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'lake'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Lake<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/lake.jpg" alt="" class="img-responsive">
<p>Brown family on the steps of their home in Lake County, Florida</p>
</div>
</div>
<p>Lake County houses an extensive roster of museums within its borders. Museums such as the Groveland Historical Museum, Lake County Historical Museum, and the Mount Dora History Museum are located in this county.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.lakecountyfl.gov/">Lake County</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.grovelandhistory.org/home.html">Groveland Historical Museum </a></li>
<li><a target="_blank" href="http://www.ladylake.org/home/historical-museum">Lady Lake Historical Society Museum</a></li>
<li><a target="_blank" href="http://www.lakecountyfl.gov/historical_museum/">Lake County Historical Museum</a></li>
<li><a target="_blank" href="https://www.facebook.com/pages/Eustis-Historical-Museum-Preservation-Society/117230934998929?ref=hl">Eustis Historical Museum and Preservation Society</a></li>
<li><a target="_blank" href="http://www.leesburgheritagesociety.com/">Leesburg Heritage Society and Historical Museum</a></li>
<li><a target="_blank" href="http://www.smithsonianmag.com/museumday/venues/Mount-Dora-History-Museum.html">Mount Dora History Museum</a></li>
<li><a href="http://mountdoracenterforthearts.org/" target="_blank">Mount Dora Center for the Arts</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.cityofclermontfl.com/index.asp?Type=B_BASIC&SEC={AACE746E-4923-4109-8802-60B40F885AC3}&DE=">South Lake County Historical Society Townsend House</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.stjohnsriverhistsoc.org/">Saint Johns River Historical Society</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Levy County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'levy'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Levy<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/levy.jpg" alt="" class="img-responsive">
<p>Bird's Eye View of Cedar Key, FL in 1884</p>
</div>
</div>
<p>Inside Levy County you can find a variety of sites that represent the heritage of this county. The Ceder Keys National Wildlife Refuge gives visitors an opportunity to explore the unique ecosystem of the area. Ceder Key Museum State Park and Shell Mound Park are some of the other great attractions to visit in this area.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.levycounty.org/">Levy County</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://cedarkeymuseum.com/">Cedar Key Historical Society Museum</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/cedarkeymuseum/">Cedar Key Museum State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://seenorthflorida.com/destinations/shellmound.php">Shell Mound Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/fanningsprings/default.cfm">Fanning Springs State Park</a></li>
<li><a target="_blank" href="http://www.fws.gov/cedarkeys/">Cedar Keys National Wildlife Refuge</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.levycountyhistoricalsociety.com/">Levy County Historical Society</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Marion County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'marion'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Marion<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/marion.jpg" alt="" class="img-responsive">
<p><NAME> Rawlings Historic State Park</p>
</div>
</div>
<p>Marion County was formally established in 1844 although its borders were altered multiple times up until 1877. Examples of the types of attractions in this county are the Marion County Museum of History and Archaeology, where visitors can discover Marion County’s past, and <NAME> Rawlings Historic State Park.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.marioncountyfl.org/">Marion County</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a href="http://www.appletonmuseum.org/" targe="_blank">Appleton Museum</a> </li>
<li><a target="_blank" href="http://www.marion.k12.fl.us/district/srm/index.cfm">Silver River Museum</a></li>
<li><a target="_blank" href="http://marioncountyarchaeology.com/mcmha/mcmha.htm">Marion County Museum of History and Archaeology</a></li>
<li><a target="_blank" href="http://www.cf.edu/departments/instruction/las/vpa/webber/webber_gallery.htm">Webber Center Gallery</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.marioncountyfl.org/Parks/Pr_Directory/Park_Carney.aspx">Carney Island Recreation and Conservation Area</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/marjoriekinnanrawlings/default.cfm">Marjorie Kinnan Rawlings Historic State Park</a></li>
</ul>
</div>
<h2>Historic Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://partners.ocalamarion.com/partner/mcintosh-historic-district/">McIntosh Historic District</a></li>
<li><a target="_blank" href="http://partners.ocalamarion.com/partner/boomtown-historic-district/">Boomtown Historic District</a></li>
<li><a target="_blank" href="http://www.feeldowntownocala.com/">Ocala Historic Downtown Square</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Sumter County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'sumter'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Sumter<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center">
<div class="image">
<img src="images/sumter.jpg" alt="" class="img-responsive">
<p>Dade Battlefield Historic State Park.</p>
</div>
</div>
<p>Sumter County is a great destination for history lovers who can visit the Dade Battlefield Historic State Park, the site of the battle that started the Second Seminole War. The visitor center at this state park displays information about the battle as well as a short film. The Dade Battlefield Society hosts reenactments at this site and is a great resource to get a real feeling for this site’s history.</p>
</div>
</div>
<div class="col-md-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://sumtercountyfl.gov/">Sumter County</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/dadebattlefield/default.cfm">Dade Battlefield Historic State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.cem.va.gov/cems/nchp/florida.asp">Florida National Cemetery</a></li>
<li><a target="_blank" href="http://www.webcitation.org/query?url=http://www.geocities.com/yosemite/rapids/8428/hikeplans/bushnell/planbushnell.html&date=2009-10-26+00:29:21">Bushnell Historical Trail</a></li>
</ul>
</div>
<h2>Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.dadebattlefield.com/">Dade Battlefield Society</a></li>
</ul>
</div>
</div><!-- /.col -->
<?php }else{ ?>
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-12 col-md-8 col-md-push-2">
<p>
The Central region offers many amazing historical and archaeological sites that you can visit. Click on any county below to discover sites in your area.
<hr/>
<!-- Interactive SVG Map -->
<div id="cmap" class="center-block"></div>
</p>
<!-- <hr/>
<div class="col-sm-12 text-center">
<div class="image"><img src="" alt="" class="img-responsive" width="400" height="464"></div>
</div> -->
</div>
</div><!-- /.row -->
<?php } ?>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#cmap').mapSvg({
source: 'images/c_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //North Central Region Marker
xy:[200,365],
tooltip:'Central Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Bradford' :{popover:'<h3>Bradford</h3><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=bradford"> Explore Bradford County</a></p>'},
'Alachua' :{popover:'<h3>Alachua</h3><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=alachua"> Explore Alachua County</a></p>'},
'Gilchrist' :{popover:'<h3>Gilchrist</h3><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=gilchrist"> Explore Gilchrist County</a></p>'},
'Levy' :{popover:'<h3>Levy</h3><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=levy"> Explore Levy County</a></p>'},
'Marion' :{popover:'<h3>Marion</h3><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=marion"> Explore Marion County</a></p>'},
'Lake' :{popover:'<h3>Lake</h3><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=lake"> Explore Lake County</a></p>'},
'Sumter' :{popover:'<h3>Sumter</h3><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=sumter"> Explore Sumter County</a></p>'},
'Citrus' :{popover:'<h3>Citrus</h3><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=citrus"> Explore Citrus County</a></p>'},
'Hernando' :{popover:'<h3>Hernando</h3><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=hernando"> Explore Hernando County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
include 'header.php';
//Employee activate/deactivate form submitted
if($_POST['submit']){
$changeTo = $_POST['activeStatus'];
$id = $_POST['id'];
$sql = "UPDATE Employees SET isActive = '$changeTo' WHERE id = '$id'";
mysql_query($sql);
}
$regionsArray = join('\',\'',$_SESSION['my_regions']);
$employeeSql = "SELECT * FROM Employees WHERE id IN (SELECT employeeID FROM EmployeeRegion WHERE region IN ('$regionsArray')) ORDER BY position DESC";
$listEmployees = mysql_query($employeeSql);
echo mysql_error();
?>
<table width="700" border="0" cellspacing="2" align="center">
<tr>
<td valign="top" style="width:200px;">
<h3 align="center">Admin Options</h3>
<ul>
<li><a href="changePassword.php">Change my Password</a></li>
<?php if($_SESSION['my_role'] != 3){ ?>
<li><a href="addEmployees.php">Add an Employee</a></li>
<?php } ?>
</ul>
<p> </p>
</td>
<td valign="top" style="width:500px;">
<h3 align="center">Employees in Your Region(s)</h3>
<table id="employees" class="tablesorter" style="margin-left:auto; margin-right:auto;">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
if(mysql_num_rows($listEmployees) != 0)
while($employee = mysql_fetch_array($listEmployees)){
$employee['isActive'] ? $isActive="Active" : $isActive="Inactive";
$employee['isActive'] ? $text="Deactivate" : $text="Activate";
$employee['isActive'] ? $color="Green" : $color="Red";
$employee['isActive'] ? $activeStatus="0" : $activeStatus="1";
if($isActive=="Active"){
echo '<tr><td>'
.$employee['firstName'].' '.$employee['lastName'].'</td><td>'
.$employee['position'].'</td><td>'
.'<span style="color:'.$color.'">'.$isActive.'</span></td><td>';
?>
<form action="admin.php" method="post">
<input name="submit" style="font-size:10px" type="submit" value="<?php echo $text; ?>" text="<?php echo $text; ?>"/>
<input name="activeStatus" type="hidden" value="<?php echo $activeStatus; ?>" />
<input name="id" type="hidden" value="<?php echo $employee['id']; ?>" />
</form>
<?php
echo '</td></tr>';
}
} ?>
</tbody>
</table>
</td>
</tr>
<tr>
<td colspan="2">
<hr/>
<!---
<h3 align="center">Admin Options</h3>
<ul>
<li><a href="addEmployees.php">Add Employees</a></li>
</ul>
<p> </p>
<p> </p>
--->
</td>
</tr>
</table>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "Programs";
include 'header.php';
?>
<!-- Main Middle -->
<script type="text/javascript">
showElement('projects_sub');
</script>
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Workshops</h1></th>
</tr>
<tr>
<td class="table_mid">
<p>
We offer a variety of workshops throughout the year, but are also happy to respond to special requests! Our most common offerings are listed below. To attend or request a workshop, please <a href="mailto:<EMAIL>
">contact us</a>. <br />
<br />
</p>
<hr/>
<p align="center">
<img src="images/CRPT_logo.jpg" alt="" class="padded" /></p>
<p>
<strong class="color">Cemetery Resource Protection Training</strong> (CRPT) focuses on cemetery care and protection. Participants explore cemeteries as historical resources, laws that protect them, conserving headstone and markers, managing cemetery landscapes, and practice hands-on headstone cleaning with a D-2 solution. </p>
<p> <br />
</p>
<hr/>
<p align="center"><br/>
<img src="images/Project Archaeology.jpg" alt="Project Archaeology" class="padded" /></p>
<p><br />
<strong class="color"><em>Project Archaeology: Investigating Shelter</em></strong> is a supplementary science and social studies curriculum unit for grades 3 through 5. This workshop aims to familiarize educators with archaeology resources for the classroom that enhance learning opportunities in math, science, art, and social studies. Workshop participants will receive archaeology education guides published by <em>Project Archaeology</em> that take students through scientific processes and an archaeological investigation of Kingsley Plantation, including accounts from oral history, use of primary documents, and interpreting the archaeological record. <br />
<br />
To learn more about<em> Project Archaeology</em>, visit <a href="http://www.projectarchaeology.org/" target="_blank">www.projectarchaeology.org</a>. <br />
</p>
<hr/>
<p align="center"><br/>
<img src="images/TimuTech.jpg" alt="Timucuan Technology" class="padded" /></p>
<p><br />
<strong class="color"><em>Timucuan Technology</em></strong> is a book of lesson plans focused on biotechnology of Timucuan Indians through the study of archaeology in northeast Florida. It explores human interaction with the environment and changes made over time by the timucua to meet basic needs through biological products. Geared towards 6th-8th grade students, <em>Timucuan Technology</em> uses hands-on activities to address Sunshine State Standards in science, math, language arts, and social studies.<br />
Due to the extensive content of these lessons, each workshop focuses on only one or two elements of the book itself. Sections for workshops include: <br/>
Pyrotechnology
<ul>
<li>Tool-Making Technology</li>
<li>Animal Technology</li>
<li>Wild Plant Technology</li>
<li>Agricultural Technology</li>
<li>Building Technology</li>
<li>Archaeological Technology</li>
<li>Archaeology—Beyond Excavation</li>
<li>History and the Timucua</li>
</ul>
</p>
<p>To learn more about <em>Timucuan Technology</em>, visit <a href="http://www.flpublicarchaeology.org/timucuan" target="_blank">www.flpublicarchaeology.org/timucuan</a>
<br />
</p>
<hr/>
<p align="center">
<a href="http://www.coquinaqueries.org"><img src="images/Coquina Queries.jpg" alt="Coquina Queries" class="padded" /></a></p>
<p><br />
<strong class="color">Coquina Queries</strong> introduces educators to archaeology resources for the classroom that enhance learning opportunities in math, science, language arts, and social studies. Participants receive the book of lessons and activities developed by FPAN using a state grant. Winner of the 2010 Florida Preservation Award, <em>Coquina Queries</em> explores archaeology and northeast Florida’s past through coquina, a unique stone native to the region. It offers a variety of hands-on activities and is aligned with Sunshine State Standards for 4th and 5th grade students, though they can be adapted for students of any age.<br />
<br />
To learn more about <em>Coquina Queries</em>, visit <a href="http://www.coquinaqueries.org">www.coquinaqueries.org</a>.</p>
<p> </p>
<!---
<hr/>
<h2 align="center"><br />
Become a Certified Interpretive Guide!</h2>
<p align="center"><a href="images/NAI_flier.png"><img src="images/NAI_flier_sm.png" class="padded" /></a></p>
<p align="center">
<a href="documents/RegistrationFormNAI.pdf"> NAI Training Registration Form </a>
</p>
<br/>
<hr/>
--->
<!---
<p align="center"><a href="documents/Advocacy_Workshop_flier.pdf" target="_blank"><img src="images/advocacy_workshop_flier.png" /></a></p>
<p>
In response to recent events impacting local heritage sites, we invite the public to join us as we discuss archaeology beyond artifacts, legal issues to consider when people dig, ethical considerations of residents and professionals, and the emotional attachments that exist between a community and the place they live. We will brainstorm short-term and long-term solutions to current events, evaluating the affordances and constraints of various actions.
The goal of the offering is to provide resources for residents considering taking on a more active role in archaeological current events and inform an advocate's decision making processes.
<br />
</p>
<hr/>
--->
<h2 align="left">Additional Programming</h2>
<p align="left">Still want more? Check out our <a href="http://storify.com/FPANNortheast"><strong>Storify</strong></a> and <a href="http://fpannortheast.tumblr.com/"><strong>Tumblr</strong></a> pages!</p>
<p>For more local archaeology news, sign up for our latest <a href="http://flpublicarchaeology.org/newsletter/northeast/user/subscribe.php"><strong>newsletter</strong></a>!</p></td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
$pageTitle = "Links";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Site Preservation</h1></th>
</tr>
<tr>
<td class="table_mid"><p>Florida’s archaeology sites are a precious, nonrenewable resource. Here are some ways that citizens can help protect and preserve archaeology sites.</p>
<p><strong>Florida Master Site File</strong></p>
<p>Adding sites to the Florida Master Site File protects sites in two ways: it documents what is currently known about them, which can be helpful to archaeologists studying other sites nearby. Second, it creates a permanent record of the site that is provided when construction is set to take place in the area. If you believe you have a site on your property, please contact our <a href="mailto:<EMAIL>">Site ID Specialist</a>, who can help assess and document the resource. </p>
<p><strong class="color">Archaeological Ordinances: </strong></p>
<p>Sites can also be protected through local legislation. Though state and federal laws protect much public land, local governments can get involved to preserve local archaeological resources. See the links below for examples of real archaeological and preservation ordinances that are locally in use (as well as one sample ordinance).</p>
<p><a href="documents/ClayCounty.pdf">Clay County </a><br />
<a href="documents/NewSmyrna.pdf">New Smyrna</a><br />
<a href="documents/PonceInlet.pdf">Ponce Inlet</a><br />
<a href="documents/St.Augustine.pdf">St. Augustine </a><br />
<a href="documents/St.JohnsCounty.pdf">St. Johns County </a><br />
<a href="documents/VolusiaCounty.pdf">Volusia</a><br />
<a href="documents/BlankOrdinance.pdf">Blank Sample Ordinance </a> </p></td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
$pageTitle = "Training Programs";
include '../header.php';
?>
<!-- Main Middle -->
<div class="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Training Programs</h1></th>
</tr>
<tr>
<td ><p>The Florida Public Archaeology Network offers training programs, workshops, and informational presentations on a variety of topics. </p>
<p>Whether you need:</p>
<ul>
<li> training for professional certification</li>
<li>to maintain CEUs</li>
<li> a new way to get your organization involved in your local heritage</li>
<li>to learn about archaeological resources for your job or volunteer position</li>
</ul>
<p>We can help out!
<br />
<br/>
Some of our programs are free of charge, while others have a small registration fee to help cover the cost of materials and activities. Click on the links below to learn more about FPAN's Training Programs.
</p>
<p class="center"><img src="images/programsMontage.jpg" class="padded" alt="Training Programs" /></p>
<p>If you don't see the program you're interested in scheduled in your area, <a href="http://www.flpublicarchaeology.org/regions.php">contact your local FPAN office</a> and request it! All FPAN Regions can offer these programs, but usually need <strong>5-10</strong> people (depending on the program) to make a class. </p>
<hr/>
<p><strong><a href="teacherInService.php">Archaeology in the Classroom Teacher In-Service Workshop</a></strong><br />
Use the lure of the past to engage students in math, science, language arts, fine arts, and critical thinking! </p>
<p><strong><a href="projectArchaeology.php">Project Archaeology: Investigating Shelter</a></strong> is a supplementary science and social studies curriculum unit for grades 3 through 5. This workshop aims to familiarize educators with archaeology resources for the classroom that enhance learning opportunities in math, science, art, and social studies. Workshop participants will receive archaeology education guides published byProject Archaeology that take students through scientific processes and an archaeological investigation of Kingsley Plantation, including accounts from oral history, use of primary documents, and interpreting the archaeological record.</p>
<p><strong><a href="CRPT.php">Cemetery Resource Protection Training (CRPT)</a></strong><br />
Join Florida Public Archaeology Network staff to learn about protecting human burial sites and preserving historic cemeteries. </p>
<p><strong><a href="humanRemains.php">Human Remains and the Law</a></strong><br />
Geared toward land mangers, this half-day workshop focuses on Florida and US laws regulating the discovery of human remains and the management of Native American remains within museum collections.</p>
<p><strong><a href="HADS.php">Heritage Awareness Diving Seminar (HADS)</a></strong><br />
The Heritage Awareness Diving Seminar provides scuba training agency Course Directors, Instructor Trainers, and Instructors with information and skills to proactively protect shipwrecks, artificial reefs, and other underwater cultural sites as part of the marine environment. Participants will be prepared to teach the new Heritage Awareness Diving Specialty through NAUI, PADI, and SDI. <br />
<em>*Taught in partnership with the Florida Bureau of Archaeological Research. </em></p>
<p><strong><a href="SSEAS.php">Submerged Sites Education and Archaeological Stewardship (SSEAS)</a></strong><br />
This program is intended to train sport divers in the methods of non-disturbance archaeological recording and then give these trained divers a mission! </p>
<p><strong><a href="parkRanger.php">Park Ranger Workshop</a></strong><br />
This one-day training is designed to assist rangers and park personnel in the identification, protection, interpretation, and effective management of historical and archaeological resources. </p>
<p><strong><a href="forestResources.php">Forest Resources Environmental Policy Special Sites Workshop</a></strong><br />
This one-day workshop helps forestry professionals to identify, manage, and protect "special sites" such as historical and archaeological resources they are likely to encounter in the course of their work, including Native American sites, cemeteries, industrial sites, and sites submerged in rivers and streams. </p>
<p><strong><a href="HART.php">Historical & Archaeological Resources Training (HART)</a></strong><br />
Designed for county and municipal governmental administrators, land managers, and planners, this one-day seminar describes how best to manage historical and archaeological resources and methods for promoting these resources for the benefit of their communities.<br />
<em>*Taught in partnership with the Florida Bureau of Archaeological Research. </em></p>
<p> </p> </td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?><file_sep><?php
$pageTitle = "Programs";
include 'header.php';
?>
<!-- Main Middle -->
<script type="text/javascript">
showElement('projects_sub');
</script>
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Upcoming Programs</h1></th>
</tr>
<tr>
<td class="table_mid">
<p>
<h2 >Timucuan Technology Workshops</h2>
</p>
<p align="center">
<a href="documents/TimutechFlier1.pdf"><img src="images/TimuTechFlier1.png" alt="" /></a>
<br/><br/>
<a href="documents/TimuTechRegForm.docx">Timucuan Technology Registration Form </a>
</p>
<br/>
<p align="center">
<a href="documents/TimutechFlier2.pdf"><img src="images/TimuTechFlier2.png" alt="" />
</a>
</p>
<hr/>
<h2>Cemetery Resource Protection Training<br />
</h2>
<p align="center"><a href="documents/CRPTflier.pdf"><img src="images/CRPTflier.png" /><br/><br/>
<a href="documents/CRPT_deland_registration.docx"><strong>CRPT Registration Form</strong></a></p>
<!---
<hr/>
<h2 align="center"><br />
Become a Certified Interpretive Guide!</h2>
<p align="center"><a href="images/NAI_flier.png"><img src="images/NAI_flier_sm.png" class="padded" /></a></p>
<p align="center">
<a href="documents/RegistrationFormNAI.pdf"> NAI Training Registration Form </a>
</p>
<br/>
<hr/>
--->
<!---
<p align="center"><a href="documents/Advocacy_Workshop_flier.pdf" target="_blank"><img src="images/advocacy_workshop_flier.png" /></a></p>
<p>
In response to recent events impacting local heritage sites, we invite the public to join us as we discuss archaeology beyond artifacts, legal issues to consider when people dig, ethical considerations of residents and professionals, and the emotional attachments that exist between a community and the place they live. We will brainstorm short-term and long-term solutions to current events, evaluating the affordances and constraints of various actions.
The goal of the offering is to provide resources for residents considering taking on a more active role in archaeological current events and inform an advocate's decision making processes.
<br />
</p>
<hr/>
--->
<p align="center"> </p>
<h2 align="left">Additional Programming</h2>
<p align="left">Still want more? Check out our <a href="http://storify.com/FPANNortheast"><strong>Storify</strong></a> and <a href="http://fpannortheast.tumblr.com/"><strong>Tumblr</strong></a> pages!</p>
<p>For more local archaeology news, sign up for our latest <a href="http://flpublicarchaeology.org/newsletter/northeast/user/subscribe.php"><strong>newsletter</strong></a>!</p></td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
$pageTitle = "Home";
include 'dbConnect.php';
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<td class="lg_mid" style="vertical-align:top">
<h1 align="center"> Florida Archaeology Month 2012</h1>
<br/>
<div align="center"><img src="images/hrLine.png"/></div>
<br />
<p><strong>Florida's diverse history and prehistory stretches back over 12,000 years.</strong> Every March, statewide programs and events celebrating Florida Archaeology Month are designed to encourage Floridians and visitors to learn more about the archaeology and history of the state, and to preserve these important parts of Florida's rich cultural heritage. Plan to attend some of the many events throughout Florida during March 2012. A full listing of events can be found on the events page linked at the top of the page.</p>
<p align="center"><strong>Download the 2012 Archaeology Month Poster</strong><br />
<a href="posterArchives/2012-poster-front.jpg">2012 FAM Poster - Front</a><br/>
<a href="posterArchives/2012-poster-back.jpg">2012 FAM Poster - Back</a></p>
<p><strong>Florida Archaeology Month 2012</strong> explores how archaeology contributes to our understanding of the Civil War. Information about local events can be found on the Florida Anthropological Society (FAS) Website, and on local FAS chapter Websites that can be accessed from the main <a href="http://www.fasweb.org/index.html" target="_blank">FAS Webpage</a></p>
<p><strong>Florida Archaeology Month</strong> is coordinated by the Florida Anthropological Society, and supported by the Department of State, Division of Historical Resources. Additional sponsors for 2012 include the Florida Archaeological Council, Florida Public Archaeology Network, state and local museums, historical commissions, libraries, and public and private school systems. The 2012 poster and bookmarks are available through the local <a href="links.php#chapters">Florida Anthropological Society Chapters</a> and can also be acquired at the Florida Public Archaeology Network's <a href="http://flpublicarchaeology.org/darc.php">Destination Archaeology Resource Center</a> museum.</p>
<br/>
<div align="center"><img src="images/hrLine.png"/></div>
<p>
<a href="http://flpublicarchaeology.org/DCWApp">
<img src="images/DCW_screens_sm.png" align="left" style="padding:5px;" />
</a>
<br/><br/>Download the <a href="http://flpublicarchaeology.org/DCWApp">Destination: Civil War iPhone app</a> to learn more about Civil War sites in Florida! <a href="http://flpublicarchaeology.org/civilwar">Destination: Civil War</a> is a guide to public places in Florida that tell the story of the Civil War and the movement to preserve its lessons. Many are significant archaeological sites, all are worthy of a visit and respectful reflection. </p>
<p> </p>
</td>
</tr>
</table>
<? include 'calendar.php'; ?>
<? include 'eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include 'footer.php'; ?><file_sep><?php
session_start();
if(!isset($_SESSION['email']))
header("location:index.php?loggedIn=no");
//Connect to database
$link = mysql_connect('fpanweb.powwebmysql.com', 'fam_user', ')OKM9ijn');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(fam_events);
//Global Variables
$pageTitle = "Admin Interface";
$table = "events";
$header = "../header.php";
$footer = "../footer.php";
$calPage = "eventList.php";
//Check to see if form field is blank throw error if it is
function check_input($field,$msg){
$field = trim($field);
$field = stripslashes($field);
$field = htmlspecialchars($field);
global $page;
if(empty($field))
event_error($msg,$page);
}
//Check date for mm/dd/yyyy format
function check_date($date){
global $page;
$regex = "'(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](20)\d\d'";
$msg = "Please enter a valid date.<br/>Must use mm/dd/yyyy format.";
check_input($date,"Date must not be blank.");
if(!preg_match($regex,$date))
event_error($msg,$page);
}
//Check time for hh:mm format
function check_time($time){
global $page;
//$regex = "/^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/";
//$regex = '([0-1][0-9]|[2][0-3]):([0-5][0-9])$';
// HH:MM format, leading zeroes optional
$regex = "/^([0]?[1-9]|1[0-2]):([0-5][0-9])$/";
$msg = "Please enter a valid time.<br/>Must use hh:mm format.";
if(!preg_match($regex,$time))
event_error($msg,$page);
}
//Format a phone number
function formatPhone($num){
$num = preg_replace('/[^0-9]/', '', $num);
$len = strlen($num);
if($len == 7)
$num = preg_replace('/([0-9]{3})([0-9]{4})/', '$1-$2', $num);
elseif($len == 10)
$num = preg_replace('/([0-9]{3})([0-9]{3})([0-9]{4})/', '($1) $2-$3', $num);
return $num;
}
//Redirect and display error message
function event_error($msg,$page){
global $eventID;
$redirect = "location:$page?msg=$msg&err=true";
if($eventID)
$redirect .= "&eventID=$eventID";
header($redirect);
die();
}
?><file_sep><?php
$pageTitle = "Then and Now: Life Along the New River";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Then and Now: Life Along the New River</h1></th>
</tr>
<tr>
<td class="table_mid">
<div id="exhibit">
<?php include 'nav.php'?>
<h2 align="center">Boating </h2>
<p>
<img src="images/exhibit5.jpg" alt="A Seminole Indian man poling a dugout canoe down the New River.<br/>Image courtesy of Fort Lauderdale Historical Society." style="float:right; margin-left:10px" class="" /></p>
<p>
<strong>From prehistory to today</strong>, dugout canoes, skiffs, tour boats, and paddleboards have floated down the New River as vehicles for hunting, transportation, and recreation. In prehistoric times, the Tequesta Indians used dugout canoes to travel the local waterways. The canoes were made by burning out the center of pine logs and scraping away the charred wood with shell axes and adzes. The oldest dugout canoe found in Florida was made over 5000 years ago. </p>
<p>Thousands of years later, the Seminole Indians made dugout canoes from cypress logs. The Seminole canoes were used for hunting and fishing and to facilitate trade relations with the white settlers that had moved to the area in the late 1800s. </p>
<p>
<img src="images/exhibit6.jpg" alt="Visitors aboard Vreeland's Glass Bottom Boat in the 1920's.<br/>Image courtesy of Broward County Historical Commission" style="float:left; margin-right:10px;" class=""/>
<strong>Tour boats take over</strong> the New River as visitation grows in the 20th century. The Abeona, owned by <NAME>, was one of the first tour boats to cater specifically to tourists. His trips proved so popular, that in the 1935 tourist season his vessel carried over 2,500 passengers! <br/>
More than a dozen different vessels, including the Abeona and Jungle Queen, would take sightseers on a circular route that ran up the New River, down the Dania Canal and north along the Inter-Coastal Waterway. Seminole tourist villages entertained visitors with alligator wrestling, photo opportunities, and craft sales. Seminole families would move to these camps during tourist season to make a living. <br />
<br />
<img src="images/exhibit7.jpg" alt="In this 1948 post card, tourists watch as a Seminole man holds open
an alligator's jaws.<br/>Image courtesy of Ah-Tah-Thi-Ki Museum" style="float:right;" class="" /><br/>
Today, tour boats glide past multi-million dollar yachts, raucous bars and fine restaurants. <strong>The boat styles may have changed, but entertainment and natural beauty continues to draw people to the river.</strong><br /><br/>
<span style="font-size:10px;">Contributions to the text by <NAME>, Broward County Historical Commission Curator</span></p>
</div>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?>
<file_sep><?php
$regionsArray = array("nwrc", "nerc", "ncrc", "wcrc", "crc", "ecrc", "serc", "swrc");
//
//********* Yay for functions **********//
// Look at current URI and determine if home (not region) page.
function isHomePage(){
global $regionsArray;
$isHomePage = true;
foreach($regionsArray as $regionAbbrev){
if(strpos($_SERVER['REQUEST_URI'], $regionAbbrev))
$isHomePage = false;
}
return $isHomePage;
}
//Display FPAN logo on main site
function echoImageBranding(){
if(isHomePage())
echo '<a class="navbar-brand-logo hidden-xs" href="/index.php"><img src="/images/FPAN_logo_white.svg" class="brand-logo"/></a>';
}
//Disoplay spacer li on screen sizes with image branding
function echoBrandingSpacer(){
if(isHomePage())
echo '<li><span class="brand-spacer hidden-xs hidden-lg"></span></li>';
}
//Echo 'active' for class is $requestUri is current page
function activeClassIfMatches($requestUri) {
if(stristr($_SERVER['REQUEST_URI'], $requestUri) )
echo 'active';
}
//Convert region abreviation to CSS shortened version
function getRegionCSS($region){
$regionCSS=str_replace('rc', '', $region);
return $regionCSS;
} //end function
//Convert and return full region name from abbreviation
function getRegionName($region){
switch($region){
case "nwrc":
$regionName = "Northwest";
break;
case "ncrc":
$regionName = "North Central";
break;
case "nerc":
$regionName = "Northeast";
break;
case "crc":
$regionName = "Central";
break;
case "wcrc":
$regionName = "West Central";
break;
case "ecrc":
$regionName = "East Central";
break;
case "serc":
$regionName = "Southeast";
break;
case "swrc":
$regionName = "Southwest";
break;
default:
break;
}
return $regionName;
} //end function
// List upcoming events summaries from regions listed in $regions[] up to $numEvents
// For 'Upcoming Events' boxes
function echoUpcomingEventsBox($regions, $numEvents = 5){
global $dblink;
if(count($regions) > 1){
$sql = "SELECT * FROM nwrc WHERE nwrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM nerc WHERE nerc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM ncrc WHERE ncrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM wcrc WHERE wcrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM crc WHERE crc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM ecrc WHERE ecrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM serc WHERE serc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM swrc WHERE swrc.eventDateTimeStart >= CURDATE()
ORDER BY eventDateTimeStart ASC;";
}else{
$sql = "SELECT * FROM $regions[0] WHERE $regions[0].eventDateTimeStart >= CURDATE() ORDER BY eventDateTimeStart ASC";
}
$upcomingEvents = mysqli_query($dblink, $sql);
if(mysqli_num_rows($upcomingEvents) != 0){
echo "<ul>";
while(($event = mysqli_fetch_array($upcomingEvents)) && ($numEvents > 0)){
$timestampStart = strtotime($event['eventDateTimeStart']);
$eventDate = date('M, j', $timestampStart);
$linkDate = date('m/d/Y', $timestampStart);
$eventTimeStart = date('g:i a', $timestampStart);
echo "<li><strong>".$eventDate." <span class=\"event-separator\">@</span> "."".$eventTimeStart."</strong> ";
if(count($regions) > 1){
echo "in <a href=".$event['region']." class=\"btn ".getRegionCSS($event['region'])."-btn events-btn\">".getRegionName($event['region']). "</a> <br/>";
echo "<a href=\"".$event['region']."/eventDetail.php?eventID=$event[eventID]&eventDate=$linkDate\">".stripslashes($event['title'])."</a></li>";
}else{
echo "<a href=\"eventDetail.php?eventID=$event[eventID]&eventDate=$linkDate\">".stripslashes($event['title'])."</a></li>";
}
$numEvents--;
}
echo "</ul>";
}else
echo '<p style="font-size:12px;" align="center">No events currently scheduled. <br/> Check back soon!</p>';
} //end function
?><file_sep><?php
include 'appHeader.php';
include $header;
//If eventDate is define in URL, show only events for that day
$allEvents = true;
$listEvents = mysql_query($sql);
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header">
<h1>Events Archive</h1>
</th>
</tr>
<tr>
<td class="table_mid">
<div align="center" style="margin-left:30px; margin-right:30px; font-size:11px;">
All past events are displayed here and will remain on the calendar. Past events will not be visible on the "Upcoming Events" page. <br/>
</div>
<?php
//display message or error if any
if($err)
$color = "red";
if($msg)
echo "<p align=\"center\" style=\"color:$color;\" class=\"msg\"> $msg </p>";
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM $table
WHERE eventDateTimeStart <= CURDATE()";
$result = mysql_query($sql, $link);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 8;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT * FROM $table
WHERE eventDateTimeStart <= CURDATE()
ORDER BY eventDateTimeStart DESC
LIMIT $offset, $rowsperpage";
$listEvents = mysql_query($sql, $link);
if(mysql_num_rows($listEvents) != 0){
while($event = mysql_fetch_array($listEvents)){
$timestampStart = strtotime($event['eventDateTimeStart']);
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventDate = date('F j', $timestampStart);
$eventTimeStart = date('g:i a', $timestampStart);
$eventTimeEnd = date('g:i a', $timestampEnd);
// echo "<tr><td colspan=\"2\"><hr/></td></tr>";
echo '<table width="100%">';
echo "<tr><td valign=\"top\"><h5 style=\"margin-left:20px; margin-top:10px;\">";
echo "<a href=\"eventEdit.php?eventID=" . $event['eventID'] . "\">Edit</a><br/>";
echo "<a href=\"eventEdit.php?eventID=" . $event['eventID'] . "&dupe=true\">Duplicate</a><br/>";
echo "<a href=\"processEdit.php?eventID=" . $event['eventID'] . "&del=true&archived=true\"";
echo "onclick=\"return confirm('Are you sure you want to delete this event?');\">Delete</a></h5></td>";
echo "<td><p><strong>" . $eventDate . " @ " . $eventTimeStart . " til " . $eventTimeEnd . "</strong><br/>";
echo stripslashes($event['title']) . "</p></td></tr>";
echo '</table>';
echo '<hr/>';
}
}else
echo '<p align="center">No events are currently in the archive.</p>';
// end while
echo "<h4 align=\"center\">";
/****** build the pagination links ******/
// range of num links to show
$range = 1;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a>";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo "[<b>$x</b>]";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
echo "</h4>";
?>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include 'adminBox.php'; ?><br />
<?php include '../events/calendar.php'; ?>
</div>
</div>
<!-- End Main div -->
<div class="clearFloat"></div>
<?php include $footer ?><file_sep><?php
$pageTitle = "Erorr 404";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1>Error 404</h1>
</div>
<div class="col-sm-8 col-sm-push-2 box-dash">
<p>Sorry, that page could not be found.</p>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
include 'appHeader.php';
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed
if(!in_array($ext,$allowed_filetypes)){
$msg = 'File type '.$ext.' is not allowed.';
$err = true;
}
// Check the filesize, if it is too large
elseif(filesize($_FILES['userfile']['tmp_name']) > $max_filesize){
$msg = 'The file you attempted to upload is too large.';
$err = true;
}
// Check if we can upload to the specified path
elseif(!is_writable($uploadDirectory)){
$msg = 'You cannot upload to the specified directory.';
$err = true;
}
// Upload the file to your specified path.
else{
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadDirectory . $filename))
$msg = $filename ." was uploaded successfully."; // It worked.
else{
$msg = 'There was an error during the file upload.'; // It failed :(.
$err = true;
}
}
header("Location: upload.php?msg=$msg&err=$err");
?>
<file_sep><?php
include 'appHeader.php';
include $header;
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1>Admin Overview</h1>
</div>
<div class="col-sm-7 col-lg-6 col-lg-offset-1">
<div class="box box-tab">
<p>Welcome to the admin section, See an explanation of options below. Any login prompts will use the same username and password as this admin page.</p>
<ul>
<li><strong>Events</strong><br/>
<ul>
<li><strong>Add</strong> - Add a new event from a blank form.<br/></li>
<li><strong>View/Edit</strong> - See a list of all current and upcoming events in the system. Edit or delete an event from this list.</li>
<li><strong>Archive</strong> - See a list of all past events in the system. Edit, duplicate or delete an event from this list.</li>
</ul>
</li>
<li><strong>Upload</strong> - Use this option for newsletter or event listing purpose only. See files that have been uploaded, upload new files or delete unwanted files. </li>
<li><strong>File Sharing (FTP site) - </strong>Upload or download files from the shared FPAN file server.</li>
<li><strong>Newsletter</strong> - Takes you to the poMMo newsletter management interface. </li>
<li><strong>Gallery</strong> - Add albums or individual photos to your site's photo gallery through this interface.</li>
<li><strong>Logout</strong> - Log out of this account. </li>
</ul>
</div>
</div><!-- ./col -->
<div class="col-sm-5 col-lg-4">
<?php include '../events/calendar.php'; ?>
</div> <!-- ./col -->
</div><!-- ./row -->
</div><!-- ./container -->
<?php include $footer; ?><file_sep><?php
$pageTitle = "Home";
include 'dbConnect.php';
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<td class="lg_mid" style="vertical-align:top">
<h1 align="center"> Florida Archaeology Month</h1>
<h2 align="center"> Poster Archives </h2>
<p align="center">
<strong> View Posters from: </strong> <br/>
<ul>
<li> 2013 | <a href="posterArchives/2013-poster-front.jpg">Front</a> -
<a href="posterArchives/2013-poster-back.jpg">Back</a>
</li>
<li> 2012 | <a href="posterArchives/2012-poster-front.jpg">Front</a> -
<a href="posterArchives/2012-poster-back.jpg">Back</a>
</li>
<li> 2011 | <a href="posterArchives/2011-poster-front.jpg">Front</a> -
<a href="posterArchives/2011-poster-back.jpg">Back</a>
</li>
<li> 2010 | <a href="posterArchives/2010-poster-front.jpg">Front</a>
- <a href="posterArchives/2010-poster-back.jpg">Back</a>
</li>
<li> 2009 | <a href="posterArchives/2009-poster-front.jpg">Front</a>
- <a href="posterArchives/2009-poster-back.jpg">Back</a>
</li>
<li> 2007 | <a href="posterArchives/2007-poster-front.jpg">Front</a>
- <a href="posterArchives/2007-poster-back.jpg">Back</a>
</li>
</ul>
</p>
</td>
</tr>
</table>
<? include 'calendar.php'; ?>
<? include 'eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include 'footer.php'; ?><file_sep><?php
$pageTitle = "Contact";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-6 col-sm-push-3">
<h3>Address</h3>
<p class="text-center">
74 King Street<br/> St. Augustine, FL 32085-1027
</p>
</div>
</div>
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/kevin.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Public Archaeology Coordinator</em><br/>
(904) 392-8065<br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('kevin_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="kevin_bio" class="hidden bio">
</div>
</div><!-- /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
/**
* This plugin deals with functions have been removed from mainstream Zenphoto as they have been
* supplanted.
* They are not maintained and they are not guaranteed to function correctly with the
* current version of Zenphoto.
*
* The actual set of functions resides in a <var>deprecated-functions.php</var> script within
* the plugins folder. (General deprecated functions are in the %PLUGIN_FOLDER%/deprecated-functins folder)
*
* Convention is that the deprecated functions script will have a class defined for containing the following:
*
* <ul>
* <li>general functions with parameters which have been deprecated: these are declared <var>public static</var></li>
* <li>class methods that have been deprecated: these are declared <var>static</var></li>
* <li>clas methods with parameters which have been deprecated: these are declared <var>final static</var></li>
* </ul>
*
* The default settings cause an <var>E_USER_NOTICE</var> error to be generated when the function is used.
* The text of the error message will tell you how to replace calls on the deprecated function. The error
* message can be disabled to allow your scripts to continue to run. Visit the <i>deprecated-functions</i>
* plugin options. Find the function and uncheck the box by the function.
*
* A utility button is provided that allows you to search themes and plugins for uses of functions which have been deprecated.
* Use it to be proactive in replacing these discontinued items.
*
* @author <NAME> (sbillard)
* @package plugins
* @subpackage development
*/
$plugin_description = gettext("Provides deprecated Zenphoto functions.");
$plugin_notice = gettext("This plugin is <strong>NOT</strong> required for the Zenphoto distributed functions.");
$option_interface = 'deprecated_functions';
$plugin_is_filter = 900 | CLASS_PLUGIN;
if (OFFSET_PATH == 2)
enableExtension('deprecated-functions', $plugin_is_filter); // Yes, I know some people will be annoyed that this keeps coming back,
// but each release may deprecated new functions which would then just give
// (perhaps unseen) errors. Better the user should disable this once he knows
// his site is working.
zp_register_filter('admin_utilities_buttons', 'deprecated_functions::button');
zp_register_filter('admin_tabs', 'deprecated_functions::tabs');
class deprecated_functions {
var $listed_functions = array();
var $unique_functions = array();
function __construct() {
global $_internalFunctions;
foreach (getPluginFiles('*.php') as $extension => $plugin) {
$deprecated = stripSuffix($plugin) . '/deprecated-functions.php';
if (file_exists($deprecated)) {
$plugin = basename(dirname($deprecated));
$content = file_get_contents($deprecated);
preg_match_all('~@deprecated\s+.*since\s+.*(\d+\.\d+\.\d+)~', $content, $versions);
preg_match_all('/([public static|static]*)\s*function\s+(.*)\s?\(.*\)\s?\{/', $content, $functions);
if ($plugin == 'deprecated-functions') {
$plugin = 'core';
$suffix = '';
} else {
$suffix = ' (' . $plugin . ')';
}
foreach ($functions[2] as $key => $function) {
if ($functions[1][$key]) {
$flag = '_method';
$star = '*';
} else {
$star = $flag = '';
}
$name = $function . $star . $suffix;
$option = 'deprecated_' . $plugin . '_' . $function . $flag;
setOptionDefault($option, 1);
$this->unique_functions[strtolower($function)] = $this->listed_functions[$name] = array(
'plugin' => $plugin,
'function' => $function,
'class' => trim($functions[1][$key]),
'since' => @$versions[1][$key],
'option' => $option,
'multiple' => array_key_exists($function, $this->unique_functions));
}
}
}
}
function getOptionsSupported() {
$options = $deorecated = $list = array();
foreach ($this->listed_functions as $funct => $details) {
$list[$funct] = $details['option'];
}
$options[gettext('Functions')] = array('key' => 'deprecated_Function_list', 'type' => OPTION_TYPE_CHECKBOX_UL,
'checkboxes' => $list,
'order' => 1,
'desc' => gettext('Send the <em>deprecated</em> notification message if the function name is checked. Un-checking these boxes will allow you to continue using your theme without warnings while you upgrade its implementation. Functions flagged with an asterisk are class methods. Ones flagged with two asterisks have deprecated parameters.'));
return $options;
}
static function tabs($tabs) {
if (zp_loggedin(ADMIN_RIGHTS)) {
if (!isset($tabs['development'])) {
$tabs['development'] = array('text' => gettext("development"),
'subtabs' => NULL);
}
$tabs['development']['subtabs'][gettext("deprecated")] = PLUGIN_FOLDER . '/deprecated-functions/admin_tab.php?page=deprecated&tab=' . gettext('deprecated');
$named = array_flip($tabs['development']['subtabs']);
natcasesort($named);
$tabs['development']['subtabs'] = $named = array_flip($named);
$tabs['development']['link'] = array_shift($named);
}
return $tabs;
}
/*
* used to provided deprecated function notification.
*/
static function notify($use) {
$traces = @debug_backtrace();
$fcn = $traces[1]['function'];
if (empty($fcn))
$fcn = gettext('function');
if (!empty($use))
$use = ' ' . $use;
//get the container folder
if (isset($traces[0]['file']) && isset($traces[0]['line'])) {
$script = basename(dirname($traces[0]['file']));
} else {
$script = 'unknown';
}
if ($script == 'deprecated-functions') {
$plugin = 'core';
} else {
$plugin = $script;
}
if (isset($traces[1]['file']) && isset($traces[1]['line'])) {
$script = basename($traces[1]['file']);
$line = $traces[1]['line'];
} else {
$script = $line = gettext('unknown');
}
if (@$traces[1]['class']) {
$flag = '_method';
} else {
$flag = '';
}
$option = 'deprecated_' . $plugin . '_' . $fcn . $flag;
if (($fcn == 'function') || getOption($option)) {
trigger_error(sprintf(gettext('%1$s (called from %2$s line %3$s) is deprecated'), $fcn, $script, $line) . $use . ' ' . sprintf(gettext('You can disable this error message by going to the <em>deprecated-functions</em> plugin options and un-checking <strong>%s</strong> in the list of functions.' . '<br />'), $fcn), E_USER_WARNING);
}
}
static function button($buttons) {
$buttons[] = array(
'category' => gettext('Development'),
'enable' => true,
'button_text' => gettext('Check deprecated use'),
'formname' => 'deprecated_functions_check.php',
'action' => WEBPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/deprecated-functions/check_for_deprecated.php',
'icon' => 'images/magnify.png',
'title' => gettext("Searches PHP scripts for use of deprecated functions."),
'alt' => gettext('Check for update'),
'hidden' => '',
'rights' => ADMIN_RIGHTS
);
return $buttons;
}
static function addPluginScript() {
global $_zp_plugin_scripts;
if (is_array($_zp_plugin_scripts)) {
foreach ($_zp_plugin_scripts as $script) {
echo $script . "\n";
}
}
}
}
//Load the deprecated function scripts
require_once(stripSuffix(__FILE__) . '/deprecated-functions.php');
foreach (getPluginFiles('*.php') as $extension => $plugin) {
$deprecated = stripSuffix($plugin) . '/deprecated-functions.php';
if (file_exists($deprecated)) {
require_once($deprecated);
}
unset($deprecated);
}
?>
<file_sep><?php
include 'header.php';
$activityArray = array();
$typeActivity = $_GET['typeActivity'];
$activityID = $_GET['id'];
$title = getTitle($typeActivity);
$page = getPage($typeActivity);
//Delete event
if($_GET['submit'] == 'Delete'){
$sql = "DELETE FROM $typeActivity WHERE id = $activityID; ";
mysql_query($sql) ? $err = false : $err = true;
$sql = "DELETE FROM EmployeeActivity WHERE activityID = $activityID; ";
mysql_query($sql) ? $err = false : $err = true;
$sql = "DELETE FROM Activity WHERE id = $activityID; ";
mysql_query($sql) ? $err = false : $err = true;
if(!$err)
$msg = "Event was successfully deleted!";
else
$msg = "Error: Event was unable to be deleted.";
echo "<div class=\"summary\">";
echo "<br/><br/><h3>".$msg."</h3><br/><br/><br/><br/>";
echo "<a href=\"viewTypeActivities.php?typeActivity=$typeActivity\">View other ".$title." activities</a>";
echo " or <a href=\"main.php\">return to main menu</a>. <br/><br/>";
echo "</div>";
}else{
?>
<table border="0" cellspacing="2" align="center" class="displayActivity">
<tr>
<td valign="top">
<h2 align="center"><?php echo $title; ?></h2>
<hr/>
<?php
$thisActivityArray = getActivity($typeActivity, $activityID);
printActivity($thisActivityArray);
//Only show edit/delete options for authorized users
if(canEdit()){
?>
<div align="center">
<form method="get" action="<?php echo $page; ?>">
<input type="hidden" name="id" value="<?php echo $activityID; ?>" />
<input type="submit" name="submit" value="Edit" />
</form>
<form method="get" action="<?php curPageUrl(); ?>" onsubmit="return confirm('Are you SURE you wish to delete this?');">
<input type="hidden" name="id" value="<?php echo $activityID; ?>" />
<input type="hidden" name="typeActivity" value="<?php echo $typeActivity; ?>" />
<input type="submit" name="submit" value="Delete" />
</form>
</div>
<?php
}//end canEdit if
} //endif ?>
</td>
</tr>
</table>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "Home";
$bg = array('jumbotron.jpg','jumbotron2.jpg','jumbotron3.jpg','jumbotron4.jpg'); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
include('_header.php');
require_once("../rss/rsslib.php");
$url = "http://www.flpublicarchaeology.org/blog/wcrc/feed";
?>
<!-- page-content begins -->
<div class="page-content container">
<!-- Row One -->
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="col-sm-12">
<div class="jumbotron hidden-xs" style="background: url(images/<?php echo $selectedBg; ?>) 40% no-repeat; background-position:left;"> </div>
</div>
<div class="col-md-7">
<h2><small>Latest from the</small> Blog</h2>
<div class="box-tab">
<?php echo RSS_Links($url, 2); ?>
</div>
<div class="box-dash">
<p>The <span class="h4">West Central</span> Region is located in Tampa, hosted by the University of South Florida and serves Desoto, Hardee, Highlands, Hillsborough, Manatee, Pasco, Pinellas, Polk and Sarasota counties. Click on the county to see some of the sites that are open and interpreted for the public.</p>
<!-- Interactive SVG Map -->
<div class="center-block hidden-xs" id="wcmap"></div>
<img class="img-responsive visible-xs" src="images/wc_counties_map.svg" />
</div>
</div><!-- /.col -->
<div class="col-md-5">
<h2>Upcoming Events</h2>
<div class="box-tab events-box">
<!-- Non-mobile list (larger) -->
<div class="hidden-xs">
<?php
$regionArray = array($table);
echoUpcomingEventsBox($regionArray,5);
?>
</div>
<!-- Mobile events list -->
<div class="visible-xs">
<?php
$regionArray = array($table);
echoUpcomingEventsBox($regionArray,3);
?>
</div>
<p class="text-center">
<a class="btn btn-primary btn-sm" href="eventList.php">View more</a>
</p>
</div>
<h3>Newsletter <small>Signup</small></h3>
<form role="form" method="get" action="newsletter.php">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="email" placeholder="<EMAIL>">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div><!-- /.col -->
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div> <!-- /.col -->
</div><!-- /.row one -->
<div class="row">
<div class="col-md-6">
<div class="region-callout-box wc-volunteer">
<h1>Volunteer</h1>
<p>Opportunities to get your hands dirty.</p>
<a href="volunteer.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<div class="region-callout-box wc-explore">
<h1>Explore</h1>
<p>Discover historical and archaeological sites!</p>
<a href="explore.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<div class="region-callout-box wc-sseas">
<h1>SSEAS</h1>
<p>Divers making a difference</p>
<a href="../workshops/SSEAS.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<div class="region-callout-box wc-archworks">
<h1>Archaeology Works</h1>
<p>Hands-on archaeology for all.</p>
<a href="../workshops/archsworks.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div>
</div><!-- /.row two -->
</div><!-- /.page-content /.container-fluid -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#wcmap').mapSvg({
source: 'images/wc_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //North Central Region Marker
xy:[200,365],
tooltip:'West Central Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Pasco' :{popover:'<h3>Pasco</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=pasco"> Explore Pasco County</a></p>'},
'Hillsborough' :{popover:'<h3>Hillsborough</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=hillsborough"> Explore Hillsborough County</a></p>'},
'Pinellas' :{popover:'<h3>Pinellas</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=pinellas"> Explore Pinellas County</a></p>'},
'Manatee' :{popover:'<h3>Manatee</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=manatee"> Explore Manatee County</a></p>'},
'Sarasota' :{popover:'<h3>Sarasota</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=sarasota"> Explore Sarasota County</a></p>'},
'Polk' :{popover:'<h3>Polk</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=polk"> Explore Polk County</a></p>'},
'Hardee' :{popover:'<h3>Hardee</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=hardee"> Explore Hardee County</a></p>'},
'Highlands' :{popover:'<h3>Highlands</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=highlands"> Explore Highlands County</a></p>'},
'Desoto' :{popover:'<h3>Desoto</h3><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=desoto"> Explore Desoto County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Explore";
$county = isset($_GET['county']) ? $_GET['county'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<!-- ********* ****************** **************** -->
<!-- ********* Explore Charlotte County ********** -->
<!-- ********* ****************** **************** -->
<?php if($county == 'charlotte'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Charlotte<small> County</small></h1>
</div>
<!-- <div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
</div>
</div> -->
<div class="col-md-6">
<h2>County Offices & Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://charlottecountyfl.com/">Charlotte County Website</a></li>
<li><a target="_blank" href="http://www.charlotteharbortravel.com/">Charlotte Harbor Visitor & Convention Bureau</a></li>
<li><a target="_blank" href="http://www.ci.punta-gorda.fl.us/about/history.html">Punta Gorda Historic District</a></li>
<li><a target="_blank" href="http://puntagordahistory.com/">Punta Gorda Historical Society</a></li>
<li><a target="_blank" href="http://www.theculturalcenter.com/">The Cultural Center of Charlotte County</a></li>
</ul>
</div>
<h2>Museums, Cultural & Historic Centers</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.faahpn.com/faaphn/">Blanchard House Museum</a></li>
<li><a target="_blank" href="http://www.charlottecountyfl.com/Historical/">Charlotte County Historic Center</a></li>
<li><a target="_blank" href="http://www.mhaam.org/">The Military Heritage and Aviation Museum</a></li>
<li></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/charlotteharbor/default.cfm">Charlotte Harbor Preserve State Park</a></li>
</ul>
</div>
<h2>Cemeteries</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.rootsweb.com/~flcharlo/indhist.htm">Indian Springs Cemetery</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** ***************** -->
<!-- ********* Explore Collier County ************* -->
<!-- ********* ****************** ***************** -->
<?php }elseif($county == 'collier'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Collier<small> County</small></h1>
</div>
<!-- <div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
</div>
</div> -->
<div class="col-md-6">
<h2>County Offices & Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.colliergov.net/">Collier County Website</a></li>
<li><a target="_blank" href="http://www.paradisecoast.com/">Collier County Convention and Visitors Bureau</a></li>
<li><a target="_blank" href="http://www.napleshistoricalsociety.org/">Naples Historical Society</a></li>
<li><a target="_blank" href="http://www.themihs.org/">Marco Island Historical Society</a></li>
<li><a target="_blank" href="http://www.napleshistoricalsociety.org/">Naples Historic Society at Palm Cottage</a></li>
</ul>
</div>
<h2>Parks & Preserves</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.nps.gov/bicy/index.htm">Big Cypress National Preserve</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/collierseminole/default.cfm">Collier-Seminole State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.colliermuseums.com/locations/collier_museum.php">Collier County Museum</a></li>
<li><a target="_blank" href="http://www.colliermuseums.com/locations/immokalee.php">Immokalee Pioneer Museum at Roberts Ranch</a></li>
<li><a target="_blank" href="http://www.themihs.org/">Marco Island Historical Museum</a></li>
<li><a target="_blank" href="http://www.colliermuseums.com/locations/museum_everglades.php">Museum of the Everglades</a></li>
<li><a target="_blank" href="http://naplesbackyardhistory.net/">Naples Backyard History Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** **************** -->
<!-- ********* Explore Glades County ************* -->
<!-- ********* ****************** **************** -->
<?php }elseif($county == 'glades'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Glades<small> County</small></h1>
</div>
<!-- <div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
</div>
</div> -->
<div class="col-md-6">
<h2>County Offices & Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.myglades.com/">Glades County Website</a></li>
<li><a target="_blank" href="http://www.visitglades.com/wp/home/">Glades County Tourism Development Council</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Museums, Historic Sites & Other Resources</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.gatorama.com/">Gatorama</a></li>
<li><a target="_blank" href="http://www.visitglades.com/wp/fort-center/">Fort Center Archaeological Site</a></li>
<li><a target="_blank" href="http://www.visitglades.com/wp/downtown-moore-haven/">Moore Haven Downtown Historic District</a></li>
<li><a target="_blank" href="http://www.visitglades.com/wp/ortona-mounds/">Ortona Mounds</a></li>
<li><a target="_blank" href="http://www.visitglades.com/wp/ortona-cemetery/">Ortona Cemetery </a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** **************** -->
<!-- ********* Explore Hendry County ************* -->
<!-- ********* ****************** **************** -->
<?php }elseif($county == 'hendry'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Hendry<small> County</small></h1>
</div>
<!-- <div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
</div>
</div> -->
<div class="col-md-8 col-md-push-2">
<h2>County Offices & Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.hendryfla.net/">Hendry County Website</a></li>
<li><a target="_blank" href="http://www.visithendrycounty.com/">Hendry County Tourist Development Council</a></li>
</ul>
</div>
<h2>Museums & Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.citylabelle.com/downtownplan.html">LaBelle Historic District</a></li>
<li><a target="_blank" href="http://www.ahtahthiki.com/">Ah-Tah-Thi-Ki Museum</a></li>
<li><a target="_blank" href="http://www.waymarking.com/waymarks/WMCV1Q_DOWNTOWN_LABELLE_HISTORIC_DISTRICT_Labelle_FL">Labelle Heritage Museum Inc</a></li>
<li><a target="_blank" href="http://www.floridaforestservice.com/state_forests/okaloacoochee.html">Okaloacoochee Slough State Forest</a></li>
<li><a target="_blank" href="http://www.clewistonmuseum.org/">Clewiston Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Lee County *************** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'lee'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Lee<small> County</small></h1>
</div>
<!-- <div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
</div>
</div> -->
<div class="col-md-6">
<h2>County Offices & Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.lee-county.com/">Lee County</a></li>
<li><a target="_blank" href="http://www.fortmyers-sanibel.com/">Lee County Visitor & Convention Bureau</a></li>
<li><a target="_blank" href="http://www.leetrust.org/">Lee County Trust for Historic Preservation</a></li>
<li><a target="_blank" href="http://bonitaspringshistoricalsociety.org/">Bonita Springs Historical Society</a></li>
<li><a target="_blank" href="http://www.bocagrandehistoricalsociety.com/">Boca Grande Historical Society</a></li>
<li><a target="_blank" href="http://swflhistoricalsociety.com/">Southwest Florida Historical Society</a></li>
</ul>
</div>
<h2>Parks & Trails</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.flmnh.ufl.edu/rrc/calusatrail.htm">Calusa Heritage Trail</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/cayocosta/">Cayo Costa State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/moundkey/default.cfm">Mound Key Archaeological State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.alvafl.org/history_of_alva.htm">The Alva Historical Museum</a></li>
<li><a target="_blank" href="http://www.bocagrandehistoricalsociety.com/">The Boca Grande Historical Society & Museum</a></li>
<li><a target="_blank" href="http://www.capecoralhistoricalmuseum.org/">Cape Coral Historical Society Museum </a></li>
<li><a target="_blank" href="http://www.museumoftheislands.com/">Museum of the Islands</a></li>
<li><a target="_blank" href="http://www.bestofsanibelcaptiva.com/historic/museum.shtml">Sanibel Historical Village & Museum</a></li>
<li><a target="_blank" href="http://www.swflmuseumofhistory.com/">Southwest Florida Museum of History</a></li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.edisonfordwinterestates.org/">Edison-Ford Winter Estate</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/koreshan/">Koreshan State Historic Site</a></li>
<li><a target="_blank" href="http://www.bonitaspringshistoricalsociety.org/BSHS/Liles_Hotel_History_Center.html">Liles Hotel</a></li>
</ul>
</div>
</div><!-- /.col -->
<?php }else{ ?>
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-12 col-md-8 col-md-push-2">
<p>
The Northeast region offers many amazing historical and archaeological sites that you can visit. Click on any county below to discover sites in your area.
<hr/>
<!-- Interactive SVG Map -->
<div id="swmap" class="center-block"></div>
</p>
<!-- <hr/>
<div class="col-sm-12 text-center">
<div class="image"><img src="" alt="" class="img-responsive" width="400" height="464"></div>
</div> -->
</div>
</div><!-- /.row -->
<?php } ?>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#swmap').mapSvg({
source: 'images/sw_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //North Central Region Marker
xy:[200,365],
tooltip:'Southwest Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Charlotte' :{popover:'<h3>Charlotte</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=charlotte"> Explore Charlotte County</a></p>'},
'Glades' :{popover:'<h3>Glades</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=glades"> Explore Glades County</a></p>'},
'Hendry' :{popover:'<h3>Hendry</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=hendry"> Explore Hendry County</a></p>'},
'Lee' :{popover:'<h3>Lee</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=lee"> Explore Lee County</a></p>'},
'Collier' :{popover:'<h3>Collier</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=collier"> Explore Collier County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Workshops - HART";
include('../_header.php');
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1> Workshops, <small>HART</small></h1>
</div>
<div class="col-lg-8 col-lg-push-2 col-sm-10 col-sm-push-1 box-tab box-line row">
<div class="col-sm-12 text-center">
<div class="image">
<img class="img-responsive" src="images/HART.jpg">
</div>
</div>
<p>
Designed for county and municipal governmental administrators, land managers, and planners, this interesting and informative one-day seminar describes archaeological and historical resources, how best to manage these resources, and methods for promoting the resources for the benefit of counties, cities, and towns. Topics covered include:
</p>
<ul>
<li>cultural resource management</li>
<li>archaeological and historic preservation law</li>
<li>the role of the Florida Division of Historical Resources</li>
<li>DHR compliance review process</li>
<li>nominating sites to the National Register and designating as a State Archaeological Landmark</li>
<li>funding opportunities</li>
<li>incorporating and promoting public access to historic sites and structures</li>
<li>best management practices for cultural sites</li>
<li>economic impacts of historic preservation</li>
<li>local organizations that can assist you</li>
</ul>
<p><em>Taught in partnership with the Florida Bureau of Archaeological Research.</em></p>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
if (!defined('WEBPATH')) die();
require_once('normalizer.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="no" name="apple-mobile-web-app-capable" />
<!-- this will not work right now, links open safari -->
<meta name="format-detection" content="telephone=no">
<meta content="index,follow" name="robots" />
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type" />
<link href="<?php echo $_zp_themeroot ?>/images/homescreen.png" rel="apple-touch-icon" />
<meta content="minimum-scale=1.0, width=device-width, maximum-scale=0.6667, user-scalable=no" name="viewport" />
<link href="<?php echo $_zp_themeroot ?>/css/style.css" rel="stylesheet" type="text/css" />
<script src="<?php echo $_zp_themeroot ?>/javascript/functions.js" type="text/javascript"></script>
<script src="<?php echo $_zp_themeroot ?>/javascript/rotate.js" type="text/javascript"></script>
<title><?php echo getBareGalleryTitle(); ?></title>
<?php zp_apply_filter("theme_head"); ?>
<title><?php echo getBareGalleryTitle(); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php $archivepageURL = htmlspecialchars(getGalleryIndexURL()); ?>
<script type="application/x-javascript">
addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false);
function hideURLbar(){
window.scrollTo(0,1);
}
</script>
<?php
setOption("image_quality",1,false);
$quality = getOption('image_quality');
//$args = array($size, $width, $height, $cw, $ch, $cx, $cy, $newquality, $thumb, $crop, $thumbstandin, $thumbWM, $adminrequest, $gray);
?>
</head>
<body class="portrait">
<script type="text/javascript" language="JavaScript">
updateOrientation();
</script>
<div id="topbar">
<div id="title"><?php echo getBareGalleryTitle(); ?></div>
</div>
<div id="content">
<div class="graytitle"><?php //echo gettext('Recently Updated Galleries'); ?></div>
<p>
DESTINATION: CIVIL WAR is a listing of Civil War heritage sites that are open for the public to visit. View a map of all of these sites with <a href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=http:%2F%2Fwww.flpublicarchaeology.org%2Fcivilwar%2Fsites.kmz&sll=37.0625,-95.677068&sspn=58.72842,135.263672&ie=UTF8&t=h&ll=28.960089,-83.748779&spn=8.511294,16.907959&z=5" class="dark">Google Maps</a>
</p>
<div class="galleryalbum">
<ul class="autolist">
<?php
$count = 0;
while (next_album()):
?>
<li class="withimage">
<a href="<?php echo htmlspecialchars(getAlbumLinkURL());?>" class="img">
<?php printCustomAlbumThumbImage(getBareAlbumTitle(), null, 480, 120, 480, 120); ?>
<span class="folder_info">
<?php
$anumber = getNumAlbums() ;
$inumber = getNumImages();
if ($anumber > 0 || $inumber > 0) {
echo '<em>';
if ($anumber == 0) {
if ($inumber != 0) {
printf(ngettext('%u photo','%u photos', $inumber), $inumber);
}
} else if ($anumber == 1) {
if ($inumber > 0) {
printf(ngettext('1 album, %u photo','1 album, %u photos', $inumber), $inumber);
} else {
printf(gettext('1 album'));
}
} else {
if ($inumber == 1) {
printf(ngettext('%u album, 1 photo','%u albums, 1 photo', $anumber), $anumber);
} else if ($inumber > 0) {
printf(ngettext('%1$u album, %2$s','%1$u albums, %2$s', $anumber), $anumber, sprintf(ngettext('%u photo','%u photos',$inumber),$inumber));
} else {
printf(ngettext('%u album','%u albums', $anumber), $anumber);
}
}
echo '</em>';
}
?>
</span>
<span class="name"><?php echo getBareAlbumTitle();?></span>
<span class="arrow_img"></span>
</a>
</li>
<?php
//this will limit the amount of processing of for loading main page. goto archive (gallery.php) for all.
$count++;
if($count==6){
break;
}
endwhile;
?>
</ul>
</div>
<div id="footer"> </div>
</div>
</body>
</html>
<file_sep><?php
$pageTitle = "Explore";
$county = isset($_GET['county']) ? $_GET['county'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<!-- ********* ****************** *********** -->
<!-- ********* Explore Clay County ********** -->
<!-- ********* ****************** *********** -->
<?php if($county == 'clay'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Clay County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Nestled in the east bank of the St Johns River, Clay County is historically known for its therapeutic warm springs and mild climate. Clay County was developed in 1858, from Duval County land, and named after Kentucky Senator <NAME>. President <NAME> is one of many historic figures drawn to area during the 19th century.</p>
</div>
</div>
<div class="col-md-6">
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://archives.clayclerk.com/">Clay County Archives </a></li>
<li><a target="_blank" href="http://www.campblanding-museum.org/">Camp Blanding Museum</a> </li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li>
<a target="_blank" href="http://archives.clayclerk.com/MagnoliaSpringsCemetery.html">Magnolia Springs Cemetery</a>
</li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li>
<a target="_blank" href="http://www.floridastateparks.org/mikeroess/default.cfm"><NAME> Gold Head Branch State Park</a>
</li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Duval County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'duval'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Duval County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Duval County/City of Jacksonville contains more recorded historic resources than any other community in the state of Florida. With over 5500 historic and archaeological sites, there is something for everyone here!</p>
</div>
</div>
<div class="col-md-6">
<h2>Parks & Preserves</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.nps.gov/foca/index.htm">Timucuan Ecological and Historic Preserve</a></li>
<li><a target="_blank" href="http://www.nps.gov/timu/historyculture/kp.htm">Kingsley Plantation National Historic Site</a></li>
<li><a target="_blank" href="http://www.exploresouthernhistory.com/campmilton.html">Camp Milton</a></li>
<li><a target="_blank" href="http://www.nps.gov/timu/historyculture/foca.htm">Fort Caroline National Memorial</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.mandarinmuseum.net/">Mandarin Museum & Historical Society</a></li>
<li><a target="_blank" href="http://www.themosh.org/Home.html">Museum of Science and History</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Flagler County *********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'flagler'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Flagler County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Flagler County is the fastest growing county in Florida. Home to Marineland, Bulow Plantation State Historic Site, and the Florida Agricultural Museum, Flagler County hosts a myriad of intriguing cultural heritage sites and beautiful natural habitats for local flora and fauna.</p>
</div>
</div>
<div class="col-md-6">
<h2>Parks & Preserves</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.flaglercounty.org/facilities.aspx?page=detail&RID=18">Princess Place Preserve</a> </li>
<li><a target="_blank" href="http://www.floridastateparks.org/bulowplantation/">Bulow Plantation Ruins Historic Park </a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/washingtonoaks/">Washington Oaks Garden State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historical Sites & Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.visitflorida.com/articles/mala-compra-plantation-history-from-the-ground-up">Mala Compra Plantation</a></li>
<li><a target="_blank" href="http://www.flaglerbeachmuseum.com/">Flagler Beach Historical Museum </a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Nassau County ************ -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'nassau'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Nassau County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Nassau is the furthest northeast county in the region. Many of the archaeological resources are located along the coast and within the vicinity of the county seat, Fernandina Beach.</p>
</div>
</div>
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/fortclinch/">Ft. Clinch State Park </a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.ameliamuseum.org/">Amelia Island Museum of History</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.aigensoc.org/cemetery_Bosque_Bello_Old.asp">Bosque Bello Old Cemetery</a></li>
<li><a target="_blank" href="http://oldtownfernandina.org/">Old Town Fernandina </a></li>
<li><a target="_blank" href="http://www.aigensoc.org/cemetery_Kings_Ferry.asp">Kings Ferry Cemetery </a></li>
<li><a target="_blank" href="http://www.fbfl.us/index.aspx?NID=474"> Amelia Island Lighthouse </a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Putnam County ************ -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'putnam'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Putnam County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Putnam County spreads to either side of the St. Johns River, boasting scenic river views and lush undulating landscape around the its county seat of Palatka. Putnam County was named for <NAME>, first president of the Florida Historic Society and a veteran of the First Seminole War.</p>
</div>
</div>
<div class="col-md-6">
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://dhr.dos.state.fl.us/archaeology/projects/mountroyal/">Mt. Royal</a></li>
<li><a target="_blank" href="http://www.putnam-fl-historical-society.org/">Putnam County Historical Society</a></li>
<li><a target="_blank" href="http://bartram.putnam-fl.com/">Bartram Trail</a></li>
<li><a target="_blank" href="http://palatkawaterworks.com/">Palatka Water Works Environmental Education Center</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/ravinegardens/default.cfm">Ravine Gardens</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** **************** -->
<!-- ********* Explore St. Johns County ********** -->
<!-- ********* ****************** **************** -->
<?php }elseif($county == 'stjohns'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>St. Johns County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Established in 1821, St Johns County is one of Florida’s two original counties, alongside Escambia County. Most known for its coastal communities and its county seat St Augustine (the oldest city in the United States), the county offers an abundance of cultural and natural heritage sites for visitors. Beautiful rural and intercoastal vistas are also plentiful and worth visiting on your way to any of the sites throughout the county.</p>
</div>
</div>
<div class="col-md-6">
<h2>Historical Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.fountainofyouthflorida.com/">Fountain of Youth Archaeological Park</a></li>
<li><a target="_blank" href="http://www.staugustinehistoricalsociety.org/">The Oldest House</a></li>
<li><a target="_blank" href="http://www.missionandshrine.org/">Mission of Nombre de Dios and Shrine of Our Lady of La Leche</a></li>
<li><a target="_blank" href="http://www.stphotios.com/">St. Photios Greek Orthodox National Shrine</a></li>
<li><a target="_blank" href="http://www.ximenezfatiohouse.org/">Ximenez-Fatio House</a></li>
</ul>
</div>
<h2>Historic Sites & Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.gtmnerr.org/">GTM Research Reserve</a></li>
<li><a target="_blank" href="http://colonialquarter.com/">Colonial Quarter</a> </li>
<li><a target="_blank" href="http://www.staugustine.ufl.edu/govHouse.html">Government House</a> </li>
<li><a target="_blank" href="http://www.staugustinelighthouse.com/">St. Augustine Light House & Museum</a></li>
<li><a target="_blank" href="http://www.oreillyhouse.org/"><NAME>'Reilly House Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.nps.gov/casa">Castillo de San Marcos</a></li>
<li><a target="_blank" href="http://www.nps.gov/foma/">Fort Matanzas</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/fortmose/default.cfm">Fort Mose State Historical State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/anastasia">Anastasia State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Volusia County *********** -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'volusia'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Volusia County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Volusia County was developed in 1854 with a population of a mere 600 people. The county is named for the small river community of Volusia, an important military supply depot during the second Seminole War. The coastal county is now home to more than 400,000 people. With 47 miles of beachfront and destinations including Daytona Beach, Ormond Beach, and New Smyrna Beach, Volusia County is a popular vacation area. In addition to beach related attractions, Volusia County is perhaps most known for its sugar mill ruins; however, visitors should also consider the 19th and 20th century house museums, significant military sites, and prehistoric shell mound sites. (<a target="_blank" href="http://volusiahistory.com">http://volusiahistory.com</a>)</p>
</div>
</div>
<div class="col-md-6">
<h2>Parks & Preserves</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/hontoonisland/default.cfm">Hontoon Island State Park</a> </li>
<li><a target="_blank" href="http://www.floridastateparks.org/bluespring/">Blue Springs State Park</a> </li>
<li><a target="_blank" href="http://fpangoingpublic.blogspot.com/2011/03/hikers-and-bikers-oh-my-touring-spruce.html">Spruce Creek Preserve</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/tomoka/default.cfm">Tomoka State Park</a></li>
<li><a target="_blank" href="http://www.nps.gov/cana/index.htm">Canaveral National Seashore</a></li>
<li><a target="_blank" href="http://www.ponce-inlet.org/Pages/PonceInletFL_BComm/S022EE4F7-022EE4F9">Ponce Preserve</a> </li>
<li><a target="_blank" href="http://www.volusia.org/services/community-services/parks-recreation-and-culture/parks-and-trails/park-facilities-and-locations/historical-parks/sugar-mill-ruins.stml">Cruger de Peyster Sugar Mill Ruins</a> </li>
</ul>
</div>
<h2>Historic Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://ormondhistory.org/the-three-chimneys-sugar-works-site/">Three Chimneys Sugar Works Site</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.moas.org/main.cfm">Museum of Arts and Sciences</a></li>
<li><a target="_blank" href="http://www.nsbhistory.org/">New Smyrna Museum of History</a></li>
<li><a target="_blank" href="http://ponceinlet.org/">Ponce Inlet Lighthouse & Musem</a></li>
</ul>
</div>
<h2>Other Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.pioneersettlement.org/education.html">Pioneer Settlement</a></li>
</ul>
</div>
</div><!-- /.col -->
<?php }else{ ?>
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-12 col-md-8 col-md-push-2">
<p>
The Northeast region offers many amazing historical and archaeological sites that you can visit. Click on any county below to discover sites in your area.
<hr/>
<!-- Interactive SVG Map -->
<div id="nemap" class="center-block"></div>
</p>
<hr/>
<!-- <div class="col-sm-12 text-center">
<div class="image"><img src="" alt="" class="img-responsive" width="400" height="464"></div>
</div> -->
</div>
</div><!-- /.row -->
<?php } ?>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#nemap').mapSvg({
source: 'images/ne_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //North Central Region Marker
xy:[200,365],
tooltip:'Northeast Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Nassau' :{popover:'<h3>Nassau</h3><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=nassau"> Explore Nassau County</a></p>'},
'Duval' :{popover:'<h3>Duval</h3><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=duval"> Explore Duval County</a></p>'},
'Clay' :{popover:'<h3>Clay</h3><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=clay"> Explore Clay County</a></p>'},
'Putnam' :{popover:'<h3>Putnam</h3><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=putnam"> Explore Putnam County</a></p>'},
'St._Johns' :{popover:'<h3>St. Johns</h3><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=stjohns"> Explore St. Johns County</a></p>'},
'Flagler' :{popover:'<h3>Flagler</h3><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=flagler"> Explore Flagler County</a></p>'},
'Volusia' :{popover:'<h3>Volusia</h3><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=volusia"> Explore Volusia County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Event Details";
include('_header.php');
//Assign date from URL and apply SQL injection protection!
if(isset($_GET["eventDate"])){
$thisDate = $_GET["eventDate"];
$formatDate = new DateTime($thisDate);
$displayDate = $formatDate->format('l, M j, Y');
}
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1>Event Details</h1>
</div>
<h2><?php if(isset($displayDate))echo $displayDate; ?></h2>
<div class="col-sm-8 box-tab">
<?php include('../events/eventDetail.php'); ?>
</div><!-- /.col -->
<div class="col-sm-4">
<?php include('../events/calendar.php'); ?>
</div>
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Home";
include 'header.php';
require_once("../rss/rsslib.php");
$url = "http://www.flpublicarchaeology.org/blog/wcrc/feed/";
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Junior Archaeologist Summer Camps</h1></th>
</tr>
<tr>
<td class="table_mid">
<div style="text-align:center"><a href="images/summercamp.png"><img src="images/summercamp_sm.png" /></a> </div>
<p><strong>Where:</strong> <br />
Weedon Island Preserve<br />
1800 Weedon Drive NE<br />
St. Petersburg, FL 33702 </p>
<p><strong>When:</strong> <em>Session 1:</em> July 21 – 25, <em>Session 2:</em> July 28 – August 1, 2014 </p>
<p><strong>Time:</strong> 9am – 4pm (Before-camp care is available from 7:45- 9am for an additional fee) </p>
<p><strong>Ages:</strong> Children 7 – 11 years </p>
<p>Florida Public Archaeology Network (FPAN), in partnership with the Alliance for Weedon Island Archaeological Research and Education (AWIARE), plans exciting new archaeology summer camps at Weedon Island Preserve designed for students who are interested in exploring the past. All camps are conducted by professional archaeologists, including educators from FPAN and allow kids to experience archaeology first-hand through activities, experiments, hikes, and even a real excavation. </p>
<p>This summer camp is designed for children with a strong interest in prehistory and history as well as learning how early people interacted with their environment. Campers will learn about the importance of archaeology and will gain understanding about early natural resources that were necessary for life in the Tampa Bay region. Highlights of the camps include guest experts, tour of an archaeological site, hands-on archaeology, lab analysis, pottery making, atlatl adventure, and earning the certificate of Tommy the Tortoise, Junior Archaeologist. </p>
<p>Registration: $150.00/camper/week </p>
<p>Registration is on a first-come, first-serve basis. Limited to 20/week. Before-camp care is available from 7:45 am to 9:00 am for an additional fee ($50.00) each week. </p>
<p>The registration form is available at <a href="http://awiare.org/?p=843" target="_blank">http://awiare.org/?p=843</a> or you can contact <NAME>’Sullivan (see information below) </p>
<p>For more information, or to register, please contact:<br />
<NAME>’Sullivan<br />
Office: <a href="tel:%28813%29%20396-2325" value="+18133962325" target="_blank">(813) 396-2325</a><br />
Email: <a href="mailto:<EMAIL>" target="_blank"><EMAIL></a></p></td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include '../events/eventBox.php'; ?><br/>
<!-- Facebook Like Box -->
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th class="sm_header">
<h1>Facebook</h1></a>
</th>
</tr>
<tr>
<td class="table_mid">
<div class="fb-like-box" data-href="http://www.facebook.com/FPANWestCentral" data-width="218" data-height="350" data-colorscheme="light" data-show-faces="true" data-header="false" data-stream="false" data-show-border="false"></div>
</td>
</tr>
<tr>
<td class="sm_bottom"></td>
</tr>
</table>
</div>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?>
<file_sep><?php
$pageTitle = "Workshops - Park Ranger Workshop";
include('../_header.php');
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1> Workshops, <small>HART</small></h1>
</div>
<div class="col-lg-8 col-lg-push-2 col-sm-10 col-sm-push-1 box-tab box-line row">
<div class="col-sm-12 text-center">
<div class="image">
<img class="img-responsive" src="images/rangerWorkshop1.jpg">
</div>
</div>
<p>
Many park rangers and public land managers come from an environmental, biology, or wildlife ecology background, and yet still are required to manage cultural resources located on their property. This one-day training is designed to assist rangers and park personnel in the identification, protection, interpretation, and effective management of historical and archaeological resources. Attendees receive a workbook filled with information and additional contacts, as well as hands-on practice in filling out archaeological site forms and tips on providing interpretive information about their sites for visitors.
</p>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
$pageTitle = "Workshops - Forest Resources Environmental Policy Special Sites ";
include('../_header.php');
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1> Workshops, <small>Forest Resources Environmental Policy Special Sites </small></h1>
</div>
<div class="col-lg-8 col-lg-push-2 col-sm-10 col-sm-push-1 box-tab box-line row">
<div class="col-sm-12 text-center">
<div class="image">
<img class="img-responsive" src="images/forest.jpg" width="3456" height="1944">
</div>
</div>
<p>Professional foresters and logging company personnel frequently come into contact with cultural resources, or “special sites.” This one-day workshop helps forestry professionals to identify historical and archaeological resources they are likely to encounter in the course of their work, including Native American sites, cemeteries, industrial sites, and sites submerged in rivers and streams. Information also includes what to do if a site is found; laws affecting sites on federal, state, and county lands; and how to proactively protect cultural sites.
</p>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
try{
if($dblink = mysqli_connect('localhost', 'root', '*UHB7ygv', 'fpan_events')){
}else{
throw new Exception("Failed to connect to MySQL: " . mysqli_connect_error());
}
} catch (Exception $e){
$sql_error = $e->getMessage();
}
?><file_sep><?php
$pageTitle = "Then and Now: Life Along the New River";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Then and Now: Life Along the New River</h1></th>
</tr>
<tr>
<td class="table_mid">
<div id="exhibit">
<?php include 'nav.php'?>
<h2 align="center">Tourism</h2>
<p><strong>For the past hundred years, tourists have flocked to the New River.</strong> Many tourists became locals, creating some of the diverse communities that exist in Fort Lauderdale to this day.</p>
<p>
<img src="images/exhibit24.jpg" style="float:right; margin-left:10px" alt="Sport fishing in Fort Lauderdale
Courtesy of the Broward County Historical Commision" />
After World War I, Sport fishing was a popular attraction that brought people to the area. Affordable Model T cars made it easy for even middle class folks to travel down to sunny Fort Lauderdale.<strong> At one time Tarpon Bend held the record for one of the largest game fish ever caught in American city limits. </strong><br />
<br />
<NAME> and <NAME> caught a 195 pound tarpon in the 1920s. In fact, this fish was so big that people stole the scales for souvenirs! The advertising that brought these people to Fort Lauderdale also helped fuel the 1920s Land Boom and the unfortunate bust that quickly followed the 1926 hurricane. </p>
<p> </p>
<p> </p>
<p>
<img src="images/exhibit25.jpg" style="float:left; margin-right:10px" alt="Brochure advertising the Marlin Beach Hotel" />
Each decade seemed to have a different target audience with 1960s being a “Spring Break” draw for college students from across the county. By the 1970s, tourism had slowed and a new market was identified. <strong> The Marlin Beach hotel became the first public gay beachside resort in the nation.</strong> The hotel responded to the gay community’s need for a destination catered to them. Vacationing at the Marlin Beach hotel served as an introduction to Fort Lauderdale for many gay visitors. A number of them returned, not as tourists, but as residents. Their presence in Fort Lauderdale has helped lead to the revitalization of neighborhoods such as Sailboat Bend, Victoria Park, and Wilton Manors.</p>
<p><span style="font-size:10px;">Contributions to the text by the Broward County LBGT Community History Project</span></p>
</div></td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?>
<file_sep><?php
$pageTitle = "Education";
include '../../admin/dbConnect.php';
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<th class="lg_header"><h1>Education</h1></th>
</tr>
<tr>
<td class="lg_mid" style="vertical-align:top">
<p>Ever wanted to bring your students to a real archaeological facility? Our museum and headquarters classroom is just the place for you! Field trips to the Destination Archaeology Resource Center and lab are designed for 3-12 grade; K-2 grade and adult programs also available. The program lasts approximately 1.5 hours and includes a powerpoint presentation called Introduction to Archaeology, a visit to Archaeology Lab or to a real archaeological site, and a guided tour of the museum exhibit where students will learn about the history and archaeology of Florida. <br />
<div align="center">
<img src="../images/kids_museum2.jpg"/>
</div>
</p>
<p>
<br />
<strong>Planning Your Trip</strong><br />
Contact DARC staff at 850 595-0050 EXT 107 or email Mike at <EMAIL> with at least two full weeks advance notice prior to the desired date and time of your group’s visit. Have at least two dates in mind prior to calling in case we cannot accommodate your group visit on the date and time you desire due to possible scheduling conflicts. We will try our best to schedule a date and time most convenient for you. Keep in mind that tours are offered Monday-Friday. Once staff has confirmed the date and time of your scheduled trip, a confirmation email will be sent to you with all the tour information. <br />
<br />
<strong>Fees</strong><br />
$2.00 suggested donation per student and chaperone. This donation to the UWF Foundation/FPAN will go to support our educational programs. Teachers and bus drivers are free. Check or cash accepted. <br />
<br />
<strong>Capacity</strong><br />
Groups of at least 10 qualify for an educational program. Due to space limitations, group number cannot exceed 65 persons per visit (including students, parents, chaperones, teachers, and drivers) . If your group exceeds the maximum number we can schedule the group for more than one visit by dividing them and having them arrive on different days or times.
</p>
<ul>
<li>10-30 students ----- Stay in 1 Group</li>
<li>30-65 students ----- Divide into 2 or 3 Groups</li>
</ul>
<p>
If your group has less than 10, you are welcome to visit the museum exhibit during normal operating hours (Monday-Saturday 10 AM – 4 PM) free of charge at your leisure. Although you will not qualify for a field trip we offer several programs throughout the year.<br />
<br />
<strong>Tour Length and Time</strong><br />
Our educational program for groups last approximately 1.5 hours. Tours slots are available Monday – Friday from 10 AM – 11:30 AM or 12:00 PM -1:30 PM. Each program will include 3 sections: An Introduction to Archaeology presentation in the classroom, a visit to a real Archaeology Lab, and a guided tour of the museum exhibit.
</p>
<p><br />
For free lesson plans visit <a href="http://www.flpublicarchaeology.org/resources/">http://www.flpublicarchaeology.org/resources/</a></p></td>
</tr>
</table>
<? include '../calendar.php'; ?>
<? include '../eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include '../footer.php'; ?><file_sep><?php
$pageTitle = "Home";
include 'dbConnect.php';
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<td class="lg_mid" style="vertical-align:top">
<h2 align="center"> Thank you! </h2>
<?php if($_GET['msg']) echo '<p align="center" style="color:green;" class="msg">'.$msg.'</p>'; ?>
<p style="margin-left:40px; margin-right:40px;">
Thank you for submitting your event! <br/><br/> We will review your event shortly and if approved, will post it to our calendar.
</p>
</td>
</tr>
</table>
<? include 'eventsBox.php'; ?>
<? include 'calendar.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include 'footer.php'; ?><file_sep><?php
include 'header.php';
//Define table name for this form
$table = 'Publication';
//if this is a new event, clear any potential leftover form data
if($_GET['new'])
$_SESSION['formVars'] = "";
//If event ID is supplied in URL, this event is being edited. Gather info from database and populate form.
if($_GET['id']){
setupEdit($_GET['id'], $table);
}
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true)
confirmSubmit($table);
//Form has been submitted but not confirmed. Display input values to check for accuracy
if(isset($_POST['submit'])&&!isset($_POST['confirmSubmission'])){
firstSubmit($_POST);
}elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="publications" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Publication</h2>
<p>Please fill out the information below to log this activity.</p>
</div>
<ul>
<li id="li_1" >
<label class="description" for="element_1">Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text" required="required"> /
<label for="element_1_1">MM</label>
</span>
<span>
<input id="element_1_2" name="day" class="element text" size="2" maxlength="2" value="<?php echo $formVars['day']; ?>" type="text" required="required"> /
<label for="element_1_2">DD</label>
</span>
<span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text" required="required"><a class="red"> *</a>
<label for="element_1_3">YYYY</label>
</span>
<span id="calendar_1">
<img id="cal_img_1" class="datepicker" src="images/calendar.gif" alt="Pick a date.">
</span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</li>
<li id="li_3" >
<label class="description" for="element_3">Type of Media </label>
<div>
<select class="element select small" id="element_3" name="typeMedia" required="required">
<option value="" selected="selected"></option>
<option value="Book" <?php if($formVars['typeMedia'] == 'Book') echo 'selected="selected"'; ?> >Book</option>
<option value="Chapter" <?php if($formVars['typeMedia'] == 'Chapter') echo 'selected="selected"'; ?> >Chapter</option>
<option value="Magazine" <?php if($formVars['typeMedia'] == 'Magazine') echo 'selected="selected"'; ?> >Magazine</option>
<option value="Newspaper" <?php if($formVars['typeMedia'] == 'Newspaper') echo 'selected="selected"'; ?>>Newspaper</option>
<option value="Newsletter" <?php if($formVars['typeMedia'] == 'Newsletter') echo 'selected="selected"'; ?>>Newsletter</option>
<option value="Blog" <?php if($formVars['typeMedia'] == 'Blog') echo 'selected="selected"'; ?>>Blog</option>
<option value="Other" <?php if($formVars['typeMedia'] == 'Other') echo 'selected="selected"'; ?>>Other</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_5" >
<?php include("staffInvolved.php"); ?>
</li>
<li id="li_2" >
<label class="description" for="element_2">Comments </label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium" onKeyDown="limitText(this.form.comments,this.form.countdown,2080);"
onKeyUp="limitText(this.form.comments,this.form.countdown,2080);"><?php echo $formVars['comments']; ?></textarea><br/>
<font size="1">(Maximum characters: 2080)<br>
You have <input readonly type="text" name="countdown" size="3" value="2080"> characters left.</font>
</div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close else ?>
<div id="footer"> </div>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body></html><file_sep><?php
$pageTitle = "Contact";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-6 col-sm-push-3">
<h3>Address</h3>
<p class="text-center">
3266 North Sailboat Ave.<br/>
Crystal River, Florida 34428
</p>
</div>
</div>
<div class="staff-box row">
<div class="col-sm-6">
<img src="../wcrc/images/jeff.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME>, M.A., RPA</strong>
<em>Central Region Director</em><br/>
(813) 396-2327<br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('jeff_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="jeff_bio" class="hidden bio">
Jeff is the Director of the West Central Regional Center of FPAN. He earned a M.A. in History/Historical Archaeology and a B.A. in Anthropology from the University of West Florida. Jeff’s work experiences prior to FPAN include employment as a field tech and crew chief with Archaeological Consultants, Inc (Sarasota, FL), an underwater archaeologist for the FL Bureau of Archaeological Research, and museum curator at the Florida Maritime Museum at Cortez. Jeff enjoys coffee and smoked mullet, but not necessarily at the same time.
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6">
<img src="images/nigel.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Public Archaeology Coordinator</em><br/>
(352) 795-0208 <br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<!-- <strong onclick="javascript:showElement('barbara_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong> -->
</p>
</div>
<!-- <div class="col-xs-12">
<p id="barbara_bio" class="hidden bio">
<NAME> is a Registered Professional Archaeologist who specializes in historic archaeology, 19th and early 20th century. Her interests include the turpentine and lumber industry, specifically focusing on the social aspects of "camp life". She also has taken an interest in early Florida architecture, and did her thesis work on an early 1900s Folk Victorian structure in Sopchoppy, Florida. Her thesis focused on examining the relationship between architecture, societal relationships and social class perceptions. Barbara has also taken an interest in Southeastern Indian communities after European contact, specifically in the late 1800 up to the present, focusing on the mixing of cultures and how the Southeastern Indian population has survived and adapted.
</p>
</div> -->
</div><!-- /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Contact";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-6 col-sm-push-3">
<h3>Address</h3>
<p class="text-center">
1022 DeSoto Park Dr. <br/>
Tallahassee, Florida 32301<br/>
</p>
</div>
</div>
<div class="staff-box row">
<div class="col-sm-6">
<img src="/images/people/barbara.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME>, RPA</strong>
<em>North Central Region Director</em><br/>
(850) 933-5779<br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('barbara_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="barbara_bio" class="hidden bio">
<NAME> is a Registered Professional Archaeologist who specializes in historic archaeology, 19th and early 20th century. Her interests include the turpentine and lumber industry, specifically focusing on the social aspects of "camp life". She also has taken an interest in early Florida architecture, and did her thesis work on an early 1900s Folk Victorian structure in Sopchoppy, Florida. Her thesis focused on examining the relationship between architecture, societal relationships and social class perceptions. Barbara has also taken an interest in Southeastern Indian communities after European contact, specifically in the late 1800 up to the present, focusing on the mixing of cultures and how the Southeastern Indian population has survived and adapted.
</p>
</div>
</div><!-- /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Home";
include '../dbConnect.php';
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<th class="lg_header"><h1>Exhibits</h1></th>
</tr>
<tr>
<td class="lg_mid" style="vertical-align:top">
<h2 style="padding-left:20px;">Permanent</h2><br />
<h3><em>A Road Trip through Florida Archaeology</em></h3>
<p>
With 500 years of European history and more than 10,000 years of Native American prehistory, Florida is host to an array of cultural landmark sites. Archaeological sites across the state have helped shed the light on our past. In this exhibit you will journey through the eight different regions of Florida and visit significant archaeological sites along the way. These include prehistoric mounds, shipwrecks, forts and Spanish missions, battlefields, and museums. Throughout the exhibit you can interact with digital displays and get a chance to touch real artifacts from a few of these sites. The best part about the sites featured in the exhibit- you can visit them in person and we can show you how to get there!<br />
<div align="center">
<img src="../images/exhibits.jpg" />
</div>
</p>
<hr/>
<h2 style="padding-left:20px;">Temporary</h2>
<h3><em>Mahogany and Iron</em></h3>
<p>
Currently on Display<br />
<br />
<a href="../images/mahagony_iron_full.jpg"><img src="../images/mahagony_iron.jpg" width="350" height="255" alt="Mahogany and Iron" /></a><br />
<br />
In the late 1990s underwater archaeologists from the University of West Florida uncovered the remarkably well-preserved 17th century Spanish shipwreck of Nuestra Señora del Rosario y <NAME>. Rosario was built in 1696 as a powerful warship for the Spanish navy. As part of the Windward Fleet, she protected convoys of ships loaded with valuable goods traveling between Spain and its New World colonies. </p>
<p>Throughout her career the ship performed many duties including hunting pirates and supplying far-flung settlements. The ship was lost in 1705 while resupplying the colony at Pensacola, then known as Presidio <NAME>. This exhibit examines the excavation of this shipwreck and the clues archaeologists are uncovering about its construction currently under research. Several artifacts from the wreck are on display.</p>
<br />
<h3><em>Rebel Guns</em></h3>
<p>
March - December 2012<br />
<br />
<a href="../images/rebel_guns_full.jpg"><img src="../images/rebel_guns.jpg" width="250" height="331" alt="Rebel Guns Flier" /></a><br /><br />
During the Civil War in Florida waterways were vital to the movement of troops and supplies. In the South, the Apalachicola River led straight to the manufacturing heart of the Confederacy in Columbus, Georgia. Controlling it meant victory or defeat. The Confederacy built obstacles in the river and gun emplacements, or batteries, at strategic points along the river edge to prevent the Union from passing upriver. <br />
In 2010 a team of archaeologists from the University of West Florida and Florida Public Archaeology Network meticulously removed layers of earth in Florida’s Torreya State Park along the banks of the Apalachicola River. Here they uncovered a part of history from the American Civil War. This exhibit is the story of this site as it was revealed through archaeological investigations.
<br /></p>
<h3><em>Florida’s Fishing Ranchos: Legacy of Cuban Trade</em></h3>
<p>
June 2011 - March 2012<br />
<br />
<img src="../images/ranchos.jpg" width="350" height="238" alt="Fishing Ranchos Flier" /><br />
<br />
Before the Marxist inspired revolution of 1959, trade between Cuba and the land of Florida lasted for hundreds of years. Fishermen from Cuba found the waters on Florida’s southwest coast productive and markets in Havana made trade opportunities between them profitable. By the 19th century Cuban fishing ranchos on Florida’s Gulf coast were occupied year round and they formed deep connections with other cultural groups living in the state. This exhibit is about this legacy of trade and the fishermen who formed these unique communities. The exhibit features interpretive panels and artifacts.</p></td>
</tr>
</table>
<? include '../calendar.php'; ?>
<? include '../eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include '../footer.php'; ?><file_sep><?php
include 'admin/dbConnect.php';
include '_publicFunctions.php';
?>
<!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>FPAN<?php if($pageTitle){echo " - ".$pageTitle;} ?></title>
<meta name="DESCRIPTION" content="FPAN is dedicated to the protection of cultural resources, both on land and underwater, and to involving the public in the study of their past."/>
<meta name="KEYWORDS" content="fpan, florida public archaeology, public archaeology, florida, archaeology, florida archaeology, florida archaeology network"/>
<!-- All Inclusive Stylsheet (Bootstrap, FontAwesome, FPAN Styles) -->
<link href="/_css/style.css" rel="stylesheet">
<!-- Favicon -->
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
<!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Google Web Tools tag -->
<meta name="google-site-verification" content="M4KK2hljMvdoaAI0qoPzvOwifcVuvp-fC6gV6HeVQbU" /
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-7301672-3']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- end google analytics -->
</head>
<body>
<!-- Nav goes here! -->
<?php include('_mainNav.php'); ?><file_sep><?php
$pageTitle = "Programs";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Cemetery Resource Protection Training (CRPT)</h1></th>
</tr>
<tr>
<td>
<p class="center">
<img src="images/crptBanner.jpg" class="padded" />
</p><br/>
<p>
Join the <a href="https://www.facebook.com/groups/418690514894961/">CRPT Alliance group on Facebook</a> for the latest news on upcoming CRPT events. </p>
<img src="images/crpt1.jpg" style="float:right; margin-right:70px;" class="padded"/>
<p>
CRPT focuses on cemetery care and protection. Participants explore cemeteries as historical resources, laws that protect them, conserving headstone and markers, managing cemetery landscapes, and practice hands-on headstone cleaning with a D-2 solution. <br />
</p>
<br/>
<hr/>
<p>
<h4> <a href="http://www.flpublicarchaeology.org/programs/">< Go Back to Program List</a></h4>
</p>
</td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?><file_sep><?php
$pageTitle = "";
include('../_header.php');
?>
<div class="container">
<div class="page-header">
<h1> Cemetery Resource Protection Training (CRPT)</h1>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 ">
<div class="row box box-line">
<div class="col-sm-12">
<img src="images/crpt_lg.svg" class="img-responsive center-block" alt="CRPT Banner" />
<br/>
<p>Join the <a href="https://www.facebook.com/groups/418690514894961/" target="_blank">CRPT Alliance group on Facebook</a> for the latest news on upcoming CRPT events.</p>
<p>CRPT focuses on cemetery care and protection. Participants explore cemeteries as historical resources, laws that protect them, conserving headstone and markers, managing cemetery landscapes, and practice hands-on headstone cleaning with a D-2 solution. </p>
</div><!-- /.col -->
<div class="col-sm-12 text-center">
<div class="image">
<img src="images/crpt3.jpg" class="img-responsive" alt="CRPT trainees" />
<p> CRPT partcipants and instructors </p>
</div>
</div><!-- /.col -->
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
$pageTitle = "Programs";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Archaeo Cart</h1></th>
</tr>
<tr>
<td class="table_mid">
<h3 align="center"><em>What is ARCHAEO CART?</em></h3>
<p><strong>ARCHAEO CART</strong> is a program of the <strong>Florida Public Archaeology Network </strong>and is used to deliver engaging educational programs and archaeology outreach. When <strong>ARCHAEO CART</strong> visits your school or location, students and visitors can tour virtual displays of archaeology sites across Florida, uncover prehistoric and historic timelines, or discover what it takes to think like and be an archaeologist.</p>
<p align="center"><img src="images/archaeo_cart_postcard.png" alt="Archaeo Cart Postcard" class="padded"/></p>
<p><strong>ARCHAEO CART</strong> is a Portable Public Archaeology Classroom. It comes equipped with archaeology-related educational activities, interactive displays, and reading and resource materials. It is available for use at museums, libraries, media centers, schools, classrooms, and special events. Groups or organizations can borrow <strong>ARCHAEO CART</strong> for a predetermined length of time. Borrowers are required to provide security and dedicated electricity for the device and must also participate in a short training and workshop upon delivery. </p>
<p> </p>
<p align="center"><img src="images/archaeo_cart.jpg" alt="Archaeo Cart" class="padded"/></p>
<h3 align="center"><em>How can I get ARCHAEO CART?</em></h3>
<p><strong>ARCHAEO CART</strong> is currently being piloted at the <a href="http://www.tampabayhistorycenter.org/">Tampa Bay History Center</a> and <a href="http://www.staugustinelighthouse.com/">St. Augustine Lighthouse & Museum</a>. It will be available to a wider audience in <strong>March 2012</strong>. Please contact us at <a href="mailto:<EMAIL>"><EMAIL></a> for more information or to schedule the cart for your venue. </p>
<h3 align="center">
<em>Who is <NAME> Tortoise?<br />
</em> <img src="images/Tommy_tortoise.png" alt="<NAME> Tortoise" /></h3>
<p><strong><NAME> Tortoise</strong> is your guide through Florida archaeology. His timeline program on <strong>ARCHAEO CART</strong>’s touch screen teaches participants about the many cultural time periods in Florida. He also travels to many sites in Florida and shares what he has learned through his Facebook page. </p>
<p>Make sure to visit <strong><a href="http://www.facebook.com/pages/Tommy-the-Tortoise-Junior-Archaeologist/189861687739646">Tommy the Tortoise</a></strong> on Facebook and become a fan!</p></td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
$pageTitle = "Timucuan Technology";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Timucuan Technology</h1></th>
</tr>
<tr>
<td class="table_mid"><p><strong>Download:</strong> <em>Timucuan Technology</em>(68 MB)
Instructions for Teachers (X MB) <a name="_GoBack"></a> Alignment with Sunshine State Standards, answer keys, activity tips, references, recommended reading <img src="images/clip_image002.jpg" alt="" width="52" height="52" hspace="12"> Introduction—Who Were the Timucua? </p>
<p> </p>
<table border="0">
<tr>
<td>
<img src="images/clip_image004.jpg" alt="" width="61" height="60" hspace="12">
</td>
<td>1. Theodore de Bry’s Timucuan Engravings—Fact or Fiction? <br/>
Teacher Pages </td>
</tr>
<tr>
<td>
<img src="images/clip_image006.jpg" alt="" width="65" height="59" hspace="12">
</td>
<td>2. Pyrotechnology <br/>
Teacher Pages </td>
</tr>
<tr>
<td>
<img src="images/clip_image008.jpg" alt="" width="69" height="73" hspace="12">
</td>
<td>3. Tool-Making Technology <br/>
Teacher Pages</td>
</tr>
<tr>
<td>
<img src="images/clip_image010.jpg" alt="" width="67" height="62" hspace="12">
</td>
<td>4. Animal Technology <br/>
Teacher Pages</td>
</tr>
<tr>
<td>
<img src="images/clip_image012.jpg" alt="" width="67" height="66" hspace="12">
</td>
<td>5. Wild Plant Technology <br/>
Teacher Pages</td>
</tr>
<tr>
<td>
<img src="images/clip_image014.jpg" alt="" width="69" height="72" hspace="12">
</td>
<td>6. Agricultural Technology <br/>
Teacher Pages </td>
</tr>
<tr>
<td>
<img src="images/clip_image016.jpg" alt="" width="75" height="77" hspace="12">
</td>
<td>7. Building Technology <br/>
Teacher Pages</td>
</tr>
<tr>
<td>
<img src="images/clip_image018.jpg" alt="" width="74" height="67" hspace="12">
</td>
<td>8. Archaeological Technology <br/>
Teacher Pages</td>
</tr>
<tr>
<td>
<img src="images/clip_image020.jpg" alt="" width="75" height="70" hspace="12">
</td>
<td>9. Archaeology—Beyond Excavation <br/>
Teacher Pages </td>
</tr>
<tr>
<td>
<img src="images/clip_image022.jpg" alt="" width="75" height="69" hspace="12">
</td>
<td>10. History and the Timucua <br/>
Teacher Pages</td>
</tr>
</table>
</td>
</tr>
<tr>
<td height="2" class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
include 'header.php';
//Submission has been confirmed, add to database
if($_POST['submit'] == true){
$formVars = $_SESSION['formVars'];
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$email = mysql_real_escape_string($_POST['email']);
$position = mysql_real_escape_string($_POST['position']);
//Set user access role
if(($position == "Outreach Coordinator") || ($position == "Regional Director"))
$role = 2; //Level 2 - Submit/Edit/View events in own region
else
$role = 3; //Level 3 - Submit/View events in own region (Other Staff and Interns)
//Insert employee info
$sql = "INSERT INTO Employees (role, firstName, lastName, position, email, password)
VALUES ('$role', '$firstName', '$lastName', '$position', '$email', AES_ENCRYPT('password', '$_SESSION[aes_key]')) ";
if(!mysql_query($sql)){
$err = true;
$msg .= ' Error: ' . mysql_error();
}
//Get new Employee ID
$sql = "SELECT id FROM Employees WHERE email = '$email'";
$result = mysql_query($sql);
$employeeID = mysql_result($result, 0);
$sql ="";
//Add entires to EmployeeRegion table for associated regions
foreach($_POST['region'] as $region){
$sql = "INSERT INTO EmployeeRegion (employeeID, region) VALUES ($employeeID, '$region');";
if(!mysql_query($sql)){
$err = true;
$msg .= ' Error: ' . mysql_error();
}
}
//echo $sql;
//If there were no erorrs while inserting: Clear temporary event array, display success message
if($err != true){
$_SESSION['formVars'] = "";
$msg = "Employee was successfully added!";
}
?>
<div class="summary"> <br/>
<br/>
<?php echo "<h3>".$msg."</h3>"; ?> <br/>
<br/>
<br/>
<br/>
<a href="<?php echo $_SERVER['PHP_SELF']; ?>">Add another employee</a> or
<a href="main.php">return to main menu</a>. <br/>
<br/>
</div>
<?php }else{ ?>
<form id="addEmployees" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Add an Employee</h2>
<p>Use this form to add a new employee to the system. Default password will be "<PASSWORD>". <br/>
<strong> Make sure employee changes default password ASAP. </strong></p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="element_1">First Name </label>
<div>
<input id="element_1" name="firstName" class="element text small" type="text" maxlength="255" value="" required="required"/>
</div>
</li>
<li id="li_2" >
<label class="description" for="element_2">Last Name </label>
<div>
<input id="element_2" name="lastName" class="element text small" type="text" maxlength="255" value="" required="required"/>
</div>
</li>
<li id="li_3" >
<label class="description" for="element_3">Email </label>
<div>
<input id="element_3" name="email" class="element text medium" type="text" maxlength="255" value="" required="required"/>
</div>
</li>
<li id="li_4" >
<label class="description" for="element_4">Position </label>
<div>
<select class="element select medium" id="element_4" name="position" required="required">
<option value="" selected="selected"></option>
<option value="Regional Director" >Regional Director</option>
<option value="Outreach Coordinator" >Outreach Coordinator</option>
<option value="Intern" >Intern</option>
<option value="Other Staff">Other Staff</option>
</select>
</div>
</li>
<li id="li_5" >
<label class="description" for="element_5">Region </label>
<div>
<input type="checkbox" name="region[]" value="nwrc" /><label class="choice">Northwest</label>
<input type="checkbox" name="region[]" value="ncrc" /><label class="choice">North Central</label>
<input type="checkbox" name="region[]" value="nerc" /><label class="choice">Northeast</label>
<input type="checkbox" name="region[]" value="crc" /><label class="choice">Central</label>
<input type="checkbox" name="region[]" value="wcrc" /><label class="choice">West Central</label>
<input type="checkbox" name="region[]" value="ecrc" /><label class="choice">East Central</label>
<input type="checkbox" name="region[]" value="swrc" /><label class="choice">Southwest</label>
<input type="checkbox" name="region[]" value="serc" /><label class="choice">Southeast</label>
</div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close if ?>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body></html><file_sep><?php
$pageTitle = "Presentations";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?> <small>Request a Speaker</small></h1>
</div>
<div class="box-dash">
<!-- <div class="col-sm-12 text-center">
<div class="image">
<img src="images/presentations.jpg" alt="Speaker presentations." class="img-responsive" width="300" height="230" />
</div>
</div> -->
<p>FPAN can help facilitate speakers for meetings of your civic group, community organization,
youth club, or heritage society, and for lecture series and special events.</p>
<p>Most presentations last about 30-45 minutes with additional time for questions, although
programs usually can be tailored for your needs. Specific topics are dependent on speaker
availability, so book early! There is no charge for presentations, although donations are
gratefully accepted to support FPAN educational programs.</p>
<p>Take a look at our offerings, then <a href="https://casweb.wufoo.com/forms/north-central-speaker-request-form/">
submit the form below</a> and let us
know what you’d like to learn about! If you don’t see what you’re looking for, ask us and we’ll do our
best to accommodate you.</p>
<p class="text-center"><em>Know what you want?</em> <br/> <a class="btn btn-primary"
href="https://casweb.wufoo.com/forms/north-central-speaker-request-form/" target="_blank">Submit a Speaker Request Form</a> </p>
</div>
<h2>Presentation Topics</h2>
<div class="box-tab row">
<div class="col-sm-6">
<ul>
<li><a href="#fpt">Florida’s Prehistoric Technology</a></li>
<li><a href="#introarch">Introduction to Archaeology for Kids</a></li>
<li><a href="#flpre">Learning about Florida Prehistory</a></li>
<li><a href="#histcem">Historic Cemeteries as Cultural Resources</a></li>
<li><a href="#ecoimp">Economic Impacts of Historic Preservation and Heritage Tourism</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#spanish">Spanish Florida</a></li>
<li><a href="#introuw">Introduction to Underwater Archaeology</a></li>
<li><a href="#native">Native People, Native Plants</a></li>
<li><a href="#turpentine">The Turpentine Industry in North Florida</a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div class="col-sm-12">
<h3 id="fpt">Florida’s Prehistoric Technology</h3>
<p>Today when we think of technology we think of cell phones and computers, but what technology did Native Americans in Florida use to survive? This presentation discusses just that! We even have some replica tools that students can hold and touch to get a real feel for how these tools would have been used!</p>
</div>
<div class="col-sm-12">
<h3 id="introarch">Introduction to Archaeology for Kids</h3>
<p>This presentation focuses on the basics of archaeology, including what archaeologists do and how they do it in such a way that it is easily understandable. This presentation can be tailored so that it suits younger and older students, and it can be combined with a hands-on activity as well.</p>
</div>
<div class="col-sm-12">
<h3 id="flpre">Learning about Florida Prehistory</h3>
<p>This presentation teaches the audience about the different culture periods in Florida’s Prehistory, from Paleoindian times through the Historic Period. This presentation uses basic terms and is easy to understand. It is a fun presentation that is appropriate for both children and adults.</p>
</div>
<div class="col-sm-12">
<h3 id="histcem">Historic Cemeteries as Cultural Resources</h3>
<p>This presentation provides information on how historic cemeteries can be used in research and what information they can provide. It also touches on the basics of how to properly clean and maintain historic cemeteries. It also touches on some of the meanings of common symbols that you find in historic cemeteries. The presentation also provides resources for locating professional curators and conservators to assist with historic cemetery restoration.</p>
</div>
<div class="col-sm-12">
<h3 id="ecoimp">Economic Impacts of Historic Preservation and Heritage Tourism</h3>
<p>Heritage tourism is one of the fastest growing segments of the tourism industry. This presentation discusses the economic, as well as other benefits of historic preservation and heritage tourism. Great for groups considering heritage tourism projects.</p>
</div>
<div class="col-sm-12">
<h3 id="spanish">Spanish Florida</h3>
<p>A brief overview of the Spanish in Florida, including the Spanish Missions, focusing on Mission San Luis and the Apalachee. The presentation ends with a discussion on how the Spanish have had a lasting influence on Florida’s heritage. This presentation can be altered to cater to any age group (adult or children).</p>
</div>
<div class="col-sm-12">
<h3 id="introuw">Introduction to Underwater Archaeology</h3>
<p>This presentation discusses the differences and similarities between terrestrial and underwater archaeology. It provides a good basic understanding of how archaeologists conduct underwater excavations. It also touches on the unique preservation issues relating to objects that archaeologist find at submerged archaeological sites.</p>
</div>
<div class="col-sm-12">
<h3 id="native">Native People, Native Plants</h3>
<p>This presentation discusses how plants have been used as medicine and food in Florida by prehistoric people and early settlers in Florida. This presentation was developed for Florida Archaeology Month 2011, but continues to be relevant and of interest to the public. </p>
</div>
<div class="col-sm-12">
<h3 id="turpentine">The Turpentine Industry in North Florida</h3>
<p>This presentation discusses the turpentine and naval store industry in Florida and the impacts it had on the economy, industry and the state’s history. This presentation is geared towards adults and can be modified to reflect the local history of any region in Florida.</p>
</div>
</div>
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Home";
include '../dbConnect.php';
include 'header.php';
$flashvars = "file=http://www.flpublicarchaeology.org/resources/videos/darcIntro.flv&screencolor=000000";
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<th class="lg_header"><h1>Destination Archaeology</h1></th>
</tr>
<tr>
<td class="lg_mid" style="vertical-align:top">
<div align="center">
<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='620' height='349' id='single1' name='single1'>
<param name='movie' value='player.swf'>
<param name='allowfullscreen' value='true'>
<param name='allowscriptaccess' value='always'>
<param name='wmode' value='transparent'>
<?php echo "<param name='flashvars' value='$flashvars'>" ?>
<embed
type='application/x-shockwave-flash'
id='single2'
name='single2'
src='player.swf'
width='600'
height='338'
bgcolor='000000'
allowscriptaccess='always'
allowfullscreen='true'
wmode='transparent'
<?php echo "flashvars='$flashvars'" ?>
/>
</object>
</div>
<p align="center"><a href="http://www.youtube.com/watch?v=k9PZL1JbhAY"> View on YouTube</a> </p>
<p>Located inside the Florida Public Archaeology Network headquarters in downtown Pensacola, the
Destination Archaeology Resource Center is an archaeology museum open to the public. Inside you will
learn about the amazing archaeological sites that you can visit and experience throughout the state. Our
exhibits include displays about both land and underwater archaeology sites. We showcase heritage sites
open to the public within the eight regions of the Florida Public Archaeology Network with traditional
and interactive displays, including touchscreens, tablet computers and artifacts. Additionally, our
museum hosts a variety of free exhibits, events, and programs throughout the year.</p>
<p> </p></td>
</tr>
</table>
<? include 'calendar.php'; ?>
<? include 'eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include 'footer.php'; ?><file_sep><?php
$pageTitle = "Presentations";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?> <small>& Programs</small> </h1>
</div>
<div class="box-dash">
<p>FPAN can help facilitate speakers for meetings of your civic group, community organization,
youth club, or heritage society, and for lecture series and special events.</p>
<p>Most presentations last about 30-45 minutes with additional time for questions, although
programs usually can be tailored for your needs. Specific topics are dependent on speaker
availability, so book early! There is no charge for presentations, although donations are
gratefully accepted to support FPAN educational programs.</p>
<p>Presentation topics are divided into two sections: </p>
<div class="col-sm-12 text-center">
<p>
<a href="#children" class="btn btn-info">Activities for Children</a>
<a href="#adults" class="btn btn-info">Presentation Topics for Adults</a>
</p>
</div>
<p>Take a look at our offerings, then <a href="https://casweb.wufoo.com/forms/east-central-speaker-request-form/">
submit the form below</a> and let us
know what you’d like to learn about! If you don’t see what you’re looking for, ask us and we’ll do our
best to accommodate you.</p>
<p class="text-center"><em>Know what you want?</em> <br/> <a class="btn btn-primary"
href="https://casweb.wufoo.com/forms/east-central-speaker-request-form/" target="_blank">Submit a Speaker Request Form</a> </p>
</div>
<h2 id="children">Hands-On <small>Activities for Children</small></h2>
<div class="box-tab row">
<p>FPAN staff is available to visit your classroom, camp or club and provide hands-on archaeology education activities. If interested, select from presentation list below and fill out our program request form at the top of the page. Programs are free for public schools, public libraries, local museums and non-profit organizations. Florida Archaeology Month (March) and Summer calendars fill up fast so please schedule as soon as possible in advance.</p>
<div class="col-sm-6">
<ul>
<li><a href="#timu">Timucuan Pyrotechnology</a></li>
<li><a href="#tools">Tools of the Trade</a> </li>
<li><a href="#pbj">PB&J: How (and why!) Archaeologists Find Sites </a></li>
<li><a href="#prepot">Prehistoric Pottery</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#underwater">Underwater Archaeology</a></li>
<li><a href="#kingsley">Kingsley Slave Cabin Archaeology</a></li>
<li><a href="#prefl">Make Prehistoric Florida your Home </a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div id="timu" class="col-sm-12">
<h3>Timucuan Pyrotechnology</h3>
<p>This activity introduces students to Timucuan culture, focusing on ways that local prehistoric people used fire to meet their daily needs. A hands-on experiment provides a bang as students use balloons (and water balloons!) to explore how prehistoric people could cook prior to the advent of pottery.</p>
</div>
<div id="tools" class="col-sm-12">
<h3>Tools of the Trade </h3>
<p>One of the best ways to show people how we study a site is to share our tool kit. Students observe the tools we use in the field and infer the reasoning behind our choices. For example, many people may know we use a trowel, but what's the difference between the pointy ones versus the flat edge blades? What would we do that? Tools include trowels (yes, plural!), munsell color chart, line levels, various measuring devices, and root clippers. The most important? Our pencil and sharpie for recording our findings. </p>
</div>
<div id="pbj" class="col-sm-12">
<h3>PB&J: How (and why!) Archaeologists Find Sites </h3>
<p>A classic! Students systematically excavate a peanut butter and jelly sandwich to explore the concepts of stratigraphy and survey, emphasizing how archaeologists use the scientific method in the field. If Power Point is available, this activity can include pictures of real tools, fieldwork, and sites to enhance learning.</p>
</div>
<div id="prepot" class="col-sm-12">
<h3>Prehistoric Pottery</h3>
<p>Students learn about the advent of pottery in Florida, and do hands-on experimentation using play-doh to explore pottery-making and -decorating technology. The lesson also teaches about how pottery can help archaeologists understand a site and its prehistoric people.</p>
</div>
<div id="underwater" class="col-sm-12">
<h3>Underwater Archaeology</h3>
<p>This lesson uses on the book Shipwreck: Fast Forward to explore how underwater sites form, and the excavation processes used to retrieve information about them. Kids then try their own hand at using Cartesian coordinates by playing an adapted version of Battleship to “map” each other’s shipwrecks, and they get to map a real, 100-year-old anchor!</p>
</div>
<div id="kingsley" class="col-sm-12">
<h3>Kingsley Slave Cabin Archaeology</h3>
<p>Recent excavations at Kingsley Plantation have radically changed our understanding of what life was like for the enslaved people living there. This lesson tasks students with mapping artifacts exactly where they were found in the cabin, just like archaeologists do. After mapping, they work in teams to classify artifacts. Finally, as a group we discuss explore what we can understand about this population by looking at these artifacts in context (where they were found and with what other objects).</p>
</div>
<div id="prefl" class="col-sm-12">
<h3>Make Prehistoric Florida your Home </h3>
<p>This presentation teaches children about the raw and natural resources Native Americans used to build their campsites and villages. How did they build houses and shelter? How did they construct giant mounds? What did they make their tools and clothing out of? Kids enjoy learning how ancient peoples used the natural environment to hunt, fish, build towns, and make a living in prehistoric Florida! </p>
</div>
</div><!-- /.box /.row -->
<h2 id="adults">Presentation<small> Topics for Adults</small></h2>
<div class="box-tab row">
<p><p>FPAN staff is available to come talk to local libraries, civic organizations, historical societies and any other group interested in hearing more about Florida archaeology. Below are some of the standard talks we give in the region but we are often able to custom make a talk based on your interest. Select a title from the list below to fill out the program request form at the top of the page or get in touch with us at <a href="mailto:<EMAIL>"><EMAIL></a>. Programs are free and subject to staff availability for scheduling.</p></p>
<div class="col-sm-6">
<ul>
<li><a href="#16th">In Search of 16th-Century St. Augustine</a></li>
<li><a href="#stjohns">Archaeology Along the St. Johns River</a></li>
<li><a href="#fantastic">Fantastic Archaeology: Florida Frauds, Myths, and Mysteries</a> </li>
<li><a href="#coquina">Coquina: Florida's Pet Rock</a> </li>
<li><a href="#preweap">Prehistoric Weaponry</a> </li>
<li><a href="#archfl">Archaeology in Florida State Parks</a> </li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#shiptime">A Florida Shipwreck through Time</a> </li>
<li><a href="#histcem">Historic Cemeteries as Outdoor Museums</a></li>
<li><a href="#prehist">14,000 Years of Florida Prehistory</a> </li>
<li><a href="#paleo">Paleoenvironments</a> </li>
<li><a href="#shells">Shells</a> </li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div id="16th" class="col-sm-12">
<h3>In Search of 16th-Century St. Augustine</h3>
<p>Walking the streets of St. Augustine can confuse the visitor in search of the 16th century, but 500-year-old sites are there—often beneath their feet. This presentation synthesizes work done by archaeologists over the past century and focuses on small objects that bring ordinary people in the 16th century to life. Those planning to partake in the city's 450th birthday party can prepare with our “Top Ten to Do Before 2015”—the best ways to get a glimpse of the city’s earliest days. </p>
</div>
<div id="stjohns" class="col-sm-12">
<h3>Archaeology Along the St. Johns River</h3>
<p>The St. Johns River has played an ever changing role in the lives of northeast Floridians for thousands of years. Prehistorically, the river provided food, transportation, and a geographic conntection between people living from the source to the mouth. Historically, the river supported missions, plantations, and military outposts. Exploration is not limited to land; famous archaeological sites on the river's bottom also have been discovered and add to our knowledge of Florida's past. </p>
</div>
<div id="fantastic" class="col-sm-12">
<h3>Fantastic Archaeology: Florida Frauds, Myths, and Mysteries </h3>
<p>Celebrate Florida archaeology by learning what archaeology is, and importantly what it is not. This educational and entertaining talk will focus on the misuse and abuse of northeast Florida's past. </p>
</div>
<div id="coquina" class="col-sm-12">
<h3>Coquina: Florida's Pet Rock </h3>
<p>As a supplement to Coquina Queries we are able to come out to festivals and classrooms with a variety of teaching tools. We can either emphasize ruins in our region made out of coquina, talk about care and conservation, or create stations of hands-on activities in formal and informal settings. </p>
</div>
<div id="preweap" class="col-sm-12">
<h3>Prehistoric Weaponry</h3>
<p>The difference between a tool and a weapon is a matter of intent. While this can be difficult to ascribe archaeologically, humans have used tools as weapons for over a million years. This presentation puts better known projectile points in context of their arrival to southeastern North America and discusses biotechnology put into action by Timucuans and other prehistoric people. </p>
</div>
<div id="archfl" class="col-sm-12">
<h3>Archaeology in Florida State Parks </h3>
<p>When people first realize archaeology happens in Florida, it often surprises them to hear of how many active permits are issued to do work in state parks. Some of the digs are by field school where students learn the ABCs of excavation, while other digs are done in advance of construction or improvements to a park. This lecture emphasizes visitation of the many parks that feature archaeology interpreted for the public including Ft. Mose, Hontoon Island, Crystal River, Bulow Sugar Mill, Ft. Clinch, De Leon Springs, and many more. </p>
</div>
<div id="shiptime" class="col-sm-12">
<h3>A Florida Shipwreck through Time </h3>
<p>Based on the book <a href="http://www.amazon.com/Shipwreck-Leap-Through-Claire-Aston/dp/1901323587/ref=sr_1_2?s=books&ie=UTF8&qid=1283977267&sr=1-2">Shipwreck: Leap through Time</a>, this talk takes the audience through the stages of a shipwreck--from ship construction to underwater museum. The issue of piracy in archaeology is addressed, as well as expanding known submerged resources beyond maritime themes. </p>
</div>
<div id="histcem" class="col-sm-12">
<h3>Historic Cemeteries as Outdoor Museums</h3>
<p>We encourage families and classes to get into the cemeteries within their communities and put archaeological principles to the test. This presentation can be brought via Powerpoint or introduced on-site at an actual cemetery. Iconography, dating of headstones, and change of style over time (seriation) are emphasized along with lessons in cemetery preservation. </p>
</div>
<div id="prehist" class="col-sm-12">
<h3>14,000 Years of Florida Prehistory </h3>
<p>This lecture discusses the chronology of Florida’s prehistoric Native Americans, and discusses their major technological achievements through time. 14k Years of FL Prehistory presents the four archaeological time periods in the southeastern United States, and how archaeologists use them to differentiate among different culture groups. This presentation is perfect for those looking for a broad overview of prehistoric archaeology in Florida. </p>
</div>
<div id="paleo" class="col-sm-12">
<h3>Paleoenvironments </h3>
<p>How do archaeologists learn what past environments were like? This lecture covers the study of archaeological bones, shells, and other faunal artifacts, and also pollen and other plant remains to learn about ancient environments. It also discusses sediment coring to investigate different geological layers. ‘Paleoenvironments’ is a wonderful lecture if you’re interested in how Florida’s environment has changed affected Natives over time. </p>
</div>
<div id="shells" class="col-sm-12">
<h3>Shells </h3>
<p>The shell workshop includes both lecture- and activity-based components. It introduces participants to common Florida shells, found in both prehistoric middens and along today’s modern beaches and tidal flats. The lecture portion emphasizes the physical characteristics of species, but also discusses their ecology, how they were used by Native Americans and Europeans, and how archaeologists use them to understand past peoples and environments. The activities include shell-related games for kids, and fun shell midden scenarios/problems for adults to solve. </p>
</div>
</div><!-- /.box /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "";
include('_header.php');
?>
<div class="page-content container">
<div class="row">
<div class="col-sm-10 col-sm-push-1 box-tab">
<h2></h2>
</div>
</div>
</div><!-- /.page-content /.container -->
<?php include('_footer.php'); ?>
<file_sep><?php
$pageTitle = "Virtual Tours - Ft. Walton Temple Mound";
include('_header.php');
?>
<div class="page-content container">
<div class="row">
<div class="page-header">
<h1>Virtual Tours</h1>
</div>
<div class="col-sm-10 col-sm-push-1 box-tab">
<h2>Fort Walton Temple Mound</h2>
<div class="videoWrapper">
<iframe width="560" height="315" src="//www.youtube.com/embed/d8APisFcyos" frameborder="0" allowfullscreen></iframe>
</div>
<p>The large mound and village site within the community of Fort Walton Beach gained the attention of antiquarians and archaeologists well over 100 years ago. This site is the namesake of Fort Walton archaeological culture, which is found over a large territory in Florida and surrounding states and is characterized by impressive mounds and elaborate pottery. Though much of the village site has been built over since its initial rediscovery by archaeologists, the large temple mound remains and is preserved by the City of Fort Walton Beach.</p>
<h3>Did You Know...</h3>
<ul>
<li>The Fort Walton Temple Mound, built between 800 and 1400 A.D., is a National Historic Landmark.</li>
<li>Exhibits depict 12,000 years of Native American history; the museum features more than 6,000 ceramic artifacts and contains the finest collection of Fort Walton Period ceramics in the Southeastern U.S.</li>
<li>Artifacts from early explorers, settlers, and Civil War soldiers are also on display at three other museums on the site. These include two historic buildings that are included in one admission price.</li>
</ul>
<br/>
<a href="http://fwb.org/museums/" class="btn btn-md btn-primary center-block" target="_blank">Fort Walton Temple Mound<br/> Museum Website</a>
<br/>
<p class="text-center">139 Miracle Strip Pkwy, Fort Walton Beach, FL 32548</p>
</div>
</div>
</div><!-- /.page-content /.container -->
<?php include('_footer.php'); ?>
<file_sep><?php
$pageTitle = "";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1><strong>Public Notice<u></u><u></u></strong></h1></th>
</tr>
<tr>
<td class="table_mid">
<p>
</p>
<h2 align="center"><strong>Florida Public Archaeology Network Open Meeting</strong></h2>
<p><strong>Date and Time:</strong></p>
<p>The Florida Public Archaeology Network will hold a conference call to review strategic plan progress on November 28, 2011, 2 p.m. EDT and will last approximately one hour. The public is invited to attend.<u></u></p>
<p><strong>General Subject Matter to be Considered:</strong></p>
<p>
This is a meeting of the Development Committee to discuss staff assignments to meet strategic goals. An agenda for this meeting will be available by contacting <NAME>.</p>
<p>Contact person: <NAME>, Director, Northeast Region, <a href="mailto:<EMAIL>"><EMAIL></a>,
904-819-6476 (Tel), 904-819-6499 (Fax)<br />
<br />
Pursuant to the provisions of the Americans with Disabilities Act, any persons requiring special accommodations to attend these meetings is requested to contact the Flagler ADA Office at
1-904-819-6476 at least 48 hours before each meeting.</p>
<p> </p>
<p><br />
The Florida Public Archaeology Network announces a telephone conference call to which all persons are invited.<br />
<strong>DATE AND TIME: </strong> December 4, 2012 at 11:00 a.m. EST<br />
<br />
<strong>PLACE: </strong> Flagler College, 25 Markland Place, St. Augustine, FL 32085<br />
<br />
<strong>GENERAL SUBJECT MATTER TO BE CONSIDERED: </strong> To discuss Goal 11 in FPAN’s strategic plan. The goal is to secure private funding sources to assist with the implementation of FPAN programs. A copy of the agenda may be obtained by contacting <NAME>, Director for FPAN Northeast Region at email: <a href="mailto:<EMAIL>"><EMAIL></a> or phone: (904) 819-6476<a name="_GoBack" id="_GoBack"></a>.</p>
<p><u></u> </p>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php include 'header.htm' ?>
<h2>Photo / Media Gallery</h2>
<h3>Port of Veracruz</h3>
<p><img src="images/gallery/port-of-veracruz.jpg" alt="Port of Veracruz" /></p>
<h3>El Tajin</h3>
<p><img src="images/gallery/bense-el-tajin1.08.jpg" alt="El Tajin" /></p>
<h3>Caption?</h3>
<p><img src="images/gallery/krista-and-angel-rental-day.jpg" alt="Caption?" /></p>
<?php include 'footer.htm' ?><file_sep><?php
$table = 'events';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Florida Archaeology Month<?php if($pageTitle){echo " - ".$pageTitle;} ?></title>
<meta name="DESCRIPTION" content="Florida Archaeology Month: Every March, statewide programs and events celebrating Florida Archaeology Month are designed to encourage Floridians and visitors to learn more about the archaeology and history of the state, and to preserve these important parts of Florida's rich cultural heritage.">
<meta name="KEYWORDS" content="florida, archaeology, month, florida archaeology, florida archaeology month, FAM, FAM 2012">
<link rel="stylesheet" type="text/css" href="http://flpublicarchaeology.org/FAM/style.css" media="all" />
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-7301672-15']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body id="radial-center">
<div id="main">
<div id="header">
<img src="http://flpublicarchaeology.org/FAM/images/header.jpg" alt="Florida Archaeology Month" />
</div>
<div id="navbar">
<p align="center"> <img src="http://flpublicarchaeology.org/FAM/images/line_left.png" />
<a href="http://flpublicarchaeology.org/FAM">About</a> <img src="http://flpublicarchaeology.org/FAM/images/seperator.png" />
<a href="http://flpublicarchaeology.org/FAM/eventEdit.php">Submit Event</a> <img src="http://flpublicarchaeology.org/FAM/images/seperator.png" />
<a href="http://flpublicarchaeology.org/FAM/eventList.php">Events</a> <img src="http://flpublicarchaeology.org/FAM/images/seperator.png" />
<a href="http://flpublicarchaeology.org/FAM/links.php">Links</a> <img src="http://flpublicarchaeology.org/FAM/images/seperator.png" />
<a href="http://flpublicarchaeology.org/FAM/archives.php">Archives</a> <img src="http://flpublicarchaeology.org/FAM/images/line_right.png" />
</p>
</div>
<div class="clearFloat"></div>
<file_sep><?php
setOption("images_per_page",50,false);
setOption("albums_per_page",999,false);
$firstPageImages = setThemeColumns(1, 4);
$np = getOption('images_per_page');
if ($firstPageImages > 0) {
$firstPageImages = $firstPageImages - 1;
$myimagepagestart = 1;
} else {
$firstPageImages = $np - 1;
$myimagepagestart = 0;
}
$_zp_conf_vars['images_first_page'] = $firstPageImages;
$myimagepage = $myimagepagestart + getCurrentPage() - getTotalPages(true);
if ($myimagepage > 1 ) {
$link_slides = 2;
} else {
$link_slides = 1;
}
setOption('images_per_page', $np - $link_slides, false);
$_zp_conf_vars['images_first_page'] = NULL;
setOption('custom_index_page', 'gallery', false);
?><file_sep><?php
$pageTitle = "Home";
$bg = array('jumbotron.jpg','jumbotron2.jpg' ); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
include('_header.php');
?>
<!-- page-content begins -->
<div class="page-content container">
<!-- Row One -->
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="col-sm-12">
<div class="jumbotron hidden-xs" style="background: url(images/<?php echo $selectedBg; ?>) 40% no-repeat;"></div>
</div>
<div class="col-md-7">
<h2>Announcements</h2>
<div class="box-tab announcements-box">
<p class="text-center">No current announcements!</p>
</div>
<div class="box-dash">
<p>The <span class="h4">Northwest Region</span> serves Escambia, Santa Rosa, Okaloosa, Walton, Holmes,
Washington, Bay, Jackson, Calhoun, and Gulf Counties.</p>
<!-- Interactive SVG Map -->
<div class="center-block hidden-xs" id="nwmap"></div>
<img class="img-responsive visible-xs" src="images/nw_counties_map.svg" />
<p>The Northwest Region of the Florida Public Archaeology Network is hosted by
the University of West Florida in Pensacola, and it shares offices with the
Network Coordinating Center in the historic L&N Marine Terminal at 207 East Main St.</p>
<img src="images/lnterminal.jpg" class="img-responsive img-circle center-block"/>
</div>
</div><!-- /.col -->
<div class="col-md-5">
<h2>Upcoming Events</h2>
<div class="box-tab events-box">
<!-- Non-mobile list (larger) -->
<div class="hidden-xs">
<?php
$regionArray = array($table);
echoUpcomingEventsBox($regionArray,5);
?>
</div>
<!-- Mobile events list -->
<div class="visible-xs">
<?php
$regionArray = array($table);
echoUpcomingEventsBox($regionArray,3);
?>
</div>
<p class="text-center">
<a class="btn btn-primary btn-sm" href="eventList.php">View more</a>
</p>
</div>
<h3>Newsletter <small>Signup</small></h3>
<form role="form" method="get" action="newsletter.php">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="email" placeholder="<EMAIL>">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div><!-- /.col -->
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div> <!-- /.col -->
</div><!-- /.row one -->
<div class="row">
<div class="col-md-4">
<div class="region-callout-box nw-volunteer">
<h1>Volunteer</h1>
<p>Opportunities to get your hands dirty.</p>
<a href="volunteer.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="region-callout-box nw-explore">
<h1>Explore</h1>
<p>Discover historical and archaeological sites!</p>
<a href="explore.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="region-callout-box nw-speakers">
<h1>Speakers</h1>
<p>Request a speaker for your meeting or event.</p>
<a href="presentations.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
</div><!-- /.row two -->
</div><!-- /.page-content /.container-fluid -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#nwmap').mapSvg({
source: 'images/nw_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //Northwest Region Marker
xy:[58,165],
tooltip:'Northwest Regional Center & Coordinating Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Escambia' :{popover:'<h3>Escambia</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=escambia">Explore Escambia County</a></p>'},
'Santa_Rosa' :{popover:'<h3>Santa Rosa</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=santarosa">Explore Santa Rosa County</a></p>'},
'Okaloosa' :{popover:'<h3>Okaloosa</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=okaloosa">Explore Okaloosa County</a></p>'},
'Walton' :{popover:'<h3>Walton</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=walton">Explore Walton County</a></p>'},
'Holmes' :{popover:'<h3>Holmes</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=holmes">Explore Holmes County</a></p>'},
'Washington' :{popover:'<h3>Washington</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=washington">Explore Washington County</a></p>'},
'Bay' :{popover:'<h3>Bay</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=bay">Explore Bay County</a></p>'},
'Gulf' :{popover:'<h3>Gulf</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=gulf">Explore Gulf County</a></p>'},
'Jackson' :{popover:'<h3>Jackson</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=jackson"> Explore Jackson County</a></p>'},
'Calhoun' :{popover:'<h3>Calhoun</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=calhoun"> Explore Calhoun County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
include 'header.php';
//Assign URL variables
$typeActivity = $_GET['typeActivity'];
$regionLimit = $_POST['regionLimit'];
$displayLimit = $_POST['displayLimit'];
// Combine individual date form elements into a formatted start and end date
if(($_POST['startYear'] != NULL) || ($_POST['endYear'] != NULL)){
$startDate = $_POST['startYear']."-".$_POST['startMonth']."-".$_POST['startDay'];
$endDate = $_POST['endYear']."-".$_POST['endMonth']."-".$_POST['endDay'];
}
//If form was reset or this is the first page load, assign default values
if(($_POST['reset']) || !($_POST['submit'])){
unset($_POST);
$startDate = NULL;
$endDate = NULL;
$displayLimit = 25;
$regionLimit = "All";
}
//Get proper title string
$title = getTitle($typeActivity);
?>
<table width="700" border="0" cellspacing="2" align="center" >
<tr>
<td valign="top">
<div align="center">
<span>
<table cellspacing="15" class="limitOptions">
<thead>
<tr>
<th colspan="4">Filter Results:</th>
</tr>
</thead>
<tr>
<td>
<form action="<?php echo curPageUrl(); ?>" method="post">
<label class="description" for="element_1">Start Date </label>
<span>
<input id="element_1_1" name="startMonth" class="element text" size="2" maxlength="2" value="<?php echo $_POST['startMonth']; ?>" type="text" >
-
</span> <span>
<input id="element_1_2" name="startDay" class="element text" size="2" maxlength="2" value="<?php echo $_POST['startDay']; ?>" type="text">
-
</span> <span>
<input id="element_1_3" name="startYear" class="element text" size="4" maxlength="4" value="<?php echo $_POST['startYear']; ?>" type="text">
</span> <span id="calendar_1"> <img id="cal_img_1" class="datepicker" src="images/calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</td>
<td>
<label class="description" for="element_2">End Date </label>
<span>
<input id="element_2_1" name="endMonth" class="element text" size="2" maxlength="2" value="<?php echo $_POST['endMonth']; ?>" type="text">
-
</span> <span>
<input id="element_2_2" name="endDay" class="element text" size="2" maxlength="2" value="<?php echo $_POST['endDay']; ?>" type="text" >
-
</span> <span>
<input id="element_2_3" name="endYear" class="element text" size="4" maxlength="4" value="<?php echo $_POST['endYear']; ?>" type="text" >
</span> <span id="calendar_2"> <img id="cal_img_2" class="datepicker" src="images/calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_2_3",
baseField : "element_2",
displayArea : "calendar_2",
button : "cal_img_2",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</td>
<td>
<?php if(isAdmin()){?>
<label class="description"> Region </label>
<select name="regionLimit">
<option <?php if($_POST['reset']) echo "selected=\"selected\"" ?>>All</option>
<option value="nwrc" <?php if($regionLimit == "nwrc") echo "selected=\"selected\"" ?>>Northwest</option>
<option value="ncrc" <?php if($regionLimit == "ncrc") echo "selected=\"selected\"" ?>>North Central</option>
<option value="nerc" <?php if($regionLimit == "nerc") echo "selected=\"selected\"" ?>>Northeast</option>
<option value="wcrc" <?php if($regionLimit == "wcrc") echo "selected=\"selected\"" ?>>West Central</option>
<option value="crc" <?php if($regionLimit == "crc") echo "selected=\"selected\"" ?>>Central</option>
<option value="ecrc" <?php if($regionLimit == "ecrc") echo "selected=\"selected\"" ?>>East Central</option>
<option value="swrc" <?php if($regionLimit == "swrc") echo "selected=\"selected\"" ?>>Southwest</option>
<option value="serc" <?php if($regionLimit == "serc") echo "selected=\"selected\"" ?>>Southeast</option>
</select>
<?php } ?>
</td>
<td>
<label class="description" >Limit Results </label>
<select name="displayLimit" >
<option <?php if($displayLimit == 25) echo "selected=\"selected\"" ?> value="25">25</option>
<option <?php if($displayLimit == 50) echo "selected=\"selected\"" ?> value="50">50</option>
<option <?php if($displayLimit == 100) echo "selected=\"selected\"" ?> value="100">100</option>
<option <?php if($displayLimit == 250) echo "selected=\"selected\"" ?> value="250">250</option>
<option <?php if($displayLimit == 500) echo "selected=\"selected\"" ?> value="500">500</option>
<option <?php if(($displayLimit == 'All')||($displayLimit > 500)||($_POST['reset'])) echo "selected=\"selected\"" ?> value="9999999999">All</option>
</select>
</td>
</tr>
<tr><td colspan="4" style="text-align:center;">
<input type="submit" name="submit" value="Apply Filter"/>
<input type="submit" name="reset" value="Reset Filter"/>
</form>
</td>
</tr></table>
<br/>
<hr/>
<h2 align="center"><?php echo $title; ?></h2>
<?php
if(in_array($typeActivity, getTypeActivityArray())){
// ******** Print out all of the activity results that meet specified criteria *******
printActivities($typeActivity, $displayLimit, $startDate, $endDate, $regionLimit);
}else{
// ******** Print out all of the service results that meet specified criteria *******
printservices($typeActivity, $displayLimit, $startDate, $endDate, $regionLimit);
}
?>
</div>
</td>
</tr>
</table>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "Workshops - Project Archaeology";
include('../_header.php');
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1> Workshops, <small>Project Archaeology</small></h1>
<h3>Investigating Shelter</h3>
</div>
<div class="col-lg-8 col-lg-push-2 col-sm-10 col-sm-push-1 box-tab box-line row">
<div class="col-sm-12 text-center">
<div class="image">
<img class="img-responsive" src="images/inservice.jpg" width="600" height="357" alt="FPAN staff demonstrates activity for teachers" >
<p>FPAN staff demonstrates activity for teachers</p>
</div>
</div>
<p>
Archaeology is an extremely multi-disciplinary social science, and teachers can use the lure of the past to engage students in math, science, history, social studies, language arts, fine arts, and critical thinking. FPAN archaeologists can provide archaeology-themed in-service workshops for K-12 teachers in all subjects. Schedules range from half-day to multi-day, and include both lecture instruction and hands-on activities featuring archaeology-based lesson plans, activities, and projects that teachers can easily adapt for their classrooms.</p>
<p>All information and curricula presented directly relate to Common Core and Sunshine State Standards. Teachers receive workbooks, lesson plans, activity instructions, topics for discussion and writing assignments, CDs containing PowerPoint presentations, and PDF documents of additional material for classroom use. In-service workshops can also focus on the <a href="http://www.projectarchaeology.org">Project Archaeology</a> series of lessons.</p>
<p>
FPAN staff are happy to work with District Subject Coordinators to make sure educators receive in-service credits.</p>
<div class="col-sm-6">
<img class="img-responsive" src="images/classroomBackpack.png" width="326" height="311" >
</div>
<div class="col-sm-6">
<p>
<h3>Previous participants say:</h3>
</p>
<p><em>“I believe that the lessons provided and demonstrated will be easily implemented and are excellent examples of Common Core objectives.</em>”</p>
<p class="text-right">- <strong>Leon County Teacher</strong></p>
<p><em>“Very useful to my specific needs.”</em></p>
<p class="text-right">- <strong>Walton County Educator</strong></p>
<p><em>“Florida is a cultural wonderland-Thank you for putting it into a teachable format for teachers.” </em></p>
<p class="text-right">- <strong>Bay County Teacher</strong></p>
<p><em>“I always like workshops that provide me with activities that I can immediately take back and use-thanks!”</em> </p>
<p class="text-right">- <strong>Wakulla County Teacher</strong></p>
</div>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
/**
* This is Zenphoto's unified comment handling facility
*
* Place a call on the function <var>printCommentForm()</var> in your script where you
* wish the comment items to appear.
*
* The plugin uses <var>%ZENFOLDER%/%PLUGIN_FOLDER%/comment_form/comment_form.php</var>.
* However, you may override this form by placing a script of the same name in a similar folder in your theme.
* This will allow you to customize the appearance of the comments on your site.
*
* There are several options to tune what the plugin will do.
*
* @author <NAME> (sbillard)
* @package plugins
*/
$plugin_is_filter = 5 | CLASS_PLUGIN;
$plugin_description = gettext("Provides a unified comment handling facility.");
$plugin_author = "<NAME> (sbillard)";
$option_interface = 'comment_form';
zp_register_filter('admin_toolbox_global', 'comment_form::toolbox');
require_once(SERVERPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/comment_form/class-comment.php');
require_once(SERVERPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/comment_form/functions.php');
if (OFFSET_PATH) {
zp_register_filter('admin_overview', 'comment_form_print10Most');
zp_register_filter('admin_tabs', 'comment_form::admin_tabs');
} else {
zp_register_filter('handle_comment', 'comment_form_postcomment');
zp_register_filter('object_addComment', 'comment_form_addComment');
if (getOption('comment_form_pagination')) {
zp_register_filter('theme_head', 'comment_form_PaginationJS');
}
if (getOption('tinymce4_comments')) {
require_once(SERVERPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/tinymce4.php');
zp_register_filter('theme_head', 'comment_form_visualEditor');
}
}
class comment_form {
/**
* class instantiation function
*
*/
function comment_form() {
setOptionDefault('email_new_comments', 1);
setOptionDefault('comment_name_required', 'required');
setOptionDefault('comment_email_required', 'required');
setOptionDefault('comment_web_required', 'show');
setOptionDefault('Use_Captcha', false);
setOptionDefault('comment_form_addresses', 0);
setOptionDefault('comment_form_require_addresses', 0);
setOptionDefault('comment_form_members_only', 0);
setOptionDefault('comment_form_albums', 1);
setOptionDefault('comment_form_images', 1);
setOptionDefault('comment_form_articles', 1);
setOptionDefault('comment_form_pages', 1);
setOptionDefault('comment_form_rss', 1);
setOptionDefault('comment_form_private', 1);
setOptionDefault('comment_form_anon', 1);
setOptionDefault('comment_form_showURL', 1);
setOptionDefault('comment_form_comments_per_page', 10);
setOptionDefault('comment_form_pagination', true);
setOptionDefault('comment_form_toggle', 1);
setOptionDefault('tinymce4_comments', 'comment-ribbon.js.php');
}
/**
* Reports the supported options
*
* @return array
*/
function getOptionsSupported() {
global $_zp_captcha;
require_once(SERVERPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/tinymce4.php');
$checkboxes = array(gettext('Albums') => 'comment_form_albums', gettext('Images') => 'comment_form_images');
if (extensionEnabled('zenpage')) {
$checkboxes = array_merge($checkboxes, array(gettext('Pages') => 'comment_form_pages', gettext('News') => 'comment_form_articles'));
}
$configarray = getTinyMCE4ConfigFiles('comment');
$options = array(
gettext('Enable comment notification') => array('key' => 'email_new_comments', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 0,
'desc' => gettext('Email the Admin when new comments are posted')),
gettext('Name field') => array('key' => 'comment_name_required', 'type' => OPTION_TYPE_RADIO,
'order' => 0.1,
'buttons' => array(gettext('Omit') => 0, gettext('Show') => 1, gettext('Require') => 'required'),
'desc' => gettext('If the <em>Name</em> field is required, the poster must provide a name.')),
gettext('Email field') => array('key' => 'comment_email_required', 'type' => OPTION_TYPE_RADIO,
'order' => 0.2,
'buttons' => array(gettext('Omit') => 0, gettext('Show') => 1, gettext('Require') => 'required'),
'desc' => gettext('If the <em>Email</em> field is required, the poster must provide an email address.')),
gettext('Website field') => array('key' => 'comment_web_required', 'type' => OPTION_TYPE_RADIO,
'order' => 0.3,
'buttons' => array(gettext('Omit') => 0, gettext('Show') => 1, gettext('Require') => 'required'),
'desc' => gettext('If the <em>Website</em> field is required, the poster must provide a website.')),
gettext('Captcha field') => array('key' => 'Use_Captcha', 'type' => OPTION_TYPE_RADIO,
'order' => 0.4,
'buttons' => array(gettext('Omit') => 0, gettext('For guests') => 2, gettext('Require') => 1),
'desc' => ($_zp_captcha->name) ? gettext('If <em>Captcha</em> is required, the form will include a Captcha verification.') : '<span class="notebox">' . gettext('No captcha handler is enabled.') . '</span>'),
gettext('Address fields') => array('key' => 'comment_form_addresses', 'type' => OPTION_TYPE_RADIO,
'order' => 7,
'buttons' => array(gettext('Omit') => 0, gettext('Show') => 1, gettext('Require') => 'required'),
'desc' => gettext('If <em>Address fields</em> are shown or required, the form will include positions for address information. If required, the poster must supply data in each address field.')),
gettext('Allow comments on') => array('key' => 'comment_form_allowed', 'type' => OPTION_TYPE_CHECKBOX_ARRAY,
'order' => 0.9,
'checkboxes' => $checkboxes,
'desc' => gettext('Comment forms will be presented on the checked pages.')),
gettext('Toggled comment block') => array('key' => 'comment_form_toggle', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 2,
'desc' => gettext('If checked, existing comments will be initially hidden. Clicking on the provided button will show them.')),
gettext('Show author URL') => array('key' => 'comment_form_showURL', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 7,
'desc' => gettext('To discourage SPAM, uncheck this box and the author URL will not be revealed.')),
gettext('Only members can comment') => array('key' => 'comment_form_members_only', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 4,
'desc' => gettext('If checked, only logged in users will be allowed to post comments.')),
gettext('Allow private postings') => array('key' => 'comment_form_private', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 6,
'desc' => gettext('If checked, posters may mark their comments as private (not for publishing).')),
gettext('Allow anonymous posting') => array('key' => 'comment_form_anon', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 5,
'desc' => gettext('If checked, posters may exclude their personal information from the published post.')),
gettext('Include RSS link') => array('key' => 'comment_form_rss', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 8,
'desc' => gettext('If checked, an RSS link will be included at the bottom of the comment section.')),
gettext('Comments per page') => array('key' => 'comment_form_comments_per_page', 'type' => OPTION_TYPE_TEXTBOX,
'order' => 9,
'desc' => gettext('The comments that should show per page on the admin tab and when using the jQuery pagination')),
gettext('Comment editor configuration') => array('key' => 'tinymce4_comments', 'type' => OPTION_TYPE_SELECTOR,
'order' => 1,
'selections' => $configarray,
'null_selection' => gettext('Disabled'),
'desc' => gettext('Configuration file for TinyMCE when used for comments. Set to <code>Disabled</code> to disable visual editing.')),
gettext('Pagination') => array('key' => 'comment_form_pagination', 'type' => OPTION_TYPE_CHECKBOX,
'order' => 3,
'desc' => gettext('Uncheck to disable the jQuery pagination of comments. Enabled by default.')),
);
return $options;
}
function handleOption($option, $currentValue) {
}
static function admin_tabs($tabs) {
if (zp_loggedin(COMMENT_RIGHTS)) {
$add = true;
$newtabs = array();
foreach ($tabs as $key => $tab) {
if ($add && !in_array($key, array('overview', 'edit', 'upload', 'pages', 'news', 'tags', 'menu'))) {
$newtabs['comments'] = array('text' => gettext("comments"),
'link' => WEBPATH . "/" . ZENFOLDER . '/' . PLUGIN_FOLDER . '/' . 'comment_form/admin-comments.php?page=comments&tab=' . gettext('comments'),
'subtabs' => NULL);
$add = false;
}
$newtabs[$key] = $tab;
}
return $newtabs;
}
return $tabs;
}
static function toolbox() {
if (zp_loggedin(COMMENT_RIGHTS)) {
?>
<li>
<?php printLinkHTML(WEBPATH . "/" . ZENFOLDER . '/' . PLUGIN_FOLDER . '/' . 'comment_form/admin-comments.php?page=comments&tab=' . gettext('comments'), gettext("Comments"), NULL, NULL, NULL); ?>
</li>
<?php
}
}
}
/**
* Prints a form for posting comments
*
* @param bool $showcomments defaults to true for showing list of comments
* @param string $addcommenttext alternate text for "Add a comment:"
* @param bool $addheader set true to display comment count header
* @param string $comment_commententry_mod use to add styles, classes to the comment form div
* @param bool $desc_order default false, set to true to change the comment order to descending ( = newest to oldest)
*/
function printCommentForm($showcomments = true, $addcommenttext = NULL, $addheader = true, $comment_commententry_mod = '', $desc_order = false) {
global $_zp_gallery_page, $_zp_current_admin_obj, $_zp_current_comment, $_zp_captcha, $_zp_authority, $_zp_HTML_cache, $_zp_current_image, $_zp_current_album, $_zp_current_zenpage_page, $_zp_current_zenpage_news;
if (getOption('email_new_comments')) {
$email_list = $_zp_authority->getAdminEmail();
if (empty($email_list)) {
setOption('email_new_comments', 0);
}
}
if (is_null($addcommenttext))
$addcommenttext = '<h3>' . gettext('Add a comment:') . '</h3>';
switch ($_zp_gallery_page) {
case 'album.php':
if (!getOption('comment_form_albums'))
return;
$obj = $_zp_current_album;
break;
case 'image.php':
if (!getOption('comment_form_images'))
return;
$obj = $_zp_current_image;
break;
case 'pages.php':
if (!getOption('comment_form_pages'))
return;
$obj = $_zp_current_zenpage_page;
break;
case 'news.php':
if (!getOption('comment_form_articles') || !is_NewsArticle())
return;
$obj = $_zp_current_zenpage_news;
break;
default:
return;
break;
}
$comments_open = $obj->getCommentsAllowed();
?>
<!-- printCommentForm -->
<div id="commentcontent">
<?php
$num = getCommentCount();
if ($showcomments) {
if ($num == 0) {
if ($addheader)
echo '<h3 class="empty">' . gettext('No Comments') . '</h3>';
$display = '';
} else {
if ($addheader)
echo '<h3>' . sprintf(ngettext('%u Comment', '%u Comments', $num), $num) . '</h3>';
if (getOption('comment_form_toggle')) {
?>
<div id="comment_toggle"><!-- place holder for toggle button --></div>
<script type="text/javascript">
// <!-- <![CDATA[
function toggleComments(hide) {
if (hide) {
$('div.comment').hide();
$('.Pagination').hide();
$('#comment_toggle').html('<button class="button buttons" onclick="javascript:toggleComments(false);"><?php echo gettext('show comments'); ?></button>');
} else {
$('div.comment').show();
$('.Pagination').show();
$('#comment_toggle').html('<button class="button buttons" onclick="javascript:toggleComments(true);"><?php echo gettext('hide comments'); ?></button>');
}
}
$(document).ready(function() {
toggleComments(window.location.hash.search(/#zp_comment_id_/));
});
// ]]> -->
</script>
<?php
$display = ' style="display:none"';
} else {
$display = '';
}
}
$hideoriginalcomments = '';
if (getOption('comment_form_pagination') && COMMENTS_PER_PAGE < $num) {
$hideoriginalcomments = ' style="display:none"'; // hide original comment display to be replaced by jQuery pagination
}
if (getOption('comment_form_pagination') && COMMENTS_PER_PAGE < $num) {
?>
<div class="Pagination"></div><!-- this is the jquery pagination nav placeholder -->
<div id="Commentresult"></div>
<?php
}
?>
<div id="comments"<?php echo $hideoriginalcomments; ?>>
<?php
while (next_comment($desc_order)) {
if (!getOption('comment_form_showURL')) {
$_zp_current_comment['website'] = '';
}
?>
<div class="comment" <?php echo $display; ?>>
<div class="commentinfo">
<h4 id="zp_comment_id_<?php echo $_zp_current_comment['id']; ?>"><?php printCommentAuthorLink(); ?>: <?php echo gettext('on'); ?> <?php
echo getCommentDateTime();
printEditCommentLink(gettext('Edit'), ', ', '');
?></h4>
</div><!-- class "commentinfo" -->
<div class="commenttext"><?php echo html_encodeTagged(getCommentBody(), false); ?></div><!-- class "commenttext" -->
</div><!-- class "comment" -->
<?php
}
?>
</div><!-- id "comments" -->
<?php
}
if (getOption('comment_form_pagination') && COMMENTS_PER_PAGE < $num) {
?>
<div class="Pagination"></div><!-- this is the jquery pagination nav placeholder -->
<?php
}
?>
<!-- Comment Box -->
<?php
if ($comments_open) {
if (MEMBERS_ONLY_COMMENTS && !zp_loggedin(POST_COMMENT_RIGHTS)) {
echo gettext('Only registered users may post comments.');
} else {
$disabled = array('name' => '', 'website' => '', 'anon' => '', 'private' => '', 'comment' => '',
'street' => '', 'city' => '', 'state' => '', 'country' => '', 'postal' => '');
$stored = array_merge(array('email' => '', 'custom' => ''), $disabled, getCommentStored());
$custom = getSerializedArray($stored['custom']);
foreach ($custom as $key => $value) {
if (!empty($value))
$stored[$key] = $value;
}
foreach ($stored as $key => $value) {
$disabled[$key] = false;
}
if (zp_loggedin()) {
if (extensionEnabled('userAddressFields')) {
$address = userAddressFields::getCustomData($_zp_current_admin_obj);
foreach ($address as $key => $value) {
if (!empty($value)) {
$disabled[$key] = true;
$stored[$key] = $value;
}
}
}
$name = $_zp_current_admin_obj->getName();
if (!empty($name)) {
$stored['name'] = $name;
$disabled['name'] = ' disabled="disabled"';
} else {
$user = $_zp_current_admin_obj->getUser();
if (!empty($user)) {
$stored['name'] = $user;
$disabled['name'] = ' disabled="disabled"';
}
}
$email = $_zp_current_admin_obj->getEmail();
if (!empty($email)) {
$stored['email'] = $email;
$disabled['email'] = ' disabled="disabled"';
}
if (!empty($address['website'])) {
$stored['website'] = $address['website'];
$disabled['website'] = ' disabled="disabled"';
}
}
$data = zp_apply_filter('comment_form_data', array('data' => $stored, 'disabled' => $disabled));
$disabled = $data['disabled'];
$stored = $data['data'];
foreach ($data as $check) {
foreach ($check as $v) {
if ($v) {
$_zp_HTML_cache->disable(); // shouldn't cache partially filled in pages
break 2;
}
}
}
if (!empty($addcommenttext)) {
echo $addcommenttext;
}
?>
<div id="commententry" <?php echo $comment_commententry_mod; ?>>
<?php
$theme = getCurrentTheme();
$form = getPlugin('comment_form/comment_form.php', $theme);
require($form);
?>
</div><!-- id="commententry" -->
<?php
}
} else {
?>
<div id="commententry">
<h3><?php echo gettext('Closed for comments.'); ?></h3>
</div><!-- id="commententry" -->
<?php
}
?>
</div><!-- id="commentcontent" -->
<?php
if (getOption('comment_form_rss') && getOption('RSS_comments')) {
?>
<br class="clearall" />
<?php
if (class_exists('RSS')) {
switch ($_zp_gallery_page) {
case "image.php":
printRSSLink("Comments-image", "", gettext("Subscribe to comments"), "");
break;
case "album.php":
printRSSLink("Comments-album", "", gettext("Subscribe to comments"), "");
break;
case "news.php":
printRSSLink("Comments-news", "", gettext("Subscribe to comments"), "");
break;
case "pages.php":
printRSSLink("Comments-page", "", gettext("Subscribe to comments"), "");
break;
}
}
}
?>
<!-- end printCommentForm -->
<?php
}
?><file_sep><?php
$pageTitle = "Newsletter";
$email = isset($_GET['email']) ? $_GET['email'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle;?></h1>
</div>
<!-- Begin MailChimp Signup Form -->
<div class="col-sm-10 col-sm-push-1">
<form action="//flpublicarchaeology.us8.list-manage.com/subscribe/post?u=2467dd10db27544829dddb7f6&id=8d9114ddcd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<h2>Join our mailing list</h2>
<div class="form-group">
<label class="control-label " for="mce-EMAIL">Email Address</label>
<div class="row">
<div class="col-xs-10">
<input type="email" value="<?=$email?>" name="EMAIL" class="form-control" id="mce-EMAIL">
</div>
<div class="col-xs-2">
<span class="required">*</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label" for="mce-FNAME">First Name </label>
<input type="text" value="" name="FNAME" class="form-control" id="mce-FNAME">
</div>
<div class="form-group">
<label class="control-label" for="mce-LNAME">Last Name </label>
<input type="text" value="" name="LNAME" class="form-control" id="mce-LNAME">
</div>
<div class="form-group">
<label class="control-label">County </label>
<ul>
<li><input type="radio" value="Alachua" name="MMERGE3" id="mce-MMERGE3-0"><label for="mce-MMERGE3-0">Alachua</label></li>
<li><input type="radio" value="Bradford" name="MMERGE3" id="mce-MMERGE3-1"><label for="mce-MMERGE3-1">Bradford</label></li>
<li><input type="radio" value="Citrus" name="MMERGE3" id="mce-MMERGE3-2"><label for="mce-MMERGE3-2">Citrus</label></li>
<li><input type="radio" value="Gilchrist" name="MMERGE3" id="mce-MMERGE3-3"><label for="mce-MMERGE3-3">Gilchrist</label></li>
<li><input type="radio" value="Hernando" name="MMERGE3" id="mce-MMERGE3-4"><label for="mce-MMERGE3-4">Hernando</label></li>
<li><input type="radio" value="Lake" name="MMERGE3" id="mce-MMERGE3-5"><label for="mce-MMERGE3-5">Lake</label></li>
<li><input type="radio" value="Levy" name="MMERGE3" id="mce-MMERGE3-6"><label for="mce-MMERGE3-6">Levy</label></li>
<li><input type="radio" value="Marion" name="MMERGE3" id="mce-MMERGE3-7"><label for="mce-MMERGE3-7">Marion</label></li>
<li><input type="radio" value="Sumter" name="MMERGE3" id="mce-MMERGE3-8"><label for="mce-MMERGE3-8">Sumter</label></li>
</ul>
</div>
<div class="form-group">
<label class="control-label" >Category</label>
<ul>
<li><input type="radio" value="Volunteer/Avocational" name="MMERGE4" id="mce-MMERGE4-0"><label for="mce-MMERGE4-0">Volunteer/Avocational</label></li>
<li><input type="radio" value="Heritage Professional" name="MMERGE4" id="mce-MMERGE4-1"><label for="mce-MMERGE4-1">Heritage Professional</label></li>
<li><input type="radio" value="Land Manager/Planner" name="MMERGE4" id="mce-MMERGE4-2"><label for="mce-MMERGE4-2">Land Manager/Planner</label></li>
<li><input type="radio" value="Teacher/Edicator" name="MMERGE4" id="mce-MMERGE4-3"><label for="mce-MMERGE4-3">Teacher/Edicator</label></li>
<li><input type="radio" value="Other Interested Person" name="MMERGE4" id="mce-MMERGE4-4"><label for="mce-MMERGE4-4">Other Interested Person</label></li>
</ul>
</div>
<div id="mce-responses">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_2467dd10db27544829dddb7f6_8d9114ddcd" tabindex="-1" value=""></div>
<div class="text-center">
<input class="btn btn-primary" type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">
</div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[3]='MMERGE3';ftypes[3]='radio';fnames[4]='MMERGE4';ftypes[4]='radio';}(jQuery));var $mcj = jQuery.noConflict(true);</script> <!--End mc_embed_signup-->
<!-- <div class="box-tab col-sm-12">
<h2>Newsletter Archives</h2>
</div>/.col -->
</div><!-- /.col /.row -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep>
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th class="sm_header"><h1>Options</h1></th>
</tr>
<tr>
<td class="table_mid">
<ul>
<li><a href="adminHome.php">Overview</a></li>
<?php
if($region == "wcrc")
echo '<li><a href="http://www.flpublicarchaeology.org/blog/wcrc/wp-login.php" target="_blank"> Blog </a></li>';
if($region == "ncrc")
echo '<li><a href="http://www.flpublicarchaeology.org/blog/ncrc/wp-login.php" target="_blank"> Blog </a></li>';
if($region == "crc")
echo '<li><a href="http://www.flpublicarchaeology.org/blog/crc/wp-login.php" target="_blank"> Blog </a></li>';
if($region == "serc")
echo '<li><a href="http://www.flpublicarchaeology.org/blog/serc/wp-login.php" target="_blank"> Blog </a></li>';
?>
<li>Events</li>
<ul>
<li><a href="eventEdit.php">Add</a></li>
<li><a href="eventList.php">View/Edit</a></li>
<li><a href="eventArchive.php">Archive</a></li>
</ul>
<li><a href="http://www.flpublicarchaeology.org/gallery/zp-core/admin.php" target="_blank">Photo Gallery</a></li>
<li><a href="http://www.flpublicarchaeology.org/newsletter/<?=$newsletter?>/" target="_blank">Newsletter</a></li>
<li><a href="http://www.flpublicarchaeology.org/mollify/" target="_blank">File Sharing (FTP site)</a></li>
<li><a href="upload.php">File Upload</a></li>
<!-- <li><a href="settings.php">Settings</a></li>-->
<li><a href="index.php?logout=1">Logout</a></li>
</ul></td>
</tr>
<tr>
<td class="sm_bottom"></td>
</tr>
</table>
<file_sep><?php
if (!defined('WEBPATH')) die();
$firstPageImages = setThemeColumns('2', '6');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s').' GMT');
$pageTitle = " - " . getBareAlbumTitle();
include 'header.php';
zp_apply_filter("theme_head");
?>
<!-- Main Left Side -->
<div id="left_side">
<div id="navbar">
<div id="navbar_top"> </div>
<div id="album_container">
<ul class="album_ul">
<li><a href="http://flpublicarchaeology.org/civilwar">Home</a></li>
<li><a href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=http:%2F%2Fwww.flpublicarchaeology.org%2Fcivilwar%2Fsites.kmz&sll=37.0625,-95.677068&sspn=58.72842,135.263672&ie=UTF8&t=h&ll=28.960089,-83.748779&spn=5.689017,9.371338&z=7" target="_blank">Map of Sites</a></li>
<li><a href="http://flpublicarchaeology.org/links.php#civilwar">Sesquicentennial Links</a></li>
</ul>
<img src="http://www.flpublicarchaeology.org/images/nav_div.png" width="180" height="4" alt="divider"/>
<?php printAlbumMenuList("list","","","active_album","album_ul","active_album","");?>
</div>
<div id="navbar_bottom"> </div>
</div>
<!-- <table class="newsletter_table" cellpadding="0" cellspacing="0">
<tr>
<th class="newsletter_header"></th>
</tr>
<tr>
<td class="newsletter_table_mid">
</td>
</tr>
<tr>
<td class="newsletter_bottom"></td>
</tr>
</table>-->
</div>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header">
<h1>
<?php printAlbumTitle(true);?>
</h1>
</th>
</tr>
<tr>
<td class="table_mid">
<!-- <div align="center">
<a href="<?php //echo htmlspecialchars(getGalleryIndexURL());?>" title="<?php //echo gettext('Albums Index'); ?>">
<small>All Albums</small></a> | <small><?php //printParentBreadcrumb(); ?></small>
</div> -->
<p><?php printAlbumDesc(true); ?></p>
<div id="albums">
<?php while (next_album()): ?>
<div class="album">
<div class="thumb">
<a href="<?php echo htmlspecialchars(getAlbumLinkURL());?>" title="<?php echo gettext('View album:'); ?>
<?php echo getBareAlbumTitle();?>"><?php printAlbumThumbImage(getBareAlbumTitle()); ?></a>
</div>
<div class="albumdesc">
<strong><a class="dark" href="<?php echo htmlspecialchars(getAlbumLinkURL());?>" title="<?php echo gettext('View album:'); ?>
<?php echo getBareAlbumTitle();?>"><?php printAlbumTitle(); ?></a></strong>
<small><?php //printAlbumDate(""); ?></small>
<p><?php //printAlbumDesc(); ?></p>
</div>
<p style="clear: both; "></p>
</div>
<?php endwhile; ?>
</div>
<br/>
<div id="images">
<?php while (next_image(false, $firstPageImages)): ?>
<div class="image">
<div class="imagethumb">
<a href="<?php echo htmlspecialchars(getImageLinkURL());?>" title="<?php echo getBareImageTitle();?>">
<?php printImageThumb(getAnnotatedImageTitle()); ?></a>
</div>
</div>
<?php endwhile; ?>
</div>
<br/>
<div align="center">
<?php printPageListWithNav("« ".gettext("prev"), gettext("next")." »"); ?>
</div>
<div id="credit">
<?php if (function_exists('printUserLogin_out'))
printUserLogin_out(" | ");
?>
</div>
<?php printAdminToolbox(); ?>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?>
<file_sep><?php
$pageTitle = "Then and Now: Life Along the New River";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Then and Now: Life Along the New River</h1></th>
</tr>
<tr>
<td class="table_mid">
<div id="exhibit">
<?php include 'nav.php'?>
<h2 align="center">Film</h2>
<p><strong>South Florida’s mild climate and tropical scenery makes it an ideal setting for filmmaking.</strong> From its earliest development until today, Fort Lauderdale has been scouted for its location.</p>
<p>
<img src="images/exhibit2.jpg" alt="Famed early movie producer and director, <NAME>,
used the New River as a backdrop for several movies. <br/>Image courtesy of the Fort Lauderdale History Center" style="float:right; margin-left:10px" />
<br/>In 1919 filming began on The Idol Dancer; the first movie shot using the New River as a backdrop. The unspoiled, wild scenery of the New River was used to represent the movie’s supposed South Seas locale.
<br />
<img src="images/exhibit1.jpg" style="float:left; margin-right:10px; margin-top:10px;" alt="<NAME> steers a canoe for a member of the movie crew. <br/>
Image courtesy of Fort Lauderdale Historical Society" />
</p>
<p> </p>
<p> </p>
<p>Director <NAME> hired local Seminole Indians as extras in the movie. Young Seminole, <NAME>, served as an interpreter between the Seminole actors and the film crew. In addition to providing employment to local residents, The Idol Dancer gave exposure to the fledgling city of Fort Lauderdale.<br />
</p>
<p> </p>
<p> </p>
<p> </p>
<p><img src="images/exhibit3.jpg" style="float:left; margin-right:10px" alt="<NAME> and <NAME> take a break on the set of Where the Boys
Are, the 1960 film that cemented Fort Lauderdale's reputation as a college
spring break destination. <br/>
Caption and Image courtesy of Fort Lauderdale Historical Society, Gene Hyde Collection." /></p>
<p> </p>
<p>In the 1960s, Where the Boys Are created new buzz for the Fort Lauderdale area. The movie centered on three college friends and their quest for the perfect spring break. The movie identified the otherwise quiet town of Fort Lauderdale as the ultimate spring break destination. The movie inspired countless college students across the nation to flock south in search of sun and fun.</p>
<p>The city continued to be depicted as a spring break destination in movies like Girl Happy (1965), starring Elvis Presley, forever securing Fort Lauderdale as a spring break hot spot. </p>
<p> </p>
<p> </p>
<p> </p>
<p><strong>The same reasons that brought D.W. Griffith to Fort Lauderdale continue to draw filmmakers and movie stars here today.</strong> Since 2000, the film industry in Broward has contributed over 200 million dollars to the local economy. The New River recently provided a setting for movies such as Marley and Me (2008), Rock of Ages (2012) and for television series, including Burn Notice and The Glades.</p></td>
</div>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?>
<file_sep><?php
$pageTitle = "Virtual Tours - Arcadia Mill";
include('_header.php');
?>
<div class="page-content container">
<div class="page-header">
<h1>Virtual Tours</h1>
</div>
<div class="row">
<div class="col-sm-10 col-sm-push-1 box-tab">
<h2>Arcadia Mill Archaeological Site</h2>
<h4>American Territorial Period (1821 - 1845) - Early Statehood & Antebellum Period (1845 - 1860)</h4>
<img src="images/arcadiasign.jpg" alt="Arcadia Mill Welcome Sign" class="img-responsive">
<h3>Milton, Santa Rosa County</h3>
<p>The Arcadia Mill Archaeological Site represents the largest 19th-century water-powered industrial complex in Northwest Florida. Between 1817 and 1855 this was the site of a multi-faceted operation that included a sawmill, lumber mill, grist mill, shingle mill, and cotton textile mill. Additional buildings rounded out this complex, including housing for enslaved female workers, a kitchen, storehouse, blacksmith shop, and community well. Arcadia Mill offers the visitor an historical experience as well as the opportunity to visit a unique wetland ecosystem. Today the site is open to the public and managed by the UWF Historic Trust. It includes a visitor center, museum, and outdoor exhibits. Free guided tours are available.</p>
<img src="images/arcadiaboardwalk.jpg" alt="Arcadia Mill Boardwalk" class="img-responsive">
<h3>Did You Know...</h3>
<ul>
<li>The University of West Florida Department of Anthropology and Archaeology Institute holds field schools at the site every summer. </li>
<li>Elevated board walk with interpretive waysides leads visitors through the archaeological remains of the mills, across Pond Creek, and through adjacent swamps.</li>
<li>Historical newspapers indicate that in 1840 forty female slaves were purchased from Virginia to work in the textile mill. By 1850 African American men and children lived and worked at the site.</li>
</ul>
<img src="images/arcadiainside.jpg" alt="Inside the Arcadia Mill museum" class="img-responsive">
<br/>
<a href="http://www.historicpensacola.org/arcadia.cfm" class="btn btn-primary btn-md center-block" target="_blank">Arcadia Mill Website</a>
<br/>
<p class="text-center">5709 Mill Pond Lane in Milton, Florida.</p>
</div>
</div>
</div><!-- /.page-content /.container -->
<?php include('_footer.php'); ?>
<file_sep><?php include('_header.php'); ?>
<!-- page-content begins -->
<div class="container">
<div class="row">
</div><!-- /.row -->
</div><!-- /.page-content /.container -->
<?php include('_footer.php'); ?>
<file_sep><?php
$pageTitle = "Timucuan Technology";
include('../../_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-10 col-sm-push-1 row">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="col-sm-8 col-sm-push-2 box-dash">
<p> Resources for students and instructions for teachers for exploring northeast Florida's prehistory through biotechnology. See below for full chapters or download the entire book here:</p>
<p><a target="_blank" href="Timucuan Tech_4.pdf">Timucuan Technology</a> (60 MB)</p>
<p> <a target="_blank" href="teacher pages/teacherPagesCombined.pdf">Instructions for Teachers</a> (3 MB)</p>
<p>Alignment with Sunshine State Standards, answer keys, activity tips, references, recommended reading. </p>
</div>
</div>
<div class="box-tab row">
<div class="col-sm-12">
<img src="images/timutech.svg" alt="" class="img-responsive"/>
</div>
<div class="col-md-6">
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image002.jpg" alt="" width="52" height="52">
<p><strong>Intro</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li>
<a target="_blank" href="1a_intro.pdf"> Introduction—Who Were the Timucua? </a>
</li>
</ul>
</div><!-- /Intro Lesson -->
</div>
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image004.jpg" alt="" width="61" height="60" >
<p><strong>Lesson 1</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li>
<a target="_blank" href="1b_debry.pdf">De Bry—Fact or Fiction?</a>
</li>
<li>
<a target="_blank" href="teacher pages/teacher_1.pdf">Teacher Pages </a>
</li>
</ul>
</div>
</div><!-- /1 Lesson /.row -->
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image006.jpg" alt="" width="65" height="59">
<p><strong>Lesson 2</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li>
<a target="_blank" href="2_pyro.pdf">Pyrotechnology </a>
</li>
<li>
<a target="_blank" href="teacher pages/teacher_2.pdf">Teacher Pages </a>
</li>
</ul>
<p>Video: <a target="_blank" href="http://www.youtube.com/watch?v=LnXnuNMWE1I&list=PLuzZGqqA6qjcs_lDlxrFboatnEj60McZ9">Fire Drill</a></p>
<p>Video: <a target="_blank" href="http://www.youtube.com/watch?v=U6bALofxDOQ">Pyro & Balloons</a></p>
</div>
</div><!-- /2 Lesson /.row -->
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image008.jpg" alt="" width="69" height="73">
<p><strong>Lesson 3</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li><a target="_blank" href="3_tool.pdf">Tool-Making Technology</a></li>
<li><a target="_blank" href="teacher pages/teacher_3.pdf">Teacher Pages</a></li>
</ul>
<p>Video: <a target="_blank" href="http://www.youtube.com/watch?v=U6bALofxDOQ">Soap Carving </a></p>
</div>
</div><!-- /3 Lesson /.row -->
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image010.jpg" alt="" width="69" height="73">
<p><strong>Lesson 4</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li><a target="_blank" href="4_animal.pdf">Animal Technology</a></li>
<li><a target="_blank" href="teacher pages/teacher_4.pdf">Teacher Pages</a></li>
</ul>
</div>
</div><!-- /4 Lesson /.row -->
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image012.jpg" alt="" width="67" height="66" >
<p><strong>Lesson 5</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li><a target="_blank" href="5_wild.pdf"> Wild Plant Technology</a></li>
<li><a target="_blank" href="teacher pages/teacher_5.pdf">Teacher Pages</a></li>
</ul>
<p>Video: <a target="_blank" href="http://www.youtube.com/watch?v=Xev3ZjDvZaQ">Cord Making</a></p>
</div>
</div><!-- /5 Lesson /.row -->
</div><!--/.col --> <!-- /.row -->
<div class="col-md-6">
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image014.jpg" alt="" width="69" height="72"/>
<p><strong>Lesson 6</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li><a target="_blank" href="6_agri.pdf">Agricultural Technology</a></li>
<li><a target="_blank" href="teacher pages/teacher_6.pdf">Teacher Pages </a></li>
</ul>
</div>
</div><!-- /6 Lesson /.row -->
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image016.jpg" alt="" width="75" height="77"/>
<p><strong>Lesson 7</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li><a target="_blank" href="7_build.pdf">Building Technology</a></li>
<li><a target="_blank" href="teacher pages/teacher_7.pdf">Teacher Pages</a></li>
</ul>
<p>Video: <a target="_blank" href="http://www.youtube.com/watch?v=xgGYuL0Nnlw">Thatching</a></p>
<p>Video: <a target="_blank" href="http://www.youtube.com/watch?v=NLcs9T2I1Uc">Making a Weir</a></p>
</div>
</div><!-- /7 Lesson /.row -->
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image018.jpg" alt="" width="74" height="67" />
<p><strong>Lesson 8</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li><a target="_blank" href="8_archy.pdf">Archaeological Technology</a></li>
<li><a target="_blank" href="teacher pages/teacher_8.pdf">Teacher Pages</a></li>
<p>Video: <a target="_blank" href="http://www.youtube.com/watch?v=SAPLd9Kwl_s">Excavation </a></p>
</ul>
</div>
</div><!-- /8 Lesson /.row -->
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image020.jpg" alt="" width="75" height="70" />
<p><strong>Lesson 9</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li><a target="_blank" href="9_archyB.pdf">Archaeology—Beyond Excavation</a></li>
<li><a target="_blank" href="teacher pages/teacher_9.pdf">Teacher Pages</a></li>
<p>Video: <a target="_blank" href="http://www.youtube.com/watch?v=yTu2iS5SvZg">Canoes</a></p>
</ul>
</div>
</div><!-- /9 Lesson /.row -->
<div class="lesson row">
<div class="col-sm-3 text-center">
<img src="images/clip_image022.jpg" alt="" width="75" height="69" hspace="12" />
<p><strong>Lesson 10</strong></p>
</div>
<div class="col-sm-9 links">
<ul>
<li><a target="_blank" href="10_hist.pdf">History and the Timucua</a></li>
<li><a target="_blank" href="teacher pages/teacher_10.pdf">Teacher Pages</a></li>
</ul>
</div>
</div><!-- /10 Lesson /.row -->
</div><!--/.col --> <!--/.row -->
</div><!--/.row -->
<div class="col-sm-12 box-dash">
<p class="text-center">
<NAME>, <em>Author and Educational Consultant</em><br/>
<NAME>, <em>Project Director</em><br/>
<NAME>, <em>Graphic Designer</em><br/>
<NAME>, <em>Contributor</em><br/>
<NAME>, <em>Contributor</em><br/>
And thank you to Dr. <NAME> and Dr. <NAME> for their etensive contributions to the project.
</p>
<p>
<em>This project has been financed in part with historic preservation grant assistance provided by the Bureau of Historic Preservation, Division of Historical Resources, Florida Department of State, assisted by the Florida Historical Commission. However, the contents and opinions do not necessarily reflect the views and opinions of the Florida Department of State, nor does the mention of trade names or commercial products constitute endorsement or recommendation by the Florida Department of State.</em>
</p>
<h3>Contact</h3>
<h4><NAME></h4>
<p class="text-center">
Northeast Regional Center<br/>
74 King Street<br/>
St. Augustine, Florida 32085-1027<br/>
(904) 819-6476<br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
</p>
</div>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('../../_footer.php'); ?><file_sep><?php
$allEmployeeSql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($allEmployeeSql);
//if this is a new event, clear any potential leftover form data
if($_GET['new'])
$_SESSION['formVars'] = "";
//If event ID is supplied in URL, this event is being edited. Gather info from database and populate form.
if($_GET['id']){
$_SESSION['edit'] = true;
$_SESSION['editID'] = $_GET['id'];
$_SESSION['oldStaffInvolved'] = array();
$id = $_SESSION['editID'];
//Get event info from database
$sql = "SELECT * FROM $table WHERE id = '$id';";
$results = mysql_query($sql);
//Set form variables
if(mysql_num_rows($results) != 0)
$formVars = mysql_fetch_assoc($results);
//Set form date variables
$dateString = strtotime($formVars['activityDate']);
$formVars['month'] = date("m", $dateString);
$formVars['day'] = date("d", $dateString);
$formVars['year'] = date("Y", $dateString);
//Get staffInvolved array from EmployeeActivity table, also store in a second array for comparison after edits
$sql = "SELECT employeeID FROM EmployeeActivity
WHERE activityID = '$id'";
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results)){
$formVars['staffInvolved'][] = $row['employeeID'];
$_SESSION['oldStaffInvolved'][] = $row['employeeID'];
}
}
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true){
$formVars = $_SESSION['formVars'];
$activityDate = $formVars['activityDate'];
$activityName = $formVars['activityName'];
$county = $formVars['county'];
$city = $formVars['city'];
$partners = $formVars['partners'];
$typeActivity = $formVars['typeActivity'];
$audience = $formVars['audience'];
$numberAttendees = $formVars['numberAttendees'];
$amountIncome = $formVars['amountIncome'];
//******************************************* This is a NEW activity *******************************************
if(!$_SESSION['edit']){
//Insert new Activity ID
$sql = "INSERT INTO Activity VALUES (NULL);";
if(!mysql_query($sql))
echo ' Error: ' . mysql_error()."<br/>";
//Insert activity info with new Activity ID
$sql = "INSERT INTO $table (id, submit_id, activityDate, activityName, county, city, partners, typeActivity, audience, numberAttendees, amountIncome)
VALUES (LAST_INSERT_ID(), '$_SESSION[my_id]', '$activityDate', '$activityName', '$county', '$city', '$partners', '$typeActivity', '$audience', '$numberAttendees', '$amountIncome');";
if(!mysql_query($sql))
echo ' Error: ' . mysql_error()."<br/>";
//For each staff member checked, insert entry into EmployeeActivity to associate that employee with this activity
foreach($formVars['staffInvolved'] as $staff){
$sql = "INSERT INTO EmployeeActivity VALUES ($staff, LAST_INSERT_ID());";
if(!mysql_query($sql))
echo ' Error: ' . mysql_error()."<br/>";
}
//******************************************* This is an activity edit *******************************************
}else{
$id = $_SESSION['editID'];
//Update event info
$sql = "UPDATE $table
SET activityDate = '$activityDate',
activityName = '$activityName',
county = '$county',
city = '$city',
partners = '$partners',
typeActivity = '$typeActivity',
audience = '$audience',
numberAttendees = '$numberAttendees',
amountIncome = '$amountIncome'
WHERE id = '$id'";
if(!mysql_query($sql)){
$err = true;
$msg .= ' Error: ' . mysql_error()."<br/>";
}
//Compare old staff involved array to new one. Delete any entries not in new array.
foreach($_SESSION['oldStaffInvolved'] as $staffID){
if(!in_array($staffID, $formVars['staffInvolved'])){
$sql = "DELETE FROM EmployeeActivity WHERE employeeID = '$staffID' AND activityID = '$id'";
if(!mysql_query($sql))
echo 'Error: ' . mysql_error()."<br/>";
}
}
//Compare new staff involved array to old one. Add any staff not in the old array.
foreach($formVars['staffInvolved'] as $staffID){
if(!in_array($staffID, $_SESSION['oldStaffInvolved'])){
$sql = "INSERT INTO EmployeeActivity VALUES ('$staffID', '$id');";
if(!mysql_query($sql))
echo 'Error: ' . mysql_error()."<br/>";
}
}
}
//If there were no erorrs while inserting: Clear temporary event array, reset editing flag, display success message
if($err != true){
$_SESSION['formVars'] = "";
$_SESSION['edit'] = false;
$_SESSION['editID'] = 0;
$_SESSION['oldStaffInvolved'] = "";
$msg = "Activity was successfully logged!";
}
?>
<div class="summary"> <br/>
<br/>
<?php echo "<h3>".$msg."</h3>"; ?> <br/>
<br/>
<br/>
<br/>
<a href="<?php echo $_SERVER['PHP_SELF']; ?>">Enter another Public Outreach activity</a> or
<a href="main.php">return to main menu</a>. <br/>
<br/>
</div>
<?php } ?>
<?php
//Form has been submitted. Process form submission.
if(isset($_POST['submit']) && !isset($_POST['confirmSubmission'])){
// Sanitize Data
foreach($_POST as $var){
$var = mysql_real_escape_string(addslashes($var));
}
//Store POST form variables in local array, convert date to one variable
$formVars['activityDate'] = $formVars['year'] ."-". $formVars['month'] ."-". $formVars['day'];
$formVars = array_merge($formVars,$_POST);
//Store in session variable
$_SESSION['formVars'] = $formVars;
//Before inserting into database, check for correctness and ask for confirmation
echo "<br/><br/>";
echo "<div class=\"summary\"> <br/><br/><div style=\"text-align:left; margin-left:100px;\">";
//Loop formVars array and print key and value of each element
foreach($formVars as $key=> $value){
if(($key != 'id')&&($key != 'submit')&&($key != 'month')&&($key != 'day')&&($key != 'year')&&($key != 'staffInvolved')&&($key != 'submit_id')){
$varName = ucfirst($key);
$varName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $varName);
echo "<strong>".$varName.": </strong>".$value."<br/>";
}
}
//Display staff involved.
echo "<strong>The staff involved:</strong> <br/>";
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName']." ".$employee['lastName'];
if(in_array($employee['id'], $formVars['staffInvolved']))
echo "<span style=\"margin-left:10px;\">". $employeeName."</span><br/>";
}
echo "</div>";
?>
<br/>
<br/>
If any of this is incorrect, please <a href="<?php echo $_SERVER['PHP_SELF']; ?>"> go back and correct it</a>. <br/>
<br/>
Otherwise, please confirm your submission: <br/>
<br/>
<form id="submissionForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<input type="hidden" name="confirmSubmission" value="true" />
<input type="submit" name="submit" value="Confirm" />
</form>
<br/>
<br/>
</div>
<?php } ?><file_sep><?php
include 'header.php';
$table = 'PublicOutreach';
$excludeKeys = array('id', 'month', 'day', 'year', 'staffInvolved', 'submit', 'submit_id');
//if this is a new event, clear any potential leftover form data
if($_GET['new'])
$_SESSION['formVars'] = "";
//If event ID is supplied in URL, this event is being edited. Gather info from database and populate form.
if($_GET['id']){
$_SESSION['edit'] = true;
$_SESSION['editID'] = $_GET['id'];
$_SESSION['oldStaffInvolved'] = array();
//Get event info from database
$sql = "SELECT * FROM $table WHERE id = '$_SESSION[editID]';";
$results = mysql_query($sql);
//Set form variables
if(mysql_num_rows($results) != 0)
$formVars = mysql_fetch_assoc($results);
//Set form date variables
$dateString = strtotime($formVars['activityDate']);
$formVars['month'] = date("m", $dateString);
$formVars['day'] = date("d", $dateString);
$formVars['year'] = date("Y", $dateString);
//Get staffInvolved array from EmployeeActivity table, also store in a second array for comparison after edits
$sql = "SELECT employeeID FROM EmployeeActivity
WHERE activityID = '$_SESSION[editID]'";
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results)){
$formVars['staffInvolved'][] = $row['employeeID'];
$_SESSION['oldStaffInvolved'][] = $row['employeeID'];
}
}
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true){
$formVars = $_SESSION['formVars'];
//******************************************* This is a NEW activity *******************************************
if(!$_SESSION['edit']){
//Insert new Activity ID
$sql = "INSERT INTO Activity VALUES (NULL);";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
//For each staff member checked, insert entry into EmployeeActivity to associate that employee with this activity
foreach($formVars['staffInvolved'] as $staff){
$sql = "INSERT INTO EmployeeActivity VALUES ($staff, LAST_INSERT_ID());";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
}
//Remove any formVars not going into the database
foreach($formVars as $key => $value)
if(in_array($key, $excludeKeys))
unset($formVars[$key]);
//Make arrays of just keys and just values
$formKeys = array_keys($formVars);
$formValues = array_values($formVars);
//Generate SQL from form variables
$sql = "INSERT INTO $table (id, submit_id, ";
foreach($formKeys as $key){
$sql .= $key;
if($key != end($formKeys))
$sql .= ", ";
}
$sql .= ") ";
$sql .= "VALUES (LAST_INSERT_ID(), '$_SESSION[my_id]', ";
foreach($formValues as $value){
$sql .= "'".$value."'";
if($value != end($formValues))
$sql .= ", ";
}
$sql .= ");";
//Run query
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
$msg = "Activity was successfully logged!";
//******************************************* This is an activity edit *******************************************
}else{
//Compare old staff involved array to new one. Delete any entries not in new array.
foreach($_SESSION['oldStaffInvolved'] as $staffID){
if(!in_array($staffID, $formVars['staffInvolved'])){
$sql = "DELETE FROM EmployeeActivity WHERE employeeID = '$staffID' AND activityID = '$_SESSION[editID]'";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
}
}
//Compare new staff involved array to old one. Add any staff not in the old array.
foreach($formVars['staffInvolved'] as $staffID){
if(!in_array($staffID, $_SESSION['oldStaffInvolved'])){
$sql = "INSERT INTO EmployeeActivity VALUES ('$staffID', '$_SESSION[editID]');";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
}
}
//Remove any formVars not going into the database
foreach($formVars as $key => $value)
if(in_array($key, $excludeKeys))
unset($formVars[$key]);
//Update event info
$sql = "UPDATE $table SET ";
foreach($formVars as $key => $value){
$sql .= " ".$key." = '".$value."'";
if($value != end($formVars))
$sql .= ", ";
}
$sql .= " WHERE id = '$_SESSION[editID]';";
if(!mysql_query($sql)){
$err = true;
$msg .= ' Error: ' . mysql_error()."<br/>";
}
$msg = "Activity was successfully edited!";
}
//If there were no erorrs while inserting: Clear temporary event array, reset editing flag, display success message
if($err != true){
$_SESSION['formVars'] = "";
$_SESSION['edit'] = false;
$_SESSION['editID'] = 0;
$_SESSION['oldStaffInvolved'] = "";
}
?>
<div class="summary"> <br/>
<br/>
<?php echo "<h3>".$msg."</h3>"; ?> <br/>
<br/>
<br/>
<br/>
<a href="<?php echo $_SERVER['PHP_SELF']; ?>">Enter another Public Outreach activity</a> or
<a href="main.php">return to main menu</a>. <br/>
<br/>
</div>
<?php } ?>
<br/><br/>
<div class=\"summary\">
<br/><br/>
<?php
//Form has been submitted but not confirmed. Display input values to check for accuracy
if(isset($_POST['submit']) && !isset($_POST['confirmSubmission'])){
// Sanitize Data
foreach($_POST as $var){
$var = mysql_real_escape_string(addslashes($var));
}
//Store POST form variables in local array, convert date to one variable
$formVars['activityDate'] = $_POST['year'] ."-". $_POST['month'] ."-". $_POST['day'];
$formVars = array_merge($formVars,$_POST);
//Store in session variable
$_SESSION['formVars'] = $formVars;
//Before inserting into database, check for correctness and ask for confirmation
echo "<div style=\"text-align:left; margin-left:100px;\">";
//Loop formVars array and print key and value of each element
foreach($formVars as $key=> $value){
if(!in_array($key, $excludeKeys)){
$varName = ucfirst($key);
$varName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $varName);
echo "<strong>".$varName.": </strong>".$value."<br/>";
}
}
//Display staff involved.
$sql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($sql);
echo "<strong>The staff involved:</strong> <br/>";
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName']." ".$employee['lastName'];
if(in_array($employee['id'], $formVars['staffInvolved']))
echo "<span style=\"margin-left:10px;\">". $employeeName."</span><br/>";
}
echo "</div>";
?>
<br/>
<br/>
If any of this is incorrect, please <a href="<?php echo $_SERVER['PHP_SELF']; ?>"> go back and correct it</a>. <br/>
<br/>
Otherwise, please confirm your submission: <br/>
<br/>
<form id="submissionForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<input type="hidden" name="confirmSubmission" value="true" />
<input type="submit" name="submit" value="Confirm" />
</form>
<br/>
<br/>
</div>
<?php }elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="publicOutreach" class="appnitro" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form_description">
<h2>Public Outreach</h2>
<p>Please fill out the information below to log this activity.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text" required="required">
/
<label for="element_1_1">MM</label>
</span> <span>
<input id="element_1_2" name="day" class="element text" size="2" maxlength="2" value="<?php echo $formVars['day']; ?>" type="text" required="required">
/
<label for="element_1_2">DD</label>
</span> <span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text" required="required">
<a class="red">*</a>
<label for="element_1_3">YYYY</label>
</span> <span id="calendar_1"> <img id="cal_img_1" class="datepicker" src="images/calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</li>
<li id="li_12" >
<label class="description" for="element_12">Name of Activity/Event</label>
<div>
<input id="element_12" name="activityName" class="element text" size="40" maxlength="100" value="<?php echo $formVars['activityName']; ?>" type="text" required="required">
<a class="red">*</a></div>
</li>
<li id="li_7" >
<label class="description" for="element_7">Type of Activity</label>
<div>
<select class="element select medium" id="element_7" name="typeActivity" required="required">
<option value="" selected="selected"></option>
<option <?php if($formVars['typeActivity'] == "lecture/presentation") echo "selected=\"selected\""; ?> value="lecture/presentation" >lecture/presentation</option>
<option <?php if($formVars['typeActivity'] == "infobooth") echo "selected=\"selected\""; ?> value="infobooth" >infobooth</option>
<option <?php if($formVars['typeActivity'] == "exhibit") echo "selected=\"selected\""; ?> value="exhibit" >exhibit</option>
<option <?php if($formVars['typeActivity'] == "tour") echo "selected=\"selected\""; ?> value="tour" >tour</option>
<option <?php if($formVars['typeActivity'] == "volunteer event") echo "selected=\"selected\""; ?> value="volunteer event" >volunteer event</option>
<option <?php if($formVars['typeActivity'] == "FPAN event") echo "selected=\"selected\""; ?> value="FPAN event" >FPAN event</option>
<option <?php if($formVars['typeActivity'] == "youth activity") echo "selected=\"selected\""; ?> value="youth activity" >youth activity</option>
<option <?php if($formVars['typeActivity'] == "demo") echo "selected=\"selected\""; ?> value="demo" >demo</option>
<option <?php if($formVars['typeActivity'] == "other activity") echo "selected=\"selected\""; ?> value="other activity" >other</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_11" >
<label class="description" for="element_11">Target Audience</label>
<div>
<select class="element select medium" id="element_11" name="audience" required="required">
<option value="" selected="selected"></option>
<option <?php if($formVars['audience'] == "local") echo "selected=\"selected\""; ?> value="local" >local</option>
<option <?php if($formVars['audience'] == "state") echo "selected=\"selected\""; ?> value="state" >state</option>
<option <?php if($formVars['audience'] == "regional") echo "selected=\"selected\""; ?> value="regional" >regional</option>
<option <?php if($formVars['audience'] == "national/international") echo "selected=\"selected\""; ?> value="national/international" >national/international</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_2" >
<label class="description" for="element_10">County </label>
<div>
<select class="element select medium" id="element_10" name="county" required="required">
<option value="" selected="selected"></option>
<option value="Alachua" <?php if($formVars['county'] == "Alachua") echo 'selected="selected"';?> >Alachua</option>
<option value="Baker" <?php if($formVars['county'] == "Baker") echo 'selected="selected"';?> >Baker</option>
<option value="Bay" <?php if($formVars['county'] == "Bay") echo 'selected="selected"';?> >Bay</option>
<option value="Bradford" <?php if($formVars['county'] == "Bradford") echo 'selected="selected"';?> >Bradford</option>
<option value="Brevard" <?php if($formVars['county'] == "Brevard") echo 'selected="selected"';?> >Brevard</option>
<option value="Broward" <?php if($formVars['county'] == "Broward") echo 'selected="selected"';?> >Broward</option>
<option value="Calhoun" <?php if($formVars['county'] == "Calhoun") echo 'selected="selected"';?> >Calhoun</option>
<option value="Charlotte" <?php if($formVars['county'] == "Charlotte") echo 'selected="selected"';?> >Charlotte</option>
<option value="Citrus" <?php if($formVars['county'] == "Citrus") echo 'selected="selected"';?> >Citrus</option>
<option value="Clay" <?php if($formVars['county'] == "Clay") echo 'selected="selected"';?> >Clay</option>
<option value="Collier" <?php if($formVars['county'] == "Collier") echo 'selected="selected"';?> >Collier</option>
<option value="Columbia" <?php if($formVars['county'] == "Columbia") echo 'selected="selected"';?> >Columbia</option>
<option value="DeSoto" <?php if($formVars['county'] == "DeSoto") echo 'selected="selected"';?> >DeSoto</option>
<option value="Dixie" <?php if($formVars['county'] == "Dixie") echo 'selected="selected"';?>>Dixie</option>
<option value="Duval" <?php if($formVars['county'] == "Duval") echo 'selected="selected"';?>>Duval</option>
<option value="Escambia" <?php if($formVars['county'] == "Escambia") echo 'selected="selected"';?>>Escambia</option>
<option value="Flagler" <?php if($formVars['county'] == "Flagler") echo 'selected="selected"';?>>Flagler</option>
<option value="Franklin" <?php if($formVars['county'] == "Franklin") echo 'selected="selected"';?>>Franklin</option>
<option value="Gadsden" <?php if($formVars['county'] == "Gadsden") echo 'selected="selected"';?>>Gadsden</option>
<option value="Gilchrist" <?php if($formVars['county'] == "Gilchrist") echo 'selected="selected"';?>>Gilchrist</option>
<option value="Glades" <?php if($formVars['county'] == "Glades") echo 'selected="selected"';?>>Glades</option>
<option value="Gulf" <?php if($formVars['county'] == "Gulf") echo 'selected="selected"';?>>Gulf</option>
<option value="Hamilton" <?php if($formVars['county'] == "Hamilton") echo 'selected="selected"';?>>Hamilton</option>
<option value="Hardee" <?php if($formVars['county'] == "Hardee") echo 'selected="selected"';?>>Hardee</option>
<option value="Hendry" <?php if($formVars['county'] == "Hendry") echo 'selected="selected"';?>>Hendry</option>
<option value="Hernando" <?php if($formVars['county'] == "Hernando") echo 'selected="selected"';?>>Hernando</option>
<option value="Highlands" <?php if($formVars['county'] == "Highlands") echo 'selected="selected"';?>>Highlands</option>
<option value="Hillsborough" <?php if($formVars['county'] == "Hillsborough") echo 'selected="selected"';?>>Hillsborough</option>
<option value="Holmes" <?php if($formVars['county'] == "Holmes") echo 'selected="selected"';?>>Holmes</option>
<option value="Indian River" <?php if($formVars['county'] == "Indian River") echo 'selected="selected"';?>>Indian River</option>
<option value="Jackson" <?php if($formVars['county'] == "Jackson") echo 'selected="selected"';?>>Jackson</option>
<option value="Jefferson" <?php if($formVars['county'] == "Jefferson") echo 'selected="selected"';?>>Jefferson</option>
<option value="Lafayette" <?php if($formVars['county'] == "Lafayette") echo 'selected="selected"';?>>Lafayette</option>
<option value="Lake" <?php if($formVars['county'] == "Lake") echo 'selected="selected"';?> >Lake</option>
<option value="Lee" <?php if($formVars['county'] == "Lee") echo 'selected="selected"';?>>Lee</option>
<option value="Leon" <?php if($formVars['county'] == "Leon") echo 'selected="selected"';?>>Leon</option>
<option value="Levy" <?php if($formVars['county'] == "Levy") echo 'selected="selected"';?>>Levy</option>
<option value="Liberty" <?php if($formVars['county'] == "Liberty") echo 'selected="selected"';?>>Liberty</option>
<option value="Madison" <?php if($formVars['county'] == "Madison") echo 'selected="selected"';?>>Madison</option>
<option value="Manatee" <?php if($formVars['county'] == "Manatee") echo 'selected="selected"';?>>Manatee</option>
<option value="Marion" <?php if($formVars['county'] == "Marion") echo 'selected="selected"';?>>Marion</option>
<option value="Martin"<?php if($formVars['county'] == "Martin") echo 'selected="selected"';?> >Martin</option>
<option value="Miami-Dade" <?php if($formVars['county'] == "Miami-Dade") echo 'selected="selected"';?>>Miami-Dade</option>
<option value="Monroe" <?php if($formVars['county'] == "Monroe") echo 'selected="selected"';?>>Monroe</option>
<option value="Nassau" <?php if($formVars['county'] == "Nassau") echo 'selected="selected"';?>>Nassau</option>
<option value="Okaloosa" <?php if($formVars['county'] == "Okaloosa") echo 'selected="selected"';?>>Okaloosa</option>
<option value="Okeechobee" <?php if($formVars['county'] == "Okeechobee") echo 'selected="selected"';?>>Okeechobee</option>
<option value="Orange" <?php if($formVars['county'] == "Orange") echo 'selected="selected"';?>>Orange</option>
<option value="Osceola" <?php if($formVars['county'] == "Osceola") echo 'selected="selected"';?>>Osceola</option>
<option value="Palm Beach" <?php if($formVars['county'] == "Palm Beach") echo 'selected="selected"';?>>Palm Beach</option>
<option value="Pasco" <?php if($formVars['county'] == "Pasco") echo 'selected="selected"';?>>Pasco</option>
<option value="Pinellas" <?php if($formVars['county'] == "Pinellas") echo 'selected="selected"';?>>Pinellas</option>
<option value="Polk" <?php if($formVars['county'] == "Polk") echo 'selected="selected"';?>>Polk</option>
<option value="Putnam" <?php if($formVars['county'] == "Putnam") echo 'selected="selected"';?>>Putnam</option>
<option value="Saint Johns" <?php if($formVars['county'] == "Saint Johns") echo 'selected="selected"';?>>Saint Johns</option>
<option value="Saint Lucie" <?php if($formVars['county'] == "Saint Lucie") echo 'selected="selected"';?>>Saint Lucie</option>
<option value="Santa Rosa" <?php if($formVars['county'] == "Santa Rosa") echo 'selected="selected"';?>>Santa Rosa</option>
<option value="Sarasota" <?php if($formVars['county'] == "Sarasota") echo 'selected="selected"';?>>Sarasota</option>
<option value="Seminole" <?php if($formVars['county'] == "Seminole") echo 'selected="selected"';?>>Seminole</option>
<option value="Sumter" <?php if($formVars['county'] == "Sumter") echo 'selected="selected"';?>>Sumter</option>
<option value="Suwannee" <?php if($formVars['county'] == "Suwannee") echo 'selected="selected"';?>>Suwannee</option>
<option value="Taylor" <?php if($formVars['county'] == "Union") echo 'selected="selected"';?>>Taylor</option>
<option value="Union" <?php if($formVars['county'] == "Union") echo 'selected="selected"';?>>Union</option>
<option value="Volusia" <?php if($formVars['county'] == "Volusia") echo 'selected="selected"';?>>Volusia</option>
<option value="Wakulla" <?php if($formVars['county'] == "Wakulla") echo 'selected="selected"';?>>Wakulla</option>
<option value="Walton" <?php if($formVars['county'] == "Walton") echo 'selected="selected"';?>>Walton</option>
<option value="Washington" <?php if($formVars['county'] == "Washington") echo 'selected="selected"';?>>Washington</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_3" >
<label class="description" for="element_3">City </label>
<div>
<input id="element_3" name="city" class="element text medium" type="text" maxlength="255" value="<?php echo $formVars['city']; ?>" required="required"/>
<a class="red">*</a></div>
</li>
<li id="li_4" >
<label class="description" for="element_4">Partners</label>
<div>
<input id="element_4" name="partners" class="element text medium" type="text" maxlength="255" value="<?php echo $formVars['partners']; ?>"/>
</div>
</li>
<li id="li_5" >
<?php include("staffInvolved.php"); ?>
</li>
<li id="li_8" >
<label class="description" for="element_8">Number of Attendees </label>
<div>
<input id="element_8" name="numberAttendees" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['numberAttendees']; ?>"/>
</div>
</li>
<li id="li_9" >
<label class="description" for="element_9">Amount of Income </label>
<div> $
<input id="element_9" name="amountIncome" class="element text small" type="text" maxlength="255" value="<?php echo $formVars['amountIncome']; ?>"/>
</div>
<p class="guidelines" id="guide_9"><small>Amount of money earned through fees or donations.</small></p>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close if ?>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body></html><file_sep><?php
$pageTitle = "Home";
include 'header.php';
require_once("../rss/rsslib.php");
$url = "http://www.flpublicarchaeology.org/blog/ncrc/feed/";
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Latest From the Blog</h1></th>
</tr>
<tr>
<td class="table_mid">
<?php echo RSS_Links($url, 2); ?>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Welcome to the North Central Region</h1></th>
</tr>
<tr>
<td class="table_mid">
<p align="center"><img src="http://www.flpublicarchaeology.org/ncrc/images/NorthCentralRegion.jpg" alt="North Central Region" border="0" usemap="#map_nc" style="border: 0;" />
<map name="map_nc">
<area shape="poly" alt="Explore Gulf County" coords="361,23,361,71,361,96,418,94,417,85,416,58,399,54,399,47,397,34,400,23" href="explore.php?county=baker" />
<area shape="poly" coords="350,164,350,163" href="#" />
<area shape="poly" coords="353,125,365,132,375,129,384,124,388,115,398,107,403,95,362,96,360,101,353,107,348,114,347,121" href="explore.php?county=union" />
<area shape="poly" coords="329,22,326,28,328,32,325,33,335,50,328,65,317,66,317,119,322,122,317,128,320,129,326,140,337,145,343,141,345,134,354,128,346,120,348,113,352,108,358,102,360,98,360,24" href="explore.php?county=columbia" />
<area shape="poly" coords="254,17,256,28,257,41,261,49,265,53,270,49,278,46,284,48,293,49,299,55,305,55,307,60,315,61,319,65,328,64,333,52,332,44,324,34,328,29,326,24,327,21" href="explore.php?county=hamilton" />
<area shape="poly" coords="315,66,315,120,319,123,316,128,306,135,299,134,298,126,292,118,280,108,273,102,265,102,259,100,257,94,254,77,260,68,259,62,266,53,272,48,280,49,290,49,295,56,302,57,307,62,313,63" href="explore.php?county=suwannee" />
<area shape="poly" coords="240,77,239,135,245,146,299,147,306,136,298,134,296,125,272,102,258,103,253,77" href="explore.php?county=lafayette" />
<area shape="poly" coords="246,148,300,147,298,152,296,164,296,177,298,185,293,194,292,202,282,217,281,222,270,228,262,216,258,210,250,210,245,201,237,201,235,194,235,185,233,181,235,170,242,170,242,158" href="explore.php?county=dixie" />
<area shape="poly" coords="193,13" href="#" />
<area shape="poly" coords="193,12,255,17,253,27,256,33,258,44,260,51,266,54,259,61,259,70,255,77,227,76,226,69,182,68,183,65,182,59,187,55,194,49,192,36" href="explore.php?county=madison" />
<area shape="poly" coords="179,70,169,76,165,85,157,101,159,109,165,109,177,120,187,120,187,125,196,129,204,142,209,144,211,154,213,161,220,162,222,168,234,170,239,169,241,163,244,156,245,147,238,136,239,77,225,76,224,70" href="explore.php?county=taylor" />
<area shape="poly" coords="192,12,155,11,155,24,158,28,158,34,150,34,150,42,146,48,146,102,156,101,169,76,181,67,182,58,193,49,191,37" href="explore.php?county=jefferson" />
<area shape="poly" coords="113,8,114,17,105,24,101,35,101,43,69,55,58,65,61,69,122,69,123,74,144,74,144,48,147,42,149,33,155,33,154,25,153,11" href="explore.php?county=leon" />
<area shape="poly" coords="42,4,36,12,32,20,37,21,38,31,49,32,51,44,60,45,61,51,65,51,62,56,64,60,85,49,101,43,102,28,107,22,112,17,114,8" href="explore.php?county=gadsden" />
<area shape="poly" coords="31,19,25,23,25,30,21,40,22,45,18,50,21,55,17,59,11,74,2,94,4,110,18,121,23,115,80,116,73,109,68,103,65,95,65,85,59,74,59,68,58,67,65,61,60,56,65,53,60,47,58,43,50,44,50,33,38,32,37,22" href="explore.php?county=liberty" />
<area shape="poly" coords="20,121,22,136,17,143,19,149,17,154,22,157,31,158,37,163,94,136,106,136,113,128,97,124,90,121,82,116,23,116" href="explore.php?county=franklin" />
<area shape="poly" coords="60,69,62,76,66,81,67,96,70,103,74,110,80,114,83,115,89,118,93,118,99,122,108,125,116,123,114,115,117,109,126,104,133,107,143,103,144,76,124,74,120,70" href="explore.php?county=wakulla" />
</map>
</p>
<p>
The North Central Region serves Franklin, Liberty, Gadsden, Leon, Wakulla, Jefferson, Madison, Taylor, Lafayette, Dixie, Suwannee, Hamilton, Columbia, Union and Baker Counties.
</p>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include '../events/eventBox.php'; ?><br/>
<!-- Twitter Feed Box -->
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th class="sm_header">
<a href="http://twitter.com/FPANnrthcentral" class="twitter">
<img src="http://flpublicarchaeology.org/images/twitter_bird.png" style="padding-left:25px; margin-right:-30px;" align="left"/>
<h1> Twitter Feed</h1></a>
</th>
</tr>
<tr>
<td class="table_mid">
<div align="center"><a href="http://twitter.com/FPANnorthwest">@FPANnrthcentral</a></div>
<ul id="twitter_update_list"><li>Twitter feed loading...</li></ul>
</td>
</tr>
<tr>
<td class="sm_bottom"></td>
</tr>
</table>
</div>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?>
<file_sep><?php
$pageTitle = "Home";
include 'dbConnect.php';
include 'header_dev.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<td class="lg_mid" style="vertical-align:top">
<h1 align="center"> Florida Archaeology Month 2013</h1>
<br/>
<div align="center"><img src="images/hrLine.png"/></div>
<br />
<p><strong>Florida's diverse history and prehistory stretches back over 12,000 years.</strong> Every March, statewide programs and events celebrating Florida Archaeology Month are designed to encourage Floridians and visitors to learn more about the archaeology and history of the state, and to preserve these important parts of Florida's rich cultural heritage. Plan to attend some of the many events throughout Florida during March 2013. A full listing of events can be found on the events page linked at the top of the page.</p>
<p align="center"><strong>Download the 2013 Archaeology Month Poster</strong><br />
<a href="posterArchives/2012-poster-front.jpg">2013 FAM Poster - Front</a><br/>
<a href="posterArchives/2012-poster-back.jpg">2013 FAM Poster - Back</a></p>
<p><strong>Florida Archaeology Month 2013</strong> explores the last 500 years of Florida history. Information about local events can be found on the Florida Anthropological Society (FAS) Website, and on local FAS chapter Websites that can be accessed from the main <a href="http://www.fasweb.org/index.html" target="_blank">FAS Webpage</a></p>
<p><strong>Florida Archaeology Month</strong> is coordinated by the Florida Anthropological Society, and supported by the Department of State, Division of Historical Resources. Additional sponsors for 2013 include the Florida Archaeological Council, Florida Public Archaeology Network, state and local museums, historical commissions, libraries, and public and private school systems. The 2013 poster and bookmarks are available through the local <a href="links.php#chapters">Florida Anthropological Society Chapters</a> and can also be acquired at the Florida Public Archaeology Network's <a href="http://flpublicarchaeology.org/darc.php">Destination Archaeology Resource Center</a> museum.</p>
<br/>
<div align="center"></div>
<p> </p>
</td>
</tr>
</table>
<? include 'calendar.php'; ?>
<? include 'eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include 'footer_dev.php'; ?><file_sep><?php
include 'appHeader.php';
$eventID = mysql_real_escape_string($_GET['eventID']);
$dupe = mysql_real_escape_string($_GET['dupe']);
//If not eventID then this is a new event or a resubmission of a failed initial event submission
if($eventID == null){
$pageTitle = "Add an Event";
$buttonText = "Add Event";
$newRecord = true;
//If form info was entered but unable to submit, repopulate form
if($_SESSION['eventVars']){
$eventVars = $_SESSION['eventVars'];
$eventDate = $eventVars['eventDate'];
$eventTimeStart = $eventVars['eventTimeStart'];
$eventTimeEnd = $eventVars['eventTimeEnd'];
$startAMPM = $eventVars['startAMPM'];
$endAMPM = $eventVars['endAMPM'];
$title = stripslashes($eventVars['eventTitle']);
$location = stripslashes($eventVars['eventLocation']);
$address = stripslashes($eventVars['eventAddress']);
$city = $eventVars['eventCity'];
$region = $eventVars['eventRegion'];
$description = stripslashes($eventVars['eventDescription']);
$url = $eventVars['eventURL'];
$contactName = $eventVars['contactName'];
$contactEmail = $eventVars['contactEmail'];
$contactPhone = $eventVars['contactPhone'];
$isApproved = $eventVars['isApproved'];
//Otherwise initialise blank variables
}else{
$eventDate = "";
$eventTimeStart = "";
$eventTimeEnd = "";
$startAMPM = "";
$endAMPM = "";
$title = "";
$location = "";
$address = "";
$city = "";
$description = "";
$region = "";
$url = "";
$contactName = "";
$contactEmail = "";
$contactPhone = "";
$isApproved = "";
}
}
//Otherwise this is an event edit, populate form data for editing
else{
$newRecord = false;
$sql = "SELECT * FROM $table WHERE eventID = $eventID;";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$pageTitle = "Edit an Event";
$buttonText = "Update Event";
//event Variables
$timestampDateTimeStart = strtotime($row['eventDateTimeStart']);
$timestampDateTimeEnd = strtotime($row['eventDateTimeEnd']);
$eventDate = date('m/d/Y', $timestampDateTimeStart);
$eventTimeStart = date('g:i', $timestampDateTimeStart);
$eventTimeEnd = date('g:i', $timestampDateTimeEnd);
$startAMPM = date('a', $timestampDateTimeStart);
$endAMPM = date('a', $timestampDateTimeEnd);
$title = stripslashes($row['eventTitle']);
$location = stripslashes($row['eventLocation']);
$address = stripslashes($row['eventAddress']);
$city = $row['eventCity'];
$region = $row['eventRegion'];
$description = stripslashes($row['eventDescription']);
$url = $row['eventURL'];
$contactName = $row['contactName'];
$contactEmail = $row['contactEmail'];
$contactPhone = $row['contactPhone'];
$isApproved = $row['isApproved'];
//$thisEventDate = new DateTime($row['eventDate']);
//$eventDate = $thisEventDate->format('m/d/Y');
//$thisEventTimeStart = new DateTime($row['eventTimeStart']);
//$eventTimeStart = $thisEventTimeStart->format('g:i');
//if($row['eventTimeEnd'] != ""){
//$thisEventTimeEnd = new DateTime($row['eventTimeEnd']);
//$eventTimeEnd = $thisEventTimeEnd->format('g:i');
//}
}
if($dupe){
$pageTitle = "Duplicate an Event";
$buttonText = "Add Event";
}
include $header;
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" >
<tr>
<td class="lg_mid">
<div style="margin-left:20px; margin-right:20px;">
<h1 align="center"><?php echo $pageTitle; ?></h1>
<br/>
<img src="../images/hrLine.png"/>
<br/>
<?php if($err && $msg) echo '<p align="center" style="color:red;" class="msg">'.$msg.'</p>'; ?>
<form action="processEdit.php" method="POST" enctype="multipart/form-data">
<?php
if(!$newRecord && !$dupe) {
echo '<input type="hidden" name="eventID" value="'.$eventID.'">';
echo '<p align="center"><a href="eventEdit.php?eventID='.$eventID.'&dupe=true">Duplicate this event</a></p>';
}
?>
<table border="0" align="center" cellpadding="5" >
<tr>
<td><div align="right">Event Approved:</div></td>
<td align="left">
<input type="checkbox" name="isApproved" value="1"
<?php
if($isApproved == 1) echo "checked=\"checked\"";
if(isset($_SESSION['email']) && ($newRecord == true)) echo "checked=\"checked\"";
?>
>
</td>
</tr>
<tr>
<td><div align="right">Date:</div></td>
<td align="left"><input id="date" class="input-text" type="text" name="eventDate" size="10" maxlength="10" value="<?php echo $eventDate?>">
<span style="color:red; font-size:10px;">*</span>
<label for="date" class="inlined"> - mm/dd/yyyy</label></td>
</tr>
<tr>
<td><div align="right">Start Time:</div></td>
<td align="left"><input id="startTime" type="text" name="eventTimeStart" size="5" maxlength="5" value="<?php echo $eventTimeStart?>">
<select name="startAMPM">
<?php
if($startAMPM == "pm"){
echo "<option value=\"am\"> AM</option>";
echo "<option value=\"pm\" selected=\"selected\">PM</option>";
}else{
echo "<option value=\"am\" selected=\"selected\">AM</option>";
echo "<option value=\"pm\"> PM</option>";
}
?>
</select>
<span style="color:red; font-size:10px;">*</span>
<label for="startTime" class="inlined">- hh:mm</label></td>
</tr>
<tr>
<td><div align="right">End Time:</div></td>
<td align="left"><input type="text" name="eventTimeEnd" size="5" maxlength="5" value="<?php echo $eventTimeEnd?>">
<select name="endAMPM">
<?php
if($endAMPM == "am"){
echo "<option value=\"am\" selected=\"selected\">AM</option>";
echo "<option value=\"pm\"> PM</option>";
}else{
echo "<option value=\"pm\" selected=\"selected\">PM</option>";
echo "<option value=\"am\"> AM</option>";
}
?>
</select><span style="color:red; font-size:10px;">*</span></td>
</tr>
<tr>
<td><div align="right">Title:</div></td>
<td align="left"><input type="text" name="title" size="44" maxlength="100" value="<?php echo $title?>">
<span style="color:red; font-size:10px;">*</span></td>
</tr>
<tr>
<td><div align="right">Location:</div></td>
<td align="left"><input type="text" name="location" size="44" maxlength="100" value="<?php echo $location?>">
<span style="color:red; font-size:10px;">*</span></td>
</tr>
<tr>
<td><div align="right">Address:</div></td>
<td align="left"><input type="text" name="address" size="44" maxlength="100" value="<?php echo $address?>">
<span style="color:red; font-size:10px;">*</span></td>
</tr>
<tr>
<td><div align="right">City:</div></td>
<td align="left"><input type="text" name="city" size="30" maxlength="50" value="<?php echo $city?>">
<span style="color:red; font-size:10px;">*</span></td>
</tr>
<tr>
<td><div align="right">Region:</div></td>
<td align="left">
<select name="region">
<option <?php if(!isset($region)) echo "selected=\"selected\""; ?> value=""></option>
<option <?php if($region == "Northwest") echo "selected=\"selected\""; ?> value="Northwest">Northwest</option>
<option <?php if($region == "North Central") echo "selected=\"selected\""; ?> value="North Central">North Central</option>
<option <?php if($region == "Northeast") echo "selected=\"selected\""; ?> value="Northeast">Northeast</option>
<option <?php if($region == "West Central") echo "selected=\"selected\""; ?> value="West Central">West Central</option>
<option <?php if($region == "Central") echo "selected=\"selected\""; ?> value="Central">Central</option>
<option <?php if($region == "East Central") echo "selected=\"selected\""; ?> value="East Central">East Central</option>
<option <?php if($region == "Southwest") echo "selected=\"selected\""; ?> value="Southwest">Southwest</option>
<option <?php if($region == "Southeast") echo "selected=\"selected\""; ?> value="Southeast">Southeast</option>
</select>
<span style="color:red; font-size:10px;">*</span>
<a href="../regions.php" target="_blank"><em> What region? </em></a>
</td>
</tr>
<tr>
<td><div align="right">Related Link:</div></td>
<!-- Not Required -->
<td align="left"><input type="text" name="url" size="44" maxlength="255" value="<?php echo $url?>"></td>
</tr>
<tr>
<td><div align="right">Contact Name:</div></td>
<td align="left"><input type="text" name="contactName" size="44" maxlength="40" value="<?php echo $contactName?>">
<span style="color:red; font-size:10px;">*</span></td>
</tr>
<tr>
<td><div align="right">Contact Email:</div></td>
<td align="left"><input type="text" name="contactEmail" size="44" maxlength="60" value="<?php echo $contactEmail?>">
<span style="color:red; font-size:10px;">*</span></td>
</tr>
<tr>
<td><div align="right">Contact Phone:</div></td>
<td align="left"><input type="text" name="contactPhone" size="20" maxlength="20" value="<?php echo $contactPhone?>">
<span style="color:red; font-size:10px;">*</span></td>
</tr>
<tr>
<td><div align="right">Description:</div></td>
<td align="left">
<textarea name="description" cols="64" rows="10" maxlength="1400"><?php echo $description?></textarea>
<span style="color:red; font-size:10px">*</span></td>
</tr>
<tr>
<td colspan="2" align="center"><div align="center"><span style="color:red; font-size:10px">*</span> - Denotes a required field.</div></td>
</tr>
<tr>
<td colspan="2">
<img src="../images/hrLine.png"/>
<br/></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input type="submit" value="<?php echo $buttonText?>" class="submit">
<input type="reset" value="Reset" class="submit">
</div></td>
</tr>
</table>
</form>
</div>
<br/>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
<?php include 'adminBox.php'; ?><br/>
<?php include '../calendar.php'; ?>
<!-- End Main div -->
<div class="clearFloat"></div>
</div>
<?php include $footer; ?><file_sep><?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "*UHB7ygv", "fpan_events");
$result = $conn->query("SELECT * FROM nerc WHERE eventDateTimeStart >= '2012-1-17'");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"eventID":"' . $rs["eventID"] . '",';
$outp .= '"eventDateTimeStart":"' . $rs["eventDateTimeStart"] . '",';
$outp .= '"eventDateTimeEnd":"'. $rs["eventDateTimeEnd"] . '",';
$outp .= '"title":"'. stripslashes($rs["title"]) . '",';
$outp .= '"description":"'. $rs["description"] . '",';
$outp .= '"location":"'. stripslashes($rs["location"]) . '",';
$outp .= '"region":"'. $rs["region"] . '",';
$outp .= '"relation":"'. $rs["relation"] . '",';
$outp .= '"flyerLink":"'. $rs["flyerLink"] . '",';
$outp .= '"link":"'. $rs["link"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?><file_sep><?php
$pageTitle = "Presentations";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?> <small>Request a Speaker</small></h1>
</div>
<div class="box-dash">
<div class="col-sm-12 text-center">
<div class="image">
<img src="images/presentations_pg.jpg" alt="" class="img-responsive" width="514" height="530" />
<p>Kids get to try out ancient hunting technology in our Atlatl Antics school program.</p>
</div>
</div>
<p>FPAN can help facilitate speakers for meetings of your civic group, community organization,
youth club, or heritage society, and for lecture series and special events.</p>
<p>Most presentations last about 30-45 minutes with additional time for questions, although
programs usually can be tailored for your needs. Specific topics are dependent on speaker
availability, so book early! There is no charge for presentations, although donations are
gratefully accepted to support FPAN educational programs.</p>
<p>Presentation topics are divided into two sections: </p>
<div class="col-sm-12 text-center">
<p>
<a href="#children" class="btn btn-info">Youth Programs</a>
<a href="#adults" class="btn btn-info">Presentations for Adults</a>
</p>
</div>
<p>Take a look at our offerings, then <a href="https://casweb.wufoo.com/forms/central-speaker-request-form/">
submit the form below</a> and let us
know what you’d like to learn about! If you don’t see what you’re looking for, ask us and we’ll do our
best to accommodate you.</p>
<p class="text-center"><em>Know what you want?</em> <br/> <a class="btn btn-primary"
href="https://casweb.wufoo.com/forms/central-speaker-request-form/" target="_blank">Submit a Speaker Request Form</a> </p>
</div>
<h2 id="children">Youth Programs</h2>
<div class="box-tab row">
<p>We have a wide variety of programming especially designed to educate kids about archaeology as well as Florida’s rich past. Whether for a classroom presentation, homeschool group, library event, school science night, or other group event we can tailor our programming to your interests and age level. Below are just a few examples of our youth programs:</p>
<div class="col-sm-6">
<ul>
<li><a href="#howold">Archaeology Works: How Old Is It?</a></li>
<li><a href="#matsci">Archaeology Works: Materials Science</a></li>
<li><a href="#diveinto">Dive into Archaeology</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#prefl">Discover Prehistoric Florida</a></li>
<li><a href="#atlatl">Atlatl Antics (for schools only)</a></li>
<li><a href="#sift">Sifting For Technology</a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div id="howold" class="col-sm-12">
<h3>Archaeology Works: How Old Is It?</h3>
<p>In this presentation you'll get to learn about a few of the ways archaeologists date artifacts and discover how they can help us learn about people who have lived in Florida throughout time!</p>
</div>
<div id="matsci" class="col-sm-12">
<h3>Archaeology Works: Materials Science</h3>
<p>Explore ancient artifacts from stone tools to pottery under a microscope just like an archaeologist! You'll get to see what aspects of these materials we, as archaeologists, focus on to get information about past technologies, and what aspects of Native American life we can learn about by studying the materials people left behind.</p>
</div>
<div id="diveinto" class="col-sm-12">
<h3>Dive into Archaeology</h3>
<p>Archaeologists don’t just work on land; they also try to learn about past people through the things they left behind underwater! In this fun and educational program, kids learn about the basics of archaeology as well as some of Florida’s important shipwrecks.</p>
</div>
<div id="prefl" class="col-sm-12">
<h3>Discover Prehistoric Florida</h3>
<p>People have lived throughout Florida for thousands of years, but the only way we know about them is through archaeology and the clues they left behind. Learn what it was like to live in prehistoric Florida long ago, complete with real artifacts and replicas of tools that ancient Floridians would have used to survive.</p>
</div>
<div id="atlatl" class="col-sm-12">
<h3>Atlatl Antics (for schools only)</h3>
<p>Learn about how hunting technology changed through time in prehistoric Florida, as well as how archaeologists study these changes. In this program kids get an introduction to archaeology and the chance to try a prehistoric hunting tool, the atlatl, for themselves.</p>
</div>
<div id="sift" class="col-sm-12">
<h3>Sifting For Technology</h3>
<p>A wall of storm surge from the 1993 Storm-of-the-Century flooded the Crystal River Archaeological State Park and caused the sea wall along the river’s edge to fail. When the new sea wall was constructed, the displaced archaeological materials along the river’s edge were saved. A replica Platform Mound, reminiscent of the Parks’ Mounds A and H, was constructed using the displaced midden deposits. Rangers and support personnel at Crystal River Archaeological State Park created the Sifting for Technology program to teach students about the people who once lived at the site. FPAN has contributed activities and outreach events to enhance the student’s understanding about the artifacts recovered from the site. The major emphasis is the recovery of items of ancient technology; however, we never know what we may find.</p>
<p>Students from local schools, colleges, civic and church groups, and other organizations are invited to participate in the recovery of prehistoric and historic artifacts, shellfish remains, animal bones, and other items that are still contained within these archaeological deposits. Although they are not in their original locations, the items recovered are very real and speak volumes about the peoples who once called this region around the Crystal River site their home.</p>
<p>While excavating, students are asked to look at each artifact and think about how that artifact got there? Who was the last person to touch it? What was it used for? How was it made? What does it tell us about the people who lived here?
Most importantly, students enjoy being able to help contribute to the knowledge of people of the past.
Absolutely no items are allowed to leave the Park. No one is allowed to keep recovered materials. All materials recovered are analyzed by students and then sent to the FPAN lab where they are archived and sent to the Division of Historical Resources in Tallahassee.</p>
<p>For more information, please contact the Crystal River Archaeological State Park at 352.795.3817</p>
</div>
</div><!-- /.box /.row -->
<h2 id="adults">Presentations for Adults</h2>
<div class="box-tab row">
<p>Archaeologists from the FPAN West Central office have a wide variety of interests and expertise to share with your group. Below are just a few examples of presentations we can provide. If you have another topic related to Florida archaeology you would like to hear about please contact us. We’re coming up with new presentation ideas all the time!</p>
<div class="col-sm-6">
<ul>
<li><a href="#introarch">Intro to Archaeology: Bringing the Past to the Present</a></li>
<li><a href="#firstfl">Tracing the First Floridians, the Paleoindians</a></li>
<li><a href="#cemetery">Cemetery Transcription and Headstone Cleaning</a></li>
<li><a href="#histmaps">Using Historical Maps in your Genealogy Research</a></li>
<li><a href="#peoplenight">People and the Night Sky</a></li>
<li><a href="#pastcontained">The Past Contained: Florida's Prehistoric Pottery Tradition</a></li>
<li><a href="#crystalriver">Crystal River: Culture and History</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#firstthanks">The First Thanksgiving in Florida: St Augustine, 1565</a></li>
<li><a href="#prepot">Prehistoric Pottery and the Crystal River Site</a></li>
<li><a href="#tampawrecks">Tampa Bay Shipwrecks of the Civil War</a></li>
<li><a href="#oldwrecks">The Oldest Shipwrecks of the Florida Keys</a></li>
<li><a href="#flpreserves">Florida's Shipwreck Preserves: Living Maritime Heritage You Can Visit</a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div id="introarch" class="col-sm-12">
<h3>Intro to Archaeology: Bringing the Past to the Present</h3>
<p>What do archaeologists do, exactly? Learn about the science of archaeology, its role as part of the field of anthropology, where archaeologists work, and how they discover and protect our cultural heritage. Appropriate for all ages, this fun and informative show sets the stage for understanding how archaeology preserves our past for the present and future.</p>
</div>
<div id="firstfl" class="col-sm-12">
<h3>Tracing the First Floridians, the Paleoindians</h3>
<p>Exciting research by archaeologists across Florida is shedding light on some of our state's earliest residents: the Paleoindians. This talk will explore what we know about Florida's first residents, as well as how archaeology can inform us about this little understood part of our past.</p>
</div>
<div id="cemetery" class="col-sm-12">
<h3>Cemetery Transcription and Headstone Cleaning</h3>
<p>Learn best practices for recording and cleaning historic grave markers in this introduction to cemetery preservation and maintenance.</p>
</div>
<div id="histmaps" class="col-sm-12">
<h3>Using Historical Maps in your Genealogy Research</h3>
<p>This talk covers the ways different historical maps such as Sanborn Fire Insurance maps, Plat maps, and Coastal Survey maps can be used in your research, as well as the many digital and paper sources for these maps, how to locate the map you need, and the possible information about your ancestors it might contain.</p>
</div>
<div id="peoplenight" class="col-sm-12">
<h3>People and the Night Sky</h3>
<p>For Native Floridians, the night sky was very important for navigational, religious, and historical reasons. Over time, the sky has changed and so has the way people relate to it. Learn about how astronomical and cultural changes have affected the importance of the night sky to people today.</p>
</div>
<div id="pastcontained" class="col-sm-12">
<h3>The Past Contained: Florida's Prehistoric Pottery Tradition</h3>
<p>Pottery was an important part of Native American culture and has also become a valuable artifact for archaeologists today. In this presentation learn all about the Native American process for making pottery, how and why they used it, and what information archaeologists can get from studying these small pieces of the past.</p>
</div>
<div id="crystalriver" class="col-sm-12">
<h3>Crystal River: Culture and History</h3>
<p>The Crystal River site was once a sprawling ceremonial center, attracting people from great distances. This complex of burial and temple mounds is one of the longest continually occupied sites in Florida. Though the Native Americans who lived there are now long gone, their impressive earthen architecture remains. The mound complex attracted early archaeologists who discovered beautifully decorated pottery, shell, and copper artifacts. The remarkable earthen structures and artifacts earned the Crystal River site a place among the most famous archaeological sites in Florida. Although the site is well known there is still much to learn about the people who once thrived on the bountiful Crystal River.</p>
</div>
<div id="firstthanks" class="col-sm-12">
<h3>The First Thanksgiving in Florida: St Augustine, 1565</h3>
<p>This family friendly presentation discusses the first contact between European explorers and Native Americans in what is now Florida, as well as the real story of the first Thanksgiving in St. Augustine.</p>
</div>
<div id="prepot" class="col-sm-12">
<h3>Prehistoric Pottery and the Crystal River Site</h3>
<p>The Crystal River site was once a sprawling ceremonial center with impressive earthen architecture. Though the earthworks are still visible today there is still much to learn about the people who created them and the artifacts they contain. In this presentation learn about the Crystal River mound complex and recent findings on the site's pottery collection.</p>
</div>
<div id="tampawrecks" class="col-sm-12">
<h3>Tampa Bay Shipwrecks of the Civil War</h3>
<p>The maritime battles of the Civil War employed a greater diversity of ships than any previous sustained naval action. This presentation illustrates this aspect and highlights a few examples of Civil War-related shipwrecks in the Tampa Bay area.</p>
</div>
<div id="oldwrecks" class="col-sm-12">
<h3>The Oldest Shipwrecks of the Florida Keys</h3>
<p>The Florida Keys are rife with remains of shipwrecks and maritime disasters. This presentation explores several that you can visit today, including the vessel remains of the famous 1733 Spanish Plate fleet disaster.</p>
</div>
<div id="flpreserves" class="col-sm-12">
<h3>Florida's Shipwreck Preserves: Living Maritime Heritage You Can Visit</h3>
<p>Clues to Florida’s maritime history are scattered along the state’s coasts, bays, and rivers in the form of shipwrecks relating to waterborne exploration, commerce, and warfare. This lecture features Florida’s Museums in the Sea, historic shipwrecks that have been interpreted for divers and snorkelers as a way to educate citizens and visitors about the real treasure of Florida’s shipwrecks – their history.</p>
</div>
</div><!-- /.box /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?> <file_sep><?php
if (!defined('WEBPATH')) die();
require_once('normalizer.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="no" name="apple-mobile-web-app-capable" /> <!-- this will not work right now, links open safari -->
<meta name="format-detection" content="telephone=no">
<meta content="index,follow" name="robots" />
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type" />
<link href="<?php echo $_zp_themeroot ?>/images/homescreen.png" rel="apple-touch-icon" />
<meta content="minimum-scale=1.0, width=device-width, maximum-scale=0.6667, user-scalable=no" name="viewport" />
<link href="<?php echo $_zp_themeroot ?>/css/style.css" rel="stylesheet" type="text/css" />
<script src="<?php echo $_zp_themeroot ?>/javascript/functions.js" type="text/javascript"></script>
<script src="<?php echo $_zp_themeroot ?>/javascript/rotate.js" type="text/javascript"></script>
<title><?php echo getBareGalleryTitle(); ?> <?php echo gettext("Archive"); ?></title>
<?php zp_apply_filter("theme_head"); ?>
<title><?php echo getBareGalleryTitle(); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
$archivepageURL = htmlspecialchars(getGalleryIndexURL());
?>
<script type="application/x-javascript">
addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false);
function hideURLbar(){
window.scrollTo(0,1);
}
</script>
</head>
<body class="portrait">
<script type="text/javascript" language="JavaScript">
updateOrientation();
</script>
<div id="topbar">
<div id="title">
<?php echo gettext('Archive'); ?></div>
<div id="leftnav">
<a href="<?php echo htmlspecialchars(getGalleryIndexURL(false));?>"><img alt="<?php echo gettext('Main Index'); ?>" src="<?php echo $_zp_themeroot ?>/images/home.png"/></a>
</div>
</div>
<div id="content">
<div class="galleryalbum"><ul class="autolist">
<?php
$count = 0;
while (next_album()):
?>
<li class="withimage">
<a href="<?php echo htmlspecialchars(getAlbumLinkURL());?>" class="img">
<?php printCustomAlbumThumbImage(getBareAlbumTitle(), null, 480, 120, 480, 120); ?>
<span class="folder_info">
<?php
$anumber = getNumAlbums() ;
$inumber = getNumImages();
if ($anumber > 0 || $inumber > 0) {
echo '<em>';
if ($anumber == 0) {
if ($inumber != 0) {
printf(ngettext('%u photo','%u photos', $inumber), $inumber);
}
} else if ($anumber == 1) {
if ($inumber > 0) {
printf(ngettext('1 album, %u photo','1 album, %u photos', $inumber), $inumber);
} else {
printf(gettext('1 album'));
}
} else {
if ($inumber == 1) {
printf(ngettext('%u album, 1 photo','%u albums, 1 photo', $anumber), $anumber);
} else if ($inumber > 0) {
printf(ngettext('%1$u album, %2$s','%1$u albums, %2$s', $anumber), $anumber, sprintf(ngettext('%u photo','%u photos',$inumber),$inumber));
} else {
printf(ngettext('%u album','%u albums', $anumber), $anumber);
}
}
echo '</em>';
}
?>
</span>
<span class="name"><?php echo getBareAlbumTitle();?></span><span class="arrow_img"></span> <!--PigsLipstick: was getBareAlbumTitle()-->
</a>
</li>
<?php
//this will process as many albums as allowed by theme settings.
endwhile;
?>
<li class="hidden autolisttext"><a class="noeffect" href="#">Load more albums...</a></li>
</ul>
</div>
<div id="footer">
<?php printZenphotoLink(); ?>
</div>
</body>
</html>
<file_sep><?php
$pageTitle = "Geotrail";
include '../header.php';
include '../../admin/dbConnect.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Geocaching with FPAN</h1></th>
</tr>
<tr>
<td class="lg_mid">
<p align="center"><img src="../images/darcgeotrail.png" alt="DARC Geo-Trail : Exploring Florida's Archaeology" /> </p>
<p style="font-size:11px; width:300px; margin-left:auto; margin-right:auto">
<img src="../images/fpangeoman.png" alt="FPAN geoman"/><br/><br/>
Are you ready to explore Northwest Florida's archaeology and history? Forget your fedoras and bullwhips, and pick up a GPS device (or download a GPS app to your smartphone)! The DARC Geo-Trail offers everyone an outdoor adventure and chance of discovery...
</p>
<p><strong>Geocaching? What's Geocaching?
</strong><br />
Geocaching is a worldwide scavenger hunt game. Players try to locate hidden containers, called caches, using GPS enabled devices and share their experiences online. Caches are often hidden very well, but are never buried or placed in areas in need of protection. To learn more about geocaching go to this official <a href="http://www.geocaching.com/articles/Brochures/EN/EN_Geocaching_BROCHURE_online_color.pdf">brochure</a> or visit this <a href="http://www.geocaching.com/guide/default.aspx">website</a>. You can also view this <a href="http://www.youtube.com/watch?v=-4VFeYZTTYs&feature=player_embedded">video</a>. Please follow all basic guidelines and rules when geocaching. </p>
<p>
<strong>DARC Geo-Trail<br />
</strong>
A "geotrail" is a series of caches tied together by a common topic or theme. Discover your Florida history through museums and archaeological sites open to the public in the DARC Geo-Trail.</p>
<p>
DARC stands for Destination Archaeology! Resource Center, the museum at the FPAN Coordinating Center. FPAN has hidden geocaches at participating sites across Northwest Florida to form a geotrail called DARC Geo-Trail. All the sites on this geotrail are connected to Florida archaeology and are featured in the Road Trip Through Florida Archaeology exhibit at the Destination Archaeology! Resource Center in Pensacola, FL.
</p>
<br/>
<p align="center"><strong>Adventure and Discovery</strong></p>
<p align="center"><img src="../images/gps.jpg" alt="GPS device on map" class="padded"/> </p>
<p>Players who participate in this geotrail will have the opportunity to visit many different types of archaeological sites at both rural and urban areas while looking for caches. </p>
<p>A few of the places this journey will take you:</p>
<ul>
<li>Ancient earthworks built by Native American civilizations long before Columbus set sail for the Americas… <br />
</li>
<li>Plantations that fueled the southern economy and ultimately led the country into Civil War… <br />
</li>
<li>Remnants of fortifications once under siege during the American Revolution… <br />
</li>
<li>Antebellum industrial areas that powered the economy of Florida …</li>
</ul>
<p><strong>Chance to Win an Official DARC Geocoin! </strong></p>
<p>The first 300 participants who record at least 12 sites will receive a traceable, special edition geocoin produced specifically for this geotrail. </p>
<p>To be eligible for the coin, please download the official <a href="http://flpublicarchaeology.org/uploads/nwrc/passport.pdf">DARC Geo-Trail passport here</a>. You will need Adobe Acrobat to view and print this document. To download Adobe Acrobat, <a href="http://www.get.adobe.com/" target="_blank"><strong>click here</strong></a>. Once you find a geocache, record the name, date, and code word (located on the inside of the logbook) in this passport and take a photo of yourself with the geocache container. The first person to find a geocache will find an FPAN item inside!</p>
<p align="center"><img src="../images/geocaching_logo.png" /></p>
<p><br />
<strong>Here’s how it works: </strong><strong> </strong><br />
</p>
<ul>
<li>Log onto <a href="www.geocaching.com%20">www.geocaching.com</a> to retrieve the cordinates and location information for the geocaches. Basic membership for site is free.<br />
</li>
<li>Search for the geocache online by GC code number or use advanced search by user name “DARC Geotrail.” <br />
</li>
<li>Locate at least 12 DARC Geo-Trail geocaches and record the code word from each geocache in your passport. Take a picture of yourself with the geocache at the site and post it to the corresponding Geocaching.com page.<br />
</li>
<li>Bring in your completed passport to the address below or mail it in for validation. The first 300 people to complete the challenge will receive the coin.*</li>
</ul><p>
<strong>Destination Archaeology Resource Center</strong><br />
<strong>207 East Main Street</strong><br />
<strong>Pensacola, FL</strong><br />
<strong>32502</strong><br />
<strong>Phone: 850.595.0050 ext. 107</strong><br />
<strong>www.flpublicarchaeology.org</strong></p>
<p>The DARC Geo-Trail is a project of the Florida Public Archaeology Network and University of West Florida. This project is supported by the <a href="http://www.floridastateparks.org/"><em>Florida Park Service</em></a> and the <a href="http://www.floridacaching.com/"><em>Florida Geocaching Association</em></a>.<br />
<br />
*Coins will be awarded on a first-come, first-serve basis as supplies last. Only one coin per person with a valid passport. Once your passport has been validated you will be rewarded with a DARC geocoin. FPAN and UWF are not responsible for any lost, stolen or misdirected passports or mail. All geocaches are officially registered at www.geocaching.com. Participants will need to register at Geocaching.com to retrieve coordinates and other location information for geocaches. Participants must log the find with a photo from the cache location. Basic membership to Geocaching.com is free. </p>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
<? include '../calendar.php'; ?>
<? include '../eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include '../footer.php'; ?><file_sep><?php
$pageTitle = "Volunteer";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-dash">
<div class="text-center">
<div class="image center-block" style="max-width:400px;">
<img src="images/getinvolved.jpg" alt="" class="img-responsive" >
<p> Volunteers help to clean grave marker at historic cemetery.</p>
</div>
</div>
<p> We don't often have hands-on volunteer opportunities with our region but, you can fill out a <a href="documents/VolunteerForm.pdf">Northeast Region Volunteer Form</a> if you'd like.
</p>
<p>
The <a href="https://saaa.shutterfly.com">St. Augustine Archaeological Association</a> is the main volunteer arm for the City’s Archaeological Department. To get involved with local digs and join in on the monthly lecture series, contact SAAA.
</p>
</div><!-- /.box-tab -->
<h2>Get Involved</h2>
<div class="box-tab">
<p>There are many Organizations you can join to pursue an interest in archaeology. Here are some of our favorites:</p>
<h3>Local Organizations</h3>
<ul>
<li><a href="http://saaa.shutterfly.com/">St. Augustine Archaeological Association</a></li>
<li><a href="http://www.tolomatocemetery.com/">Tolomato Cemetery Preservation Association</a></li>
<li><a href="http://www.nsbhistory.org/">Southeast Volusia Historical Society / New Smyrna Museum of History</a></li>
</ul>
<h3>State Organizations</h3>
<ul>
<li><a href="http://www.fasweb.org/">Florida Anthropological Society</a></li>
<li><a href="http://www.flamuseums.org/">Florida Association of Museums</a></li>
<li><a href="http://www.floridatrust.org/">Florida Trust</a></li>
</ul>
<h3>National & International Organizations</h3>
<ul>
<li><a href="http://www.saa.org/">Society for American Anthropology</a></li>
<li><a href="http://www.sha.org/">Society for Historical Archaeology</a></li>
<li><a href="http://www.southeasternarchaeology.org/">Southeastern Archaeological Conference</a></li>
<li><a href="http://www.interpnet.com/">National Association for Interpretation</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php include('_header.php'); ?>
<div class="container portfolio">
<div class="page-header">Portfolio of Work</div>
<h1>Websites</h1>
<div class="jumbotron">
<div class="row">
<h2>Florida Public Archaeology Network</h2>
<div class="col-md-5 col-sm-8">
<h3>Description</h3>
<p>Website redesign and continual maintenance for full-time employer. FPAN is composed of eight regions across the state of Florida, each of which needed its own website and identity while still retaining a consistent look and feel with the rest of the network sites.</p>
<p>
<a href="http://fpan.us/new" class="btn btn-primary btn-lg" target="_blank">View »</a>
</p>
</div>
<div class="col-md-3 col-sm-4">
<h3>Skills Used</h3>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>PHP</li>
<li>MySQL</li>
<li>Photoshop</li>
</ul>
</div>
<div class="col-md-4 col-sm-12">
<img src="images/fpan.png" class="img-responsive center-block" style="border:1px solid #222" />
</div>
</div><!-- /.row -->
<div class="row">
<h2>Destination: Archaeology, Resource Center</h2>
<div class="col-md-5 col-sm-8">
<h3>Description</h3>
<p>Located inside the Florida Public Archaeology Network headquarters in downtown Pensacola, the Destination Archaeology Resource Center is an archaeology museum open to the public. </p>
<p>
<a href="http://destinationarchaeology.org" class="btn btn-primary btn-lg" target="_blank">View »</a>
</p>
</div>
<div class="col-md-3 col-sm-4">
<h3>Skills Used</h3>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>PHP</li>
<li>MySQL</li>
<li>Photoshop</li>
</ul>
</div>
<div class="col-md-4 col-sm-12">
<img src="images/darc.png" class="img-responsive center-block" style="border:1px solid #222" />
</div>
</div><!-- /.row -->
</div><!-- /.jumbotron -->
<h1>iPhone Apps</h1>
<div class="jumbotron">
<div class="row">
<h2>Destination: Civil War</h2>
<div class="col-md-5 col-sm-8">
<h3>Description</h3>
<p>Destination: Civil War is an interactive iPhone application that lets users discover Civil War era hertiage sites, as well as museums, all across the state of Florida. The app uses the MapKit framework to display sites which are stored in an XML file. </p>
<p>
<a href="https://itunes.apple.com/us/app/destination-civil-war/id504889090?ls=1&mt=8" class="btn btn-primary btn-lg" target="_blank">View in App Store »</a>
</p>
</div>
<div class="col-md-3 col-sm-4">
<h3>Skills Used</h3>
<ul>
<li>Objective-C</li>
<li>MapKit</li>
<li>XML</li>
<li>PHP</li>
</ul>
</div>
<div class="col-md-4 col-sm-12">
<img src="images/DCW_screens.png" class="img-responsive center-block" />
</div>
</div><!-- /.row -->
<div class="row">
<h2>FPAN Mobile</h2>
<div class="col-md-5 col-sm-8">
<h3>Description</h3>
<p>FPAN Mobile is an iPhone application that was that allows users across the state of Florida to find out what kind of archaeology related public events are happening in their area. Users can find events across the state by region and if they are interested in an event they can add it to their calendar. This event calendar system is in sync with the PHP/MySQL based event calendar system in place on all FPAN regional places.</p>
<p>
<a href="https://itunes.apple.com/us/app/fpan-mobile/id478009860?mt=8&ls=1" class="btn btn-primary btn-lg" target="_blank">View in App Store »</a>
</p>
</div>
<div class="col-md-3 col-sm-4">
<h3>Skills Used</h3>
<ul>
<li>Objective-C</li>
<li>UIKit</li>
<li>MySQL</li>
</ul>
</div>
<div class="col-md-4 col-sm-12">
<img src="images/FPAN_mobile_screens.png" class="img-responsive center-block" />
</div>
</div><!-- /.row -->
</div><!-- /.jumbotron -->
<h1>Poster Design</h1>
<div class="jumbotron">
<div class="row">
<h2>Florida Archaeology Month</h2>
<div class="col-sm-8">
<h3>Description</h3>
<p>Every March, statewide programs and events celebrating Florida Archaeology Month are designed to encourage Floridians and visitors to learn more about the archaeology and history of the state. For several years, our organization has been tasked with the design of the accompanying posters and bookmarks to be distrubuted at events across the state throughout the month.</p>
</div>
<div class="col-sm-4">
<h3>Skills Used</h3>
<ul>
<li>Photoshop</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<h3>FAM 2014</h3>
<a href="images/2014_frontback.jpg" target="_blank"><img src="images/2014_frontback_sm.jpg" class="img-responsive" /><p class="text-center text-warning"><small>Click to enlarge.</small></p></a>
</div>
<div class="col-sm-4">
<h3>FAM 2013</h3>
<a href="images/2013_frontback.jpg" target="_blank"><img src="images/2013_frontback_sm.jpg" class="img-responsive" /><p class="text-center text-warning"><small>Click to enlarge.</small></p></a>
</div>
<div class="col-sm-4">
<h3>FAM 2012</h3>
<a href="images/2012_frontback.jpg" target="_blank"><img src="images/2012_frontback_sm.jpg" class="img-responsive" /><p class="text-center text-warning"><small>Click to enlarge.</small></p></a>
</div>
</div><!-- /.row -->
</div><!-- /.jumbotron -->
</div>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Educational Resources";
include('../_header.php');
?>
<!-- page-content begins -->
<div class="container">
<div class="page-header">
<h1>Resources, <small>Lesson Plans</small></h1>
</div>
<div class="row">
<div class="col-sm-6 col-lg-6 ">
<div class="box-tab">
<h3 class="text-center">Timucuan Technology</h3>
<img src="images/timucuan.jpg" class="img-responsive img-circle center-block" />
<p>Resources for students and instructions for teachers for exploring northeast
Florida's prehistory through biotechnology.</p>
<a href="timucuan" class="btn btn-primary btn-md center-block" role="button">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Shipwreck on a Table: <small>Emanuel Point Shipwreck</small></h3>
<img src="images/soat.jpg" class="img-responsive img-circle center-block" />
<p>Features a brief description of underwater archaeology, resources for learning more about shipwrecks, and a lesson plan which familiarizes students with the Emanuel Point Shipwreck with hands-on activities that allow participants to interpret the archaeological data. New Generation Sunshine State Standards (NGSSS) have been identified for all age groups and can be used in science, social studies, or math classes.</p>
<a href="SOAT.zip" class="btn btn-primary btn-md center-block" role="button" target="_blank">Download</a>
</div>
<div class="box-tab">
<h3 class="text-center">Beyond Artifacts</h3>
<img src="images/beyondArtifacts.jpg" class="img-responsive img-circle center-block" />
<p>Beyond Artifacts is a resource book compiled by staff from the Florida Public Archaeology Network
and made available to anyone with an interest in archaeological education. Coupled with support
from FPAN’s regional centers, this resource is intended to bring archaeology into your classroom
– wherever that classroom may be.</p>
<a href="BeyondArtifacts.zip" class="btn btn-primary btn-md center-block" role="button" target="_blank">Download</a>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-lg-6">
<div class="box-tab">
<h3 class="text-center">Coquina Queries</h3>
<img src="images/coquina.jpg" class="img-responsive img-circle center-block" />
<p>The Coquina Queries project, funded in part by a Florida Department of State
grant-in-aid, provides an education program based on regional coquina ruin
sites and focuses on the unique role of this material in Florida history.</p>
<a href="http://coquinaqueries.org" class="btn btn-primary btn-md center-block" role="button" target="_blank">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Investigating a Tabby Slave Cabin</h3>
<img src="images/tabby.jpg" class="img-responsive img-circle center-block" />
<p>Student archaeology book and teacher instructions available for free download on the Timucuan Preserve's website. These lessons are part of the Project Archaeology: Investigating Shelter unit that uses artifacts found by University of Florida's archaeology investigations to understand the lives of those enslaved at Kingsley Plantation. Recommended for grades 3-5, aligned with Common Core and Sunshine State standards, NCSS endorsed.</p>
<a href="http://www.nps.gov/timu/forteachers/project-archaeology.htm" class="btn btn-primary btn-md center-block" role="button" target="_blank">Learn More</a>
</div>
<div class="box-tab">
<h3 class="text-center">Archaeology Jeopardy</h3>
<img src="images/archJeopardy.jpg" class="img-responsive img-circle center-block" />
<p>Engage students with an interactive PowerPoint game of Archaeology Jeopardy with categories such
as: <em>Who Studies What?</em>, <em>Tools of the Trade</em>, <em>Archaeologists at Work</em>,
<em>Guess the Artifact</em>, and <em>Florida Prehistory</em>. </p>
<a href="IntroArchJeopardy.zip" class="btn btn-primary btn-md center-block" role="button" target="_blank">Download</a>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
<div class="row">
<div class="col-sm-6">
<h2>Other Resources</h2>
<div class="box-tab">
<p> “TeachingFlorida.org” is designed to bring the study of Florida into the classrooms of our state. Created by the Florida Humanities Council, it combines the scholarship of distinguished humanities scholars with ideas and lesson plans from Florida teachers.</p>
<a href="http://teachingflorida.org/" class="btn btn-primary btn-md center-block" role="button" target="_blank">Learn More</a>
</div>
</div>
</div>
</div><!-- /.page-content /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
include 'header.php';
$table = 'ConferenceAttendanceParticipation';
//if this is a new event, clear any potential leftover form data
if($_GET['new'])
$_SESSION['formVars'] = "";
//If event ID is supplied in URL, this event is being edited. Gather info from database and populate form.
if($_GET['id']){
setupServiceEdit($_GET['id'], $table);
}
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true){
confirmServiceSubmit($table);
}
//Form has been submitted but not confirmed. Display input values to check for accuracy
if(isset($_POST['submit'])&&!isset($_POST['confirmSubmission'])){
firstServiceSubmit($_POST);
}elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="conferenceAttendanceParticipation" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Conference Attendance / Participation</h2>
<p>Use this form to log conference attendence or participation for your <strong>self</strong> only. <br/>
This activity will be attributed to the individual currently logged in. </p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text" required="required">
/
<label for="element_1_1">MM</label>
</span> <span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text" required="required">
<a class="red"> *</a>
<label for="element_1_3">YYYY</label>
</span> </li>
<li id="li_3" >
<label class="description" for="element_3">Type</label>
<div>
<select class="element select small" id="element_3" name="typeConference" required="required">
<option value="" selected="selected"></option>
<option value="SHA" <?php if($formVars['typeConference'] == "SHA") echo 'selected="selected"'; ?> >SHA</option>
<option value="SAA" <?php if($formVars['typeConference'] == "SAA") echo 'selected="selected"'; ?> >SAA</option>
<option value="SEAC" <?php if($formVars['typeConference'] == "SEAC") echo 'selected="selected"'; ?> >SEAC</option>
<option value="FAS" <?php if($formVars['typeConference'] == "FAS") echo 'selected="selected"'; ?> >FAS</option>
<option value="FHS" <?php if($formVars['typeConference'] == "FHS") echo 'selected="selected"'; ?> >FHS</option>
<option value="FAM" <?php if($formVars['typeConference'] == "FAM") echo 'selected="selected"'; ?> >FAM</option>
<option value="FL Trust" <?php if($formVars['typeConference'] == "SHA") echo 'selected="selected"'; ?>>FL Trust</option>
<option value="Other" <?php if($formVars['typeConference'] == "SHA") echo 'selected="selected"'; ?>>Other</option>
</select>
<a class="red"> *</a> </div>
</li>
<li id="li_2" >
<label class="description" for="element_2">Comments </label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium" onKeyDown="limitText(this.form.comments,this.form.countdown,2080);"
onKeyUp="limitText(this.form.comments,this.form.countdown,2080);" ><?php echo $formVars['comments']; ?></textarea>
<br/>
<font size="1">(Maximum characters: 2080)<br>
You have
<input readonly type="text" name="countdown" size="3" value="2080">
characters left.</font> </div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close else ?>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body></html><file_sep><?php
$pageTitle = "Lecture List";
include 'header.php';
?>
<!-- Main Middle -->
<script type="text/javascript">
showElement('projects_sub');
</script>
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Program List</h1></th>
</tr>
<tr>
<td class="table_mid"><h2>Titles for Lectures and Guest Speaking Events </h2>
<p>While we are able to adapt and respond to a variety of requests for presentations, below are some of the standards we recommend when meeting a group for the first time. We are interested in creating long-term partnerships with historical societies, school districts, and civic groups. Keep in mind March is Florida Archaeology Month and new lectures and often launched at this time in response to the theme selected by the Florida Anthropological Society. Youth programs are listed first; to jump to programs geared towards an adult audience, <a href="#standards">click
here</a>.</p>
<h2>Programs for Children</h2>
<ul>
<li><strong>Timucuan Pyrotechnology</strong><br />
This activity introduces students to Timucuan culture, focusing on ways that local
prehistoric people used fire to meet their daily needs. A hands-on experiment provides a bang as
students use balloons (and water balloons!) to explore how prehistoric people could cook prior to
the advent of pottery.<br />
<br />
</li>
<li><strong>Tools of the Trade </strong><br />
One of the best ways to show people how we study a site is to share our tool kit. Students observe the tools we use in the field and infer the reasoning behind our choices. For example, many people may know we use a trowel, but what's the difference between the pointy ones versus the flat edge blades? What would we do that? Tools include trowels (yes, plural!), munsell color chart, line levels, various measuring devices, and root clippers. The most important? Our pencil and sharpie for recording our findings. <br />
<br />
</li>
<li><strong>PB&J: How (and why!) Archaeologists Find Sites </strong><br />
A classic! Students systematically excavate a peanut butter and jelly sandwich to explore the concepts of stratigraphy and survey, emphasizing how archaeologists use the scientific method in the field. If Power Point is available, this activity can include pictures of real tools, fieldwork, and sites to enhance learning. <br />
<br />
</li>
<li><strong>Prehistoric Pottery</strong><br />
Students learn about the advent of pottery in Florida, and do hands-on experimentation using play-doh to explore pottery-making and -decorating technology. The lesson also teaches about how pottery can help archaeologists understand a site and its prehistoric people.<br />
<br />
</li>
<li><strong>Underwater Archaeology</strong><br />
This lesson uses on the book <em>Shipwreck: Fast Forward</em> to explore how underwater sites form, and the excavation processes used to retrieve information about them. Kids then try their own hand at using Cartesian coordinates by playing an adapted version of Battleship to “map” each other’s shipwrecks, and they get to map a real, 100-year-old anchor!<br />
<br />
</li>
<li><strong>Kingsley Slave Cabin Archaeology</strong><br />
Recent excavations at Kingsley Plantation have radically changed our understanding of what life was like for the enslaved people living there. This lesson tasks students with mapping artifacts exactly where they were found in the cabin, just like archaeologists do. After mapping, they work in teams to classify artifacts. Finally, as a group we discuss explore what we can understand about this population by looking at these artifacts in context (where they were found and with what other objects).
</li>
<li>
<strong>Make Prehistoric Florida your Home</strong>
<br/>
This presentation teaches children about the raw and natural resources Native Americans used to build their campsites and villages. How did they build houses and shelter? How did they construct giant mounds? What did they make their tools and clothing out of? Kids enjoy learning how ancient peoples used the natural environment to hunt, fish, build towns, and make a living in prehistoric Florida!
<br/>
<br/>
</li>
</ul>
<p> </p>
<a name="standards"></a>
<h2>The Standards: </h2>
<ul>
<li><strong>In Search of 16th-Century St. Augustine</strong><br />
Walking the streets of St. Augustine can confuse the visitor in search of the 16th century,
but 500-year-old sites are there—often beneath their feet. This presentation synthesizes
work done by archaeologists over the past century and focuses on small objects that bring
ordinary people in the 16th century to life. Those planning to partake in the city's 450th
birthday party can prepare with our “Top Ten to Do Before 2015”—the best ways to get a
glimpse of the city’s earliest days. <br />
<br />
</li>
<li>
<strong>Archaeology Along the St. Johns River</strong><br />
The St. Johns River has played an ever changing role in the lives of northeast Floridians for thousands of years. Prehistorically, the river provided food, transportation, and a geographic conntection between people living from the source to the mouth. Historically, the river supported missions, plantations, and military outposts. Exploration is not limited to land; famous archaeological sites on the river's bottom also have been discovered and add to our knowledge of Florida's past.
<br />
<br />
</li>
<li><strong>Fantastic Archaeology: Florida Frauds, Myths, and Mysteries <br />
</strong>Celebrate Florida archaeology by learning what archaeology is, and importantly what it is not. This educational and entertaining talk will focus on the misuse and abuse of northeast Florida's past.
<br />
<br />
</li>
<li>
<strong>Coquina: Florida's Pet Rock </strong><br />
As a supplement to<em> Coquina Queries</em> we are able to come out to festivals and classrooms with a variety of teaching tools. We can either emphasize ruins in our region made out of coquina, talk about care and conservation, or create stations of hands-on activities in formal and informal settings.
<br />
<br />
</li>
<li><strong>Prehistoric Weaponry <br />
</strong>The difference between a tool and a weapon is a matter of intent. While this can be difficult to ascribe archaeologically, humans have used tools as weapons for over a million years. This presentation puts better known projectile points in context of their arrival to southeastern North America and discusses biotechnology put into action by Timucuans and other prehistoric people.
<br />
<br />
</li>
<li><strong>Archaeology in Florida State Parks </strong><br />
When people first realize archaeology happens in Florida, it often surprises them to hear of how many active permits are issued to do work in state parks. Some of the digs are by field school where students learn the ABCs of excavation, while other digs are done in advance of construction or improvements to a park. This lecture emphasizes visitation of the many parks that feature archaeology interpreted for the public including Ft. Mose, Hontoon Island, Crystal River, Bulow Sugar Mill, Ft. Clinch, De Leon Springs, and many more.
<br />
<br />
</li>
<li>
<strong>A Florida Shipwreck through Time </strong><br />
Based on the book <em><a href="http://www.amazon.com/Shipwreck-Leap-Through-Claire-Aston/dp/1901323587/ref=sr_1_2?s=books&ie=UTF8&qid=1283977267&sr=1-2">Shipwreck: Leap through Time</a></em>, this talk takes the audience through the stages of a shipwreck--from ship construction to underwater museum. The issue of piracy in archaeology is addressed, as well as expanding known submerged resources beyond maritime themes.
<br />
<br />
</li>
<li>
<strong>Historic Cemeteries as Outdoor Museums<br />
</strong>We encourage families and classes to get into the cemeteries within their communities and put archaeological principles to the test. This presentation can be brought via Powerpoint or introduced on-site at an actual cemetery. Iconography, dating of headstones, and change of style over time (seriation) are emphasized along with lessons in cemetery preservation.
<br />
<br />
</li>
<li>
<strong>14,000 Years of Florida Prehistory</strong>
<br/>
This lecture discusses the chronology of Florida’s prehistoric Native Americans, and discusses their major technological achievements through time. 14k Years of FL Prehistory presents the four archaeological time periods in the southeastern United States, and how archaeologists use them to differentiate among different culture groups. This presentation is perfect for those looking for a broad overview of prehistoric archaeology in Florida.
<br/>
<br/>
</li>
<li>
<strong>Paleoenvironments</strong>
<br/>
How do archaeologists learn what past environments were like? This lecture covers the study of archaeological bones, shells, and other faunal artifacts, and also pollen and other plant remains to learn about ancient environments. It also discusses sediment coring to investigate different geological layers. ‘Paleoenvironments’ is a wonderful lecture if you’re interested in how Florida’s environment has changed affected Natives over time.
<br/>
<br/>
</li>
<li>
<strong>Shells</strong>
<br/>
The shell workshop includes both lecture- and activity-based components. It introduces participants to common Florida shells, found in both prehistoric middens and along today’s modern beaches and tidal flats. The lecture portion emphasizes the physical characteristics of species, but also discusses their ecology, how they were used by Native Americans and Europeans, and how archaeologists use them to understand past peoples and environments. The activities include shell-related games for kids, and fun shell midden scenarios/problems for adults to solve.
<br/>
<br/>
</li>
</ul>
<h2 align="left">Additional Programming</h2>
<p align="left">Still want more? Check out our <a href="http://storify.com/FPANNortheast"><strong>Storify</strong></a> and <a href="http://fpannortheast.tumblr.com/"><strong>Tumblr</strong></a> pages!</p>
<p>For more local archaeology news, sign up for our latest <a href="http://flpublicarchaeology.org/newsletter/northeast/user/subscribe.php"><strong>newsletter</strong></a>!</p></td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
//Outdated msqyl_ commands
$link = @mysql_connect('fpanweb.powwebmysql.com', 'fpan_dbuser', '$ESZ5rdx');
if (!$link) {
$link = mysql_connect('localhost', 'fpan_dbuser', '$ESZ5rdx') ;
}else{
mysql_error();
}
mysql_select_db(fpan_events);
?><file_sep><?php
$pageTitle = "Home";
$bg = array('jumbotron.jpg','jumbotron2.jpg' ); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
include('_header.php');
require_once("../rss/rsslib.php");
$url = "http://www.flpublicarchaeology.org/blog/ncrc/feed/";
?>
<!-- page-content begins -->
<div class="page-content container">
<!-- Row One -->
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="col-sm-12">
<div class="jumbotron hidden-xs" style="background: url(images/<?php echo $selectedBg; ?>) 40% no-repeat;"></div>
</div>
<div class="col-md-7">
<h2><small>Latest from the</small> Blog</h2>
<div class="box-tab">
<?php echo RSS_Links($url, 2); ?>
</div>
<div class="box-dash">
<p>The <span class="h4">North Central</span> Region serves Franklin, Liberty, Gadsden, Leon, Wakulla, Jefferson, Madison, Taylor, Lafayette, Dixie, Suwannee, Hamilton, Columbia, Union and Baker Counties.</p>
<!-- Interactive SVG Map -->
<div class="center-block hidden-xs" id="ncmap"></div>
<img class="img-responsive visible-xs" src="images/nc_counties_map.svg" />
<p>The North Central Region is hosted by
the University of West Florida and is located in Tallahassee at <a href="https://goo.gl/maps/w19di">1022 DeSoto Park Dr.</a> </p>
</div>
</div><!-- /.col -->
<div class="col-md-5">
<h2>Upcoming Events</h2>
<div class="box-tab events-box">
<!-- Non-mobile list (larger) -->
<div class="hidden-xs">
<?php
$regionArray = array($table);
echoUpcomingEventsBox($regionArray,5);
?>
</div>
<!-- Mobile events list -->
<div class="visible-xs">
<?php
$regionArray = array($table);
echoUpcomingEventsBox($regionArray,3);
?>
</div>
<p class="text-center">
<a class="btn btn-primary btn-sm" href="eventList.php">View more</a>
</p>
</div>
<h3>Newsletter <small>Signup</small></h3>
<form role="form" method="get" action="newsletter.php">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="email" placeholder="<EMAIL>">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div><!-- /.col -->
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div> <!-- /.col -->
</div><!-- /.row one -->
<div class="row">
<div class="col-md-4">
<div class="region-callout-box nc-volunteer">
<h1>Volunteer</h1>
<p>Opportunities to get your hands dirty.</p>
<a href="volunteer.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="region-callout-box nc-explore">
<h1>Explore</h1>
<p>Discover historical and archaeological sites!</p>
<a href="explore.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="region-callout-box nc-speakers">
<h1>Speakers</h1>
<p>Request a speaker for your meeting or event.</p>
<a href="presentations.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
</div><!-- /.row two -->
</div><!-- /.page-content /.container-fluid -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#ncmap').mapSvg({
source: 'images/nc_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //North Central Region Marker
xy:[150,150],
tooltip:'North Central Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Gadsden' :{popover:'<h3>Gadsden</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=gadsden"> Explore Gadsden County</a></p>'},
'Leon' :{popover:'<h3>Leon</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=leon"> Explore Leon County</a></p>'},
'Liberty' :{popover:'<h3>Liberty</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=liberty"> Explore Liberty County</a></p>'},
'Franklin' :{popover:'<h3>Franklin</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=franklin"> Explore Franklin County</a></p>'},
'Wakulla' :{popover:'<h3>Wakulla</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=wakulla"> Explore Wakulla County</a></p>'},
'Jefferson' :{popover:'<h3>Jefferson</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=jefferson"> Explore Jefferson County</a></p>'},
'Madison' :{popover:'<h3>Madison</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=madison"> Explore Madison County</a></p>'},
'Taylor' :{popover:'<h3>Taylor</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=taylor"> Explore Taylor County</a></p>'},
'Hamilton' :{popover:'<h3>Hamilton</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=hamilton"> Explore Hamilton County</a></p>'},
'Suwannee' :{popover:'<h3>Suwannee</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=suwannee"> Explore Suwannee County</a></p>'},
'Lafayette' :{popover:'<h3>Lafayette</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=lafayette"> Explore Lafayette County</a></p>'},
'Dixie' :{popover:'<h3>Dixie</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=dixie"> Explore Dixie County</a></p>'},
'Columbia' :{popover:'<h3>Columbia</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=columbia"> Explore Columbie County</a></p>'},
'Baker' :{popover:'<h3>Baker</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=baker"> Explore Baker County</a></p>'},
'Union' :{popover:'<h3>Union</h3><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=union"> Explore Union County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Workshops - Project Archaeology";
include('../_header.php');
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1> Workshops, <small>Project Archaeology</small></h1>
<h3>Investigating Shelter</h3>
</div>
<div class="col-lg-8 col-lg-push-2 col-sm-10 col-sm-push-1 box-tab box-line row">
<div class="col-sm-12 text-center">
<img class="img-responsive" src="images/projectArchaeology.jpg" width="350" height="142" alt="FPAN staff demonstrates activity for teachers" >
</div>
<p><strong>Project Archaeology: Investigating Shelter</strong> is a supplementary science and social studies curriculum unit for grades 3 through 5. This workshop aims to familiarize educators with archaeology resources for the classroom that enhance learning opportunities in math, science, art, and social studies. Workshop participants will receive archaeology education guides published by Project Archaeology that take students through scientific processes and an archaeological investigation of Kingsley Plantation, including accounts from oral history, use of primary documents, and interpreting the archaeological record. </p>
<p>To learn more about Project Archaeology, visit <a href="http://www.projectarchaeology.org">www.projectarchaeology.org</a>. </p>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
session_start();
//If user is already logged in, redirect to control panel
if(isset($_SESSION['email']) && ($_GET['logout'] != 1) )
header("location:eventList.php");
//If the form was submitted
if($submit){
$link = mysql_connect('fpanweb.powwebmysql.com', 'fam_user', ')OKM9ijn');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(fam_events);
// Define $myusername and $mypassword
$email = $_POST['email'];
$password = $_POST['password'];
$_SESSION['aes_key'] = "<KEY>";
// To protect MySQL injection
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
//Check database for user
$sql = "SELECT * FROM users WHERE email='$email' and password=<PASSWORD>('$password', '$_SESSION[aes_key]')";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
// If there is one row, username and password are correct
if($count==1){
$userInfo = mysql_fetch_array($result);
$_SESSION['region'] = $userInfo['region'];
// Set session var for email to verify login
$_SESSION['email']=$email;
//Redirect to control panel
//header("location:adminHome.php");
?>
<script type="text/javascript">
<!--
window.location = "eventList.php";
//-->
</script>
<?php
}else{
$msg = "Invalid username or password.";
$err = true;
}
}
if((!isset($_SESSION['email'])) && ($_GET['loggedIn'] == "no") && ($_GET['logout'] != 1)){
$msg = "You are not currently logged in.";
$err = true;
}
if($_GET['logout'] == 1){
$msg = "You have logged out.";
session_destroy();
}
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table">
<tr>
<td class="lg_mid">
<h1 align="center"> Administration </h1>
<?php
if($msg){
if($err) $class = "err_msg";
else $class = "msg";
echo "<p align=\"center\" class=\"$class\"> $msg </p>";
}
?>
<form action="index.php" method="post">
<table width="250" border="0" align="center" cellpadding="3" cellspacing="0" >
<tr>
<td><div align="right">Email:</div></td>
<td><input name="email" id="email" type="text" size="35" >
</td>
</tr>
<tr>
<td><div align="right">Password:</div></td>
<td><input name="<PASSWORD>" id="password" type="<PASSWORD>" >
</td>
</tr>
<tr>
<td colspan="2" valign="middle"><div align="center"> <br />
<input name="submit" type="submit" value="Login" />
</div></td>
</tr>
<tr>
<td colspan="2">
<div align="center"><a href="adminHome.php"> Logged in? </a></div>
</td>
</tr>
</table>
</form>
<!-- </cfif> -->
</td>
</tr>
</table>
<div class="clearFloat"></div>
</div>
<?php include '../footer.php';?><file_sep><?php
$pageTitle = "Site Protection";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-dash">
<div class="text-center">
<div class="image text-center">
<img src="images/siteprotection.jpg" class="img-responsive" width="500" />
<p> A sign at Maximo Point Park in St Petersburg reminds visitors not to remove artifacts.</p>
</div>
</div>
<p>Florida’s archaeology sites are a precious, nonrenewable resource. Here are some ways that citizens can help protect and preserve archaeology sites.</p>
<h3>For the General Public</h3>
<p>There are three mechanisms to protect archaeological and historic sites. They occur at the local, state, and national levels. For information on each of these check out the links below. If you have questions please feel free to <a href="<EMAIL>">contact us.</a></p>
<strong>Florida Master Site File</strong>
<p>The <a href="http://www.flheritage.com/preservation/sitefile/" target="_blank">Florida Master Site File</a> is the State of Florida's official inventory of historical and cultural resources. Categories of resources recorded at the Site File include: archaeological sites, historical structures, historical cemeteries, historical bridges, historic districts. If you believe you have a site on your property, please <a href="mailt:<EMAIL>">contact us</a>, and we will help you fill out a site file form and submit it.</p>
<strong>Local Landmark Designation</strong>
<p>The strongest tools for preservation can be found at the local level. Cities and counties that participate in the Certified Local Government (CLG) program provide their citizens with ways to protect sites and historic structures at the local level. Check the list below, or check out the <a href="http://www.flheritage.com/preservation/clg/" target="_blank">Divison of Historical Resources page on CLGs</a>, to see if your community is a CLG and learn more about how you can participate in the local landmark designation process.</p>
<ul>
<li><a target="_blank" href="http://www.auburndalefl.com/citycom_dev.asp">City of Auburndale</a> - <a target="_blank" href="http://auburndale-fl.eregulations.us/rule/coor/coor_ptii_ch7_artii">Ordinance</a></li>
<li><a target="_blank" href="http://www.townofbelleair.com/index.aspx?NID=103">Town of Belleair </a></li>
<li><a target="_blank" href="http://mygulfport.us/">City of Gulfport</a> - <a target="_blank" href="https://library.municode.com/HTML/10876/level3/COOR_CH22ZO_ARTXXIHIPR.html#TOPTITLE">Ordinance</a></li>
<li><a target="_blank" href="http://www.hcbcc.net/departments/development_services/planning/index.php">Highlands County</a> - <a target="_blank" href="https://library.municode.com/HTML/10921/level2/COOR_CH5.3HIPR.html#TOPTITLE">Ordinance</a> </li>
<li><a target="_blank" href="http://hillsboroughcounty.org/index.aspx?NID=875">Hillsborough County</a> - <a target="_blank" href="https://library.municode.com/HTML/12399/level2/ARTIIISPDI_PT3.03.00HIPR.html#TOPTITLE">Ordinance</a> </li>
<li><a target="_blank" href="http://www.lakelandgov.net/commdev/communitydevelopment/historicpreservation.aspx">City of Lakeland </a>- <a target="_blank" href="https://www.lakelandgov.net/Portals/CommDev/Planning Division/Historic Preservation/Ord4898.pdf">Ordinance</a></li>
<li><a target="_blank" href="http://www.plantcitygov.com/index.aspx?nid=118&PREVIEW=YES">City of Plant City</a> - <a target="_blank" href="https://library.municode.com/HTML/10202/level2/SPAGEOR_CH38HIPR.html#TOPTITLE">Ordinance</a></li>
<li><a target="_blank" href="http://www.stpetebeach.org/city-commisson/historic-preservation.html">City of St Pete Beach</a> - <a target="_blank" href="https://library.municode.com/HTML/13806/level2/CO_DIV28HIPR.html#TOPTITLE">Ordinance</a></li>
<li><a target="_blank" href="http://www.stpete.org/historic_preservation/">City of St Petersburg</a> - <a target="_blank" href="https://library.municode.com/HTML/14674/level3/PTIISTPECO_CH16LADERE_S16.30.070HIARPROV.html#TOPTITLE">Ordinance</a></li>
<li><a target="_blank" href="http://www.sarasotagov.com/InsideCityGovernment/Content/CAC/AdvisoryBoard/ADVBRD-HPB-Summary.htm">City of Sarasota</a> - <a target="_blank" href="https://library.municode.com/HTML/19998/level2/ARTIVDEREPR_DIV8HIRESTARSI.html#TOPTITLE">Ordinance</a></li>
<li><a target="_blank" href="https://www.scgov.net/History/Pages/HistoricDesignation.aspx">Sarasota County</a> - <a target="_blank" href="https://library.municode.com/HTML/11511/level2/PTIICOOR_CH66HIPR.html#TOPTITLE">Ordinance</a></li>
<li><a target="_blank" href="http://www.tampagov.net/dept_historic_preservation/">City of Tampa</a> - <a target="_blank" href="https://library.municode.com/HTML/10132/level3/COORTAFL_CH27ZOLADE_ARTVHIPR.html#TOPTITLE">Ordinance</a></li>
<li><a target="_blank" href="http://www.ctsfl.us/DevelopmentServices/HistoricPreservation.html">City of Tarpon Springs </a>- <a target="_blank" href="https://library.municode.com/HTML/11091/level3/COOR_APCOZOLADECO_ARTVIIHEPR.html#TOPTITLE">Ordinance</a></li>
</ul>
<strong>National Register of Historic Places</strong>
<p>Listing in the <a target="_blank" href="http://www.nps.gov/nr/">National Register of Historic Places</a> provides formal recognition of a property’s historical, architectural, or archeological significance based on national standards used by every state. If you have questions about a site’s eligibility, or would like more information on the nomination process <a href="mailto:<EMAIL>">contact us</a>.</p>
<h3>For Local and State Land Managers</h3>
<p>FPAN provides training on how to effectively manage archaeological and historical sites. Check the <a href="../workshops.php">Trainings and Workshops</a> page for more information or <a href="mailto:<EMAIL>">contact us</a> to set one up in your area.</p>
</div><!-- /.box-dash -->
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
include 'appHeader.php';
include $header;
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<td class="lg_mid">
<h1>Overview</h1>
<p>Welcome to the control panel!</p>
</td>
</tr>
</table>
<?php include 'adminBox.php'; ?><br/>
<?php include '../calendar.php'; ?>
<!-- End Main div -->
<div class="clearFloat"></div>
</div>
<?php include $footer; ?><file_sep><?php
if (!defined('WEBPATH')) die();
$firstPageImages = setThemeColumns('2', '6');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s').' GMT');
$pageTitle = " - " . getBareAlbumTitle() . " | " . getBareImageTitle();
include 'header.php';
zp_apply_filter("theme_head");
//require_once(SERVERPATH.'/'.ZENFOLDER.'/js/colorbox/colorbox_ie.css.php')
?>
<script src="<?php echo FULLWEBPATH . "/" . ZENFOLDER ?>/js/colorbox/jquery.colorbox-min.js" type="text/javascript"></script>
<script type="text/javascript">
// <!-- <![CDATA[
$(document).ready(function(){
$(".colorbox").colorbox({inline:true, href:"#imagemetadata"});
});
// ]]> -->
</script>
<!-- Main Left Side -->
<div id="left_side">
<div id="navbar">
<div id="navbar_top"> </div>
<div id="album_container">
<ul class="album_ul">
<li><a href="http://flpublicarchaeology.org/civilwar">Home</a></li>
<li><a href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=http:%2F%2Fwww.flpublicarchaeology.org%2Fcivilwar%2Fsites.kmz&sll=37.0625,-95.677068&sspn=58.72842,135.263672&ie=UTF8&t=h&ll=28.960089,-83.748779&spn=5.689017,9.371338&z=7" target="_blank">Map of Sites</a></li>
<li><a href="http://flpublicarchaeology.org/links.php#civilwar">Sesquicentennial Links</a></li>
</ul>
<img src="http://www.flpublicarchaeology.org/images/nav_div.png" width="180" height="4" alt="divider"/>
<?php printAlbumMenuList("list","","","active_album","album_ul","active_album","");?>
</div>
<div id="navbar_bottom"> </div>
</div>
<!-- <table class="newsletter_table" cellpadding="0" cellspacing="0">
<tr>
<th class="newsletter_header"></th>
</tr>
<tr>
<td class="newsletter_table_mid">
</td>
</tr>
<tr>
<td class="newsletter_bottom"></td>
</tr>
</table>-->
</div>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1><?php echo getBareAlbumTitle();?></h1></th>
</tr>
<tr>
<td class="table_mid">
<div align="center">
<h3><?php printImageTitle(true); ?></h3>
<br/>
<div class="imgnav">
<?php if (hasPrevImage()) { ?>
<div class="imgprevious"><a class="dark" href="<?php echo htmlspecialchars(getPrevImageURL());?>" title="<?php echo gettext("Previous Image"); ?>">« <?php echo gettext("prev"); ?></a></div>
<?php } if (hasNextImage()) { ?>
<div class="imgnext"><a class="dark" href="<?php echo htmlspecialchars(getNextImageURL());?>" title="<?php echo gettext("Next Image"); ?>"><?php echo gettext("next"); ?> »</a></div>
<?php } ?>
</div>
<!-- The Image -->
<div id="image">
<strong>
<?php
$fullimage = getFullImageURL();
if (!empty($fullimage)) {
?>
<a href="<?php echo htmlspecialchars($fullimage);?>" title="<?php echo getBareImageTitle();?>">
<?php
}
if (function_exists('printUserSizeImage') && isImagePhoto()) {
printUserSizeImage(getImageTitle());
} else {
printDefaultSizedImage(getImageTitle());
}
if (!empty($fullimage)) {
?>
</a>
<?php
}
?>
</strong>
<?php
if (function_exists('printUserSizeImage') && isImagePhoto()) printUserSizeSelectior(); ?>
</div>
<div id="narrow">
<br/>
<small><?php printImageDesc(true); ?></small>
<?php if (function_exists('printSlideShowLink')) printSlideShowLink(gettext('View Slideshow')); ?>
<br />
<br clear="all" />
<?php if (function_exists('printGoogleMap')) printGoogleMap(); ?>
</div>
<div id="credit">
<?php printZenphotoLink(); ?>
<?php
if (function_exists('printUserLogin_out'))
printUserLogin_out(" | ");
?>
</div>
<?php printAdminToolbox(); ?>
</div>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?>
<file_sep><?php
$pageTitle = "Contact";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-6 col-sm-push-3">
<h3>Address</h3>
<p class="text-center">
207 East Main Street<br/>
Pensacola, FL 32591-2486<br/>
</p>
<h3>Fax</h3>
<p class="text-center">(850) 595-0052 </p>
</div>
</div>
<div class="staff-box row">
<div class="col-sm-6">
<img src="/images/people/barbara.jpg" class="img-circle img-responsive" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME>, RPA</strong>
<em>Northwest Region Director</em><br/>
(850) 933-5779<br/>
<a href="mailto:<EMAIL>"><EMAIL></a>
<strong onclick="javascript:showElement('barbara_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="barbara_bio" class="hidden bio">
<NAME> is a Registered Professional Archaeologist who specializes in historic archaeology, 19th and early 20th century. Her interests include the turpentine and lumber industry, specifically focusing on the social aspects of "camp life". She also has taken an interest in early Florida architecture, and did her thesis work on an early 1900s Folk Victorian structure in Sopchoppy, Florida. Her thesis focused on examining the relationship between architecture, societal relationships and social class perceptions. Barbara has also taken an interest in Southeastern Indian communities after European contact, specifically in the late 1800 up to the present, focusing on the mixing of cultures and how the Southeastern Indian population has survived and adapted.
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6 ">
<img src="/images/people/nicole.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME>, M.A., RPA</strong>
<em>Public Archaeology Coordinator</em><br/>
(850) 595-0050 Ext 103<br/>
<a href="mailto:<EMAIL>"><EMAIL></a><br/>
<strong onclick="javascript:showElement('nicole_bio');">View Bio <span class="glyphicon glyphicon-collapse-down"></span></strong>
</p>
</div>
<div class="col-xs-12">
<p id="nicole_bio" class="hidden">
<NAME> graduated with a Master’s degree in Historical Archaeology from the University of West Florida, as well as with a Bachelor’s degree in Anthropology and a Bachelor’s degree in History from the University of Central Florida. Nicole is also certified as a SCUBA Instructor with SCUBA Diving International (SDI). Before joining FPAN as the Northwest Regional Center’s Public Archaeology Coordinator in 2012, Nicole worked as an intern with the NASA History Division, FPAN, and Biscayne National Park. Nicole is also Graduate Student Representative for the Advisory Council on Underwater Archaeology (ACUA), a member of the Register of Professional Archaeologists (RPA), and a Certified Interpretive Guide through the National Association for Interpretation (NAI). Her research interests include maritime archaeology and history, public interpretation of maritime cultural resources, and social history.
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6 ">
<img src="/nwrc/images/Gregg.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Graduate Assistant</em><br/>
(850) 595-0050 Ext 104<br/>
<a href="mailto:<EMAIL>"><EMAIL></a><br/>
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6 ">
<img src="/nwrc/images/Janene.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Graduate Assistant</em><br/>
(850) 595-0050 Ext 104<br/>
<a href="mailto:<EMAIL>"><EMAIL></a><br/>
</p>
</div>
</div><!-- /.row -->
<div class="staff-box row">
<div class="col-sm-6 ">
<img src="/nwrc/images/Katherine.jpg" class="img-circle img-responsive center-block" />
</div>
<div class="col-sm-6">
<p>
<strong><NAME></strong>
<em>Graduate Assistant</em><br/>
(850) 595-0050 Ext 104<br/>
<a href="mailto:<EMAIL>"><EMAIL></a><br/>
</p>
</div>
</div><!-- /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
/****************************************************************************************************************/
/******************************************** Misc Functions ************************************************/
/****************************************************************************************************************/
//Determine if user has editing priveleges
function canEdit(){
//Interns/other staff can't edit
if($_SESSION['my_role'] == 3)
return false;
else
return true;
}
//Determine if user is admin, can see all regions
function isAdmin(){
//Interns/other staff can't edit
if($_SESSION['my_role'] == 1)
return true;
else
return false;
}
//Truncate a given $string up to a $limited number of characters
function truncate($string, $limit, $break=" ", $pad="..."){
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit) return $string;
$string = substr($string, 0, $limit);
if(false !== ($breakpoint = strrpos($string, $break))) {
$string = substr($string, 0, $breakpoint);
}
return $string . $pad;
}
//Return properly formatted title of given activity
function getTitle($typeActivity){
if($typeActivity == "PublicOutreach"){
$title = "Public Outreach";
}
if($typeActivity == "TrainingWorkshops"){
$title = "Training / Workshops";
}
if($typeActivity == "GovernmentAssistance"){
$title = "Government Assistance";
}
if($typeActivity == "Meeting"){
$title = "Meeting";
}
if($typeActivity == "SocialMedia"){
$title = "Social Media";
}
if($typeActivity == "PressContact"){
$title = "Press Contact";
}
if($typeActivity == "Publication"){
$title = "Publication";
}
if($typeActivity == "DirectMail"){
$title = "Direct Mail / Newsletter";
}
if($typeActivity == "ServiceToProfessionalSociety"){
$title = "Service To Professional Society";
}
if($typeActivity == "ServiceToHostInstitution"){
$title = "Service To Host Institution";
}
if($typeActivity == "ServiceToCommunity"){
$title = "Service To Community";
}
if($typeActivity == "TrainingCertificationEducation"){
$title = "Training / Certification / Education";
}
if($typeActivity == "ConferenceAttendanceParticipation"){
$title = "Conference Attendance / Participation";
}
return $title;
}
//Return appropriate page name for a given activity
function getPage($typeActivity){
if($typeActivity == "PublicOutreach"){
$page = "publicOutreach.php";
}
if($typeActivity == "TrainingWorkshops"){
$page = "trainingWorkshops.php";
}
if($typeActivity == "GovernmentAssistance"){
$page = "governmentAssistance.php";
}
if($typeActivity == "SocialMedia"){
$page = "socialMedia.php";
}
if($typeActivity == "Meeting"){
$page = "meeting.php";
}
if($typeActivity == "PressContact"){
$page = "pressContact.php";
}
if($typeActivity == "Publication"){
$page = "publication.php";
}
if($typeActivity == "DirectMail"){
$page = "directMail.php";
}
if($typeActivity == "ServiceToProfessionalSociety"){
$page = "serviceToProfessionalSociety.php";
}
if($typeActivity == "ServiceToHostInstitution"){
$page = "serviceToHostInstitution.php";
}
if($typeActivity == "ServiceToCommunity"){
$page = "serviceToCommunity.php";
}
if($typeActivity == "TrainingCertificationEducation"){
$page = "trainingCertificationEducation.php";
}
if($typeActivity == "ConferenceAttendanceParticipation"){
$page = "conferenceAttendanceParticipation.php";
}
return $page;
}
//Return array of all 8 region codes
function getRegionArray(){
return array('nwrc', 'ncrc', 'nerc', 'wcrc', 'crc', 'ecrc', 'swrc', 'serc');
}
//Return region name from regoin code
function getRegionName($regionCode){
switch($regionCode){
case "nwrc": $regionName = "Northwest";
break;
case "ncrc": $regionName = "North Central";
break;
case "nerc": $regionName = "Northeast";
break;
case "wcrc": $regionName = "West Central";
break;
case "crc": $regionName = "Central";
break;
case "ecrc": $regionName = "East Central";
break;
case "serc": $regionName = "Southeast";
break;
case "swrc": $regionName = "Southwest";
break;
}
return $regionName;
}
//Return array of text values of each ACTIVITY type
function getTypeActivityArray(){
return array("PublicOutreach", "TrainingWorkshops", "GovernmentAssistance", "Meeting", "SocialMedia", "PressContact", "Publication", "DirectMail");
}
//Return array of text values of each SERVICE type
function getTypeServiceArray(){
return array("ServiceToProfessionalSociety", "ServiceToHostInstitution", "ServiceToCommunity", "TrainingCertificationEducation", "ConferenceAttendanceParticipation");
}
//Get exact current page URL
function curPageURL(){
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
/****************************************************************************************************************/
/********************************** FPAN Activity Functions *************************************************/
/****************************************************************************************************************/
//Return an array of
function getActivity($table, $id){
$sql = "SELECT * FROM $table WHERE id='$id' ";
$results = mysql_query($sql);
$results_array = array();
if(mysql_num_rows($results) != 0)
$results_array = mysql_fetch_assoc($results);
//Get staffInvolved array from EmployeeActivity table, also store in a second array for comparison after edits
$sql = "SELECT employeeID FROM EmployeeActivity
WHERE activityID = '$id'";
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results)){
$results_array['staffInvolved'][] = $row['employeeID'];
}
return $results_array;
}
//Print Details of a SINGLE activity
function printActivity($activityArray){
echo "<div>";
//Loop formVars array and print key and value of each element
foreach($activityArray as $key => $value){
if(!in_array($key, $_SESSION['excludeKeys'])){
$varName = ucfirst($key);
$varName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $varName);
echo "<strong>".$varName.": </strong>".$value."<br/>";
}
}
//Display staff involved, if there were any
if($activityArray['staffInvolved']){
$sql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($sql);
echo "<strong>The staff involved:</strong> <br/>";
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName']." ".$employee['lastName'];
if(in_array($employee['id'], $activityArray['staffInvolved']))
echo "<span style=\"margin-left:10px;\">". $employeeName."</span><br/>";
}
}
echo "</div>";
}
// **************************************************************************************
//Return an ARRAY of all FPAN activities that user is allowed to see from specified table
function getActivities($table, $startDate = NULL, $endDate = NULL, $region = NULL){
// *****************************************************************************************************************
// SQL for region-specific activities if user is outreach coordinator/intern/other staff or region was specified
// Inlcudes events that were either submitted BY an employee in that region as well as events they were tagged in
// *****************************************************************************************************************
if(($_SESSION['my_role'] != 1) || (($region != NULL) && ($region != 'All'))){
if($_SESSION['my_role'] != 1)
$sql_region = join('\',\'',$_SESSION['my_regions']);
else
$sql_region = $region;
//Get an array of EmployeeIDs because the MySQL server is an asshole and bogs down when you use subqueries
$sql="SELECT employeeID FROM EmployeeRegion WHERE region IN ('$sql_region')";
$results = mysql_query($sql);
echo mysql_error();
$employeeIDArray = array();
if(mysql_num_rows($results) != 0)
while($row = mysql_fetch_assoc($results)){
array_push($employeeIDArray,$row['employeeID']);
}
$sql="";
$employeeIDArray = join(',',$employeeIDArray);
//Find any event where the submit_id is by an employee from region
$sql = "SELECT * FROM $table
WHERE submit_id IN ($employeeIDArray) ";
//If dates were specified return only events between those dates
if($startDate && $endDate)
$sql.= "AND activityDate BETWEEN '$startDate' AND '$endDate' ";
$sql.= "UNION ";
$sql.= "SELECT * FROM $table WHERE id IN (SELECT activityID FROM EmployeeActivity
WHERE employeeID IN ($employeeIDArray)) ";
//If dates were specified return only events between those dates
if($startDate && $endDate)
$sql.= "AND activityDate BETWEEN '$startDate' AND '$endDate' ";
$sql.= "ORDER BY activityDate DESC; ";
// **********************************************************************
// SQL for all activities if user is admin and no region specified
// **********************************************************************
}elseif(($_SESSION['my_role'] == 1)){
$sql = "SELECT * FROM $table ";
//If dates were specified return only events between those dates
if($startDate && $endDate)
$sql.= "WHERE activityDate BETWEEN '$startDate' AND '$endDate' ";
$sql.= "ORDER BY activityDate DESC; ";
}
//echo $sql."<br/><br/>";
$results = mysql_query($sql);
echo mysql_error();
$results_array = array();
if(mysql_num_rows($results) != 0)
while($row = mysql_fetch_assoc($results)){
$results_array[] = $row;
}
return $results_array;
}
// ****************************************************************************************************************************
//Print a number of activities of a given type
function printActivities($typeActivity, $displayLimit, $startDate = NULL, $endDate = NULL, $region = NULL, $showTitle = false){
//Generate an array of specified results
$activityArray = array();
$activityArray = getActivities($typeActivity, $startDate, $endDate, $region);
echo "<div class=\"resultsDiv\">";
if($showTitle)
echo "<p><strong>".getTitle($typeActivity)."</strong> - <a href=\"viewTypeActivities.php?typeActivity=".$typeActivity."\">View All</a>";
echo "<span class=\"resultsSummary\">Showing up to ";
if($displayLimit > 500){echo "All";}
else{echo $displayLimit;}
echo " of <strong>" . count($activityArray) . "</strong> activities found.</span></p>";
$startLimit = 1;
$tableClass = "tablesorter";
$tableID = "resultsTable".$typeActivity;
echo "<table class=$tableClass id=$tableID>";
echo "<thead>";
if($typeActivity == "PublicOutreach"){
echo "<tr><td id=\"blank_cell\"></td>";
echo "<th class=\"date\">Date</th>";
echo "<th class=\"county\">County</th>";
echo "<th class=\"activity\">Activity</th>";
echo "<th class=\"numAttendees\">Attnd.</th>";
echo "<th clas=\"eventName\">Event Name</tr> ";
echo "</thead>";
echo "<tbody>";
foreach($activityArray as $activity){
echo "<tr><td class>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View-Edit-Delete</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['county']."</td><td>";
echo $activity['typeActivity']."</td><td>";
echo $activity['numberAttendees']."</td><td>";
echo truncate(stripslashes($activity['activityName']), 25, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "TrainingWorkshops"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td>";
echo "<th class=\"date\">Date</th>";
echo "<th class=\"county\">County</th>";
echo "<th class=\"activity\">Activity</th>";
echo "<th class=\"numAttendees\">Attnd.</th>";
echo "<th clas=\"eventName\">Event Name</tr> ";
echo "</thead>";
echo "<tbody>";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View-Edit-Delete</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['county']."</td><td>";
echo $activity['typeActivity']."</td><td>";
echo $activity['numberAttendees']."</td><td>";
echo truncate(stripslashes($activity['activityName']), 25, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "GovernmentAssistance"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td>";
echo "<th class=\"date\">Date</th>";
echo "<th class=\"county\">County</th>";
echo "<th>Organization</th></tr> ";
echo "</thead>";
echo "<tbody>";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View-Edit-Delete</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['county']."</td><td>";
echo $activity['typeOrganization']."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "Meeting"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td>";
echo "<th class=\"date\">Date</th>";
echo "<th>Meeting Name</th>";
echo "<th>Category</th></tr> ";
echo "</thead>";
echo "<tbody>";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View-Edit-Delete</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo truncate(stripslashes($activity['meetingName']), 25, " ", "...")."</td><td>";
echo $activity['meetingCategory']."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "SocialMedia"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td>";
echo "<th class=\"date\">Date</th></tr>";
echo "</thead>";
echo "<tbody>";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View-Edit-Delete</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date('M, Y', $displayDate)."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "PressContact"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td>";
echo "<th class=\"date\">Date</th>";
echo "<th>Media</th>";
echo "<th>Circulation</th>";
echo "<th>Contact</th></tr> ";
echo "</thead>";
echo "<tbody>";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View-Edit-Delete</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['typeMedia']."</td><td>";
echo $activity['circulation']."</td><td>";
echo $activity['typeContact']."</td><tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "Publication"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td>";
echo "<th class=\"date\">Date</th>";
echo "<th>Media</th></tr>";
echo "</thead>";
echo "<tbody>";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View-Edit-Delete</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['typeMedia']."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeActivity == "DirectMail"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td>";
echo "<th class=\"date\">Date</th>";
echo "<th>Type Mail</th></tr>";
echo "</thead>";
echo "<tbody>";
foreach($activityArray as $activity){
echo "<tr><td>";
echo "<a href=\"viewActivity.php?id=".$activity['id']."&typeActivity=".$typeActivity."\">View-Edit-Delete</a></td><td>";
$displayDate = strtotime($activity['activityDate']);
echo date("M d, Y", $displayDate)."</td><td>";
echo $activity['typeMail']."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
echo "</tbody>";
echo "</table>";
echo "</div>";
}
/****************************************************************************************************************/
/********************************** Professional Service Functions ******************************************/
/****************************************************************************************************************/
//Return an array of all FPAN activities that user is allowed to see from specified table
function getService($table, $id){
$sql = "SELECT * FROM $table WHERE id='$id' ";
$results = mysql_query($sql);
$results_array = array();
if(mysql_num_rows($results) != 0)
$results_array = mysql_fetch_assoc($results);
//Get staffInvolved array from EmployeeActivity table, also store in a second array for comparison after edits
$sql = "SELECT employeeID FROM EmployeeActivity
WHERE activityID = '$id'";
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results)){
$results_array['staffInvolved'][] = $row['employeeID'];
}
return $results_array;
}
//Print Details of a single activity
function printService($serviceArray){
echo "<div style=\"text-align:left; margin-left:100px;\">";
//Loop formVars array and print key and value of each element
foreach($serviceArray as $key => $value){
if(!in_array($key, $_SESSION['excludeKeys'])){
$varName = ucfirst($key);
$varName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $varName);
echo "<strong>".$varName.": </strong>".$value."<br/>";
}
}
//Display staff involved, if there were any
if($serviceArray['staffInvolved']){
$sql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($sql);
echo "<strong>The staff involved:</strong> <br/>";
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName']." ".$employee['lastName'];
if(in_array($employee['id'], $serviceArray['staffInvolved']))
echo "<span style=\"margin-left:10px;\">". $employeeName."</span><br/>";
}
}
echo "</div>";
}
// ******************************************************************************************
//Return array of all Professional Service events user is allowed to see from specified table
function getServices($table, $startDate = NULL, $endDate = NULL, $region = NULL){
//SQL for region-specific activities if user is outreach coordinator/intern/other staff
if(($_SESSION['my_role'] != 1) || (($region != NULL) && ($region != 'All'))){
if($_SESSION['my_role'] != 1)
$sql_region = join('\',\'',$_SESSION['my_regions']);
else
$sql_region = $region;
/*
$sql = "SELECT *, $table.id AS service_id
FROM $table
JOIN Employees
ON $table.submit_id = Employees.id
WHERE $table.submit_id IN
(SELECT employeeID FROM EmployeeRegion
WHERE region IN ('$sql_region'))) ";
*/
$sql = "SELECT * FROM $table
JOIN Employees
ON $table.submit_id = Employees.id
WHERE $table.submit_id IN
(SELECT employeeID FROM EmployeeRegion WHERE region IN ('$sql_region')) ";
if($startDate && $endDate)
$sql.= "AND serviceDate BETWEEN '$startDate' AND '$endDate' ";
$sql.= "ORDER BY serviceDate DESC";
// **********************************************************************
// SQL for all region activities if user is admin and no region specified
// **********************************************************************
}elseif(($_SESSION['my_role'] == 1)){
$sql = "SELECT *, $table.id AS service_id
FROM $table
JOIN Employees
ON $table.submit_id = Employees.id ";
if($startDate && $endDate)
$sql.= "AND serviceDate BETWEEN '$startDate' AND '$endDate' ";
$sql.= "ORDER BY serviceDate DESC";
}
$results = mysql_query($sql);
$results_array = array();
if(mysql_num_rows($results) != 0)
while($row = mysql_fetch_assoc($results)){
$results_array[] = $row;
}
return $results_array;
}
// *************************************************************************************************************************
//Print a number services of a given type
function printServices($typeService, $displayLimit, $startDate = NULL, $endDate = NULL, $region = NULL, $showTitle = false){
//Generate an array of specified results
$serviceArray = array();
$serviceArray = getServices($typeService, $startDate, $endDate);
echo "<div class=\"resultsDiv\">";
if($showTitle)
echo "<p><strong>".getTitle($typeService)."</strong> - <a href=\"viewTypeActivities.php?typeActivity=".$typeService."\">View All</a>";
echo "<span class=\"resultsSummary\">Showing up to ";
if($displayLimit > 500){echo "All";}
else{echo $displayLimit;}
echo " of <strong>".count($serviceArray)."</strong> services found.</span></p>";
$startLimit = 1;
$tableClass = "tablesorter";
$tableID = "resultsTable".$typeService;
echo "<table class=$tableClass id=$tableID>";
echo "<thead>";
if($typeService == "ServiceToProfessionalSociety"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><th class=\"date\">Date</th><th>Employee</th><th>Society</th><th>Comments</th></tr> ";
echo "</thead>";
echo "<tbody>";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View-Edit-Delete</a> </td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
echo $employeeName."</td><td>";
echo $service['typeSociety']."</td><td>";
echo truncate(stripslashes($service['comments']), 25, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "ServiceToHostInstitution"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><th class=\"date\">Date</th><th>Employee</th><th>Comments</th></tr> ";
echo "</thead>";
echo "<tbody>";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View-Edit-Delete</a> </td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
echo $employeeName."</td><td>";
echo truncate(stripslashes($service['comments']), 25, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "ServiceToCommunity"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><th class=\"date\">Date</th><th>Employee</th><th>Comments</th></tr> ";
echo "</thead>";
echo "<tbody>";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View-Edit-Delete</a> </td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
echo $employeeName."</td><td>";
echo truncate(stripslashes($service['comments']), 25, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "TrainingCertificationEducation"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><th class=\"date\">Date</th><th>Employee</th><th>Type</th><th>Comments</th></tr> ";
echo "</thead>";
echo "<tbody>";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View-Edit-Delete</a> </td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
echo $employeeName."</td><td>";
echo $service['typeTraining']."</td><td>";
echo truncate(stripslashes($service['comments']), 25, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
if($typeService == "ConferenceAttendanceParticipation"){
echo "<tr id=\"head_row\"><td id=\"blank_cell\"></td><th class=\"date\">Date</th><th>Employee</th><th>Type</th><th>Comments</th></tr> ";
echo "</thead>";
echo "<tbody>";
foreach($serviceArray as $service){
echo "<tr><td>";
echo "<a href=\"viewService.php?id=".$service['service_id']."&typeService=".$typeService."\">View-Edit-Delete</a> </td><td>";
$displayDate = strtotime($service['serviceDate']);
echo date("M, Y", $displayDate)."</td><td>";
$employeeName = $service['firstName']." ".$service['lastName'];
echo $employeeName."</td><td>";
echo $service['typeConference']."</td><td>";
echo truncate(stripslashes($service['comments']), 25, " ", "...")."</td></tr>";
if($startLimit++ == $displayLimit){break;}
}
}
echo "</tbody>";
echo "</table>";
echo "</div>";
}
?><file_sep><?php
// Zenphoto theme definition file
$theme_description['name'] = 'zenphone';
$theme_description['author'] = '<NAME>';
$theme_description['version'] = '1.3.1';
$theme_description['date'] = '06/04/2010';
$theme_description['desc'] = gettext("A theme that ties ZenPhoto into the iPhone\Touch interface.");
?><file_sep><?php
include '../admin/dbConnect.php';
include '../_publicFunctions.php';
$table='nwrc';
?>
<!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>Destination Archaeology Resource Center<?php if($pageTitle){echo " - ".$pageTitle;} ?></title>
<meta name="DESCRIPTION" content=""/>
<meta name="KEYWORDS" content=""/>
<!-- Favicon -->
<link rel="shortcut icon" href="http://fpan.us/images/favicon.ico" type="image/x-icon" />
<!-- All Inclusive Stylsheet (Bootstrap, FontAwesome, FPAN Styles, NW Styles) -->
<link href="http://fpan.us/_css/darc_style.css" rel="stylesheet">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="http://fpan.us/_js/jquery.mousewheel.js"></script>
<!-- Add fancyBox main JS and CSS files -->
<script type="text/javascript" src="http://fpan.us/fancybox/source/jquery.fancybox.js"></script>
<link rel="stylesheet" type="text/css" href="http://fpan.us/fancybox/source/jquery.fancybox.css" media="screen" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Google Analytics Tracking Code -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-7301672-16', 'auto');
ga('send', 'pageview');
</script>
<script type="text/javascript">
$(document).ready(function() {
$(".fancybox").fancybox();
$(".youtube").fancybox({
maxWidth : 800,
maxHeight : 600,
fitToView : false,
width : '70%',
height : '70%',
autoSize : false,
closeClick : false,
openEffect : 'none',
closeEffect : 'none'
});
});
</script>
</head>
<body>
<nav class="navbar navbar-main" role="navigation">
<a href="http://destinationarchaeology.org"><img src="images/darc_logo.svg" class="hidden-xs"></a>
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Large branding logo image -->
<!--<a class="navbar-brand-logo hidden-xs" href="/index.php"><img src="images/darc_logo.svg" class="brand-logo"/></a>-->
<!-- Small text-only branding -->
<a class="navbar-brand visible-xs" href="destinationarchaeology.org"> Destination Archaeology </a>
</div> <!-- /.navbar-header -->
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav">
<!--<li><span class="brand-spacer hidden-xs hidden-lg"></span></li> -->
<!-- Main Nav items -->
<li class="visible-xs"><a href="#hours">Museum Hours</a></li>
<li class="<?=activeClassIfMatches('news.php')?>"><a href="news.php">News</a></li>
<li class="<?=activeClassIfMatches('exhibits.php')?>"><a href="exhibits.php">Exhibits</a></li>
<li class="<?=activeClassIfMatches('education.php')?>"><a href="education.php">Education</a></li>
<li class="dropdown <?=activeClassIfMatches('tours')?>">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Virtual Tours <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="tours-arcadia.php">Arcadia Mill</a></li>
<li><a href="tours-ftwalton.php">Ft. Walton Temple Mound</a></li>
</ul>
</li>
<li class="<?=activeClassIfMatches('programs.php')?>"><a href="programs.php">Programs</a></li>
<li class="<?=activeClassIfMatches('geotrail.php')?>"><a href="geotrail.php">GeoTrail</a></li>
<li ><a href="http://fpan.us/nwrc/volunteer.php" target="_blank">Lab</a></li>
</ul><!-- /.nav /.navbar-nav -->
</div><!-- /.navbar-collapse -->
</nav><!-- /.navbar-main --><file_sep><?php
$pageTitle = "Newsletter";
$email = isset($_GET['email']) ? $_GET['email'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle;?></h1>
</div>
<!-- Begin MailChimp Signup Form -->
<div class="col-sm-10 col-sm-push-1">
<form action="//flpublicarchaeology.us3.list-manage.com/subscribe/post?u=04e2cb7d45ab1d850e305d4e7&id=c20aa96669" role="form"
method="post" class="" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate >
<h2>Join our mailing list</h2>
<div class="form-group">
<label class="control-label " for="mce-EMAIL">Email Address</label>
<div class="row">
<div class="col-xs-10">
<input type="email" value="<?=$email?>" name="EMAIL" class="form-control" id="mce-EMAIL">
</div>
<div class="col-xs-2">
<span class="required">*</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label" for="mce-FNAME">First Name </label>
<input type="text" value="" name="FNAME" class="form-control" id="mce-FNAME">
</div>
<div class="form-group">
<label class="control-label" for="mce-LNAME">Last Name </label>
<input type="text" value="" name="LNAME" class="form-control" id="mce-LNAME">
</div>
<div class="form-group">
<label class="control-label" for="mce-MMERGE3">County </label>
<select name="MMERGE3" class="form-control" id="mce-MMERGE3">
<option value=""></option>
<option value="Escambia">Escambia</option>
<option value="Santa Rosa">Santa Rosa</option>
<option value="Okaloosa">Okaloosa</option>
<option value="Walton">Walton</option>
<option value="Holmes">Holmes</option>
<option value="Washington">Washington</option>
<option value="Bay">Bay</option>
<option value="Jackson">Jackson</option>
<option value="Calhoun">Calhoun</option>
<option value="Gulf">Gulf</option>
<option value="Other in FL">Other in FL</option>
<option value="Other outside FL">Other outside FL</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="mce-MMERGE4">Category </label>
<select name="MMERGE4" class="form-control" id="mce-MMERGE4">
<option value=""></option>
<option value="Volunteer/Advocational">Volunteer/Advocational</option>
<option value="Heritage Professional">Heritage Professional</option>
<option value="Teacher/Educator">Teacher/Educator</option>
<option value="Land Manager/Planner">Land Manager/Planner</option>
<option value="Other Interested Person">Other Interested Person</option>
</select>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_04e2cb7d45ab1d850e305d4e7_c20aa96669" tabindex="-1" value=""></div>
<div class="text-center"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn btn-primary"></div>
</form>
</div><!-- /.col -->
<!--End mc_embed_signup-->
<div class="box-tab col-sm-12">
<h2>Newsletter Archives</h2>
<script language="javascript" src="http://us3.campaign-archive2.com/generate-js/?u=04e2cb7d45ab1d850e305d4e7&fid=10409&show=10" type="text/javascript"></script>
Spring 2014 - <a href="../uploads/nwrc/FPAN%20NW%20Newsletter%20Spring%202014.pdf">FPAN Northwest Spring 2014 Newsletter</a><br/>
Winter 2013/2014 - <a href="../uploads/nwrc/FPAN%20NW%20Newsletter%20Winter%201314.pdf">FPAN Northwest Winter 2013/2014 Newsletter</a><br/>
Fall 2013 - <a href="../uploads/nwrc/FPAN NW Newsletter Fall 2013small.pdf">FPAN Northwest Fall 2013 Newsletter</a><br/>
Summer 2013 - <a href="../uploads/nwrc/FPAN NW Newsletter Summer_2013.pdf">FPAN Northwest Summer 2013 Newsletter</a><br/>
Spring 2013 - <a href="../uploads/nwrc/FPAN NW Newsletter_Spring 2013.pdf">FPAN Northwest Spring 2013 Newsletter</a><br/>
Winter 2012/2013 - <a href="../uploads/nwrc/FPAN NW Newsletter_Winter_2012_2013.pdf">FPAN Northwest Winter 2012/2013 Newsletter</a><br/>
Fall 2012 - <a href="../uploads/nwrc/FPAN NW Newsletter_Fall 2012.pdf">FPAN Northwest Fall 2012 Newsletter</a><br/>
Summer 2012 - <a href="../uploads/nwrc/FPAN NW Newsletter_Summer 2012.pdf">FPAN Northwest Summer 2012 Newsletter</a><br/>
Winter 2011/2012 - <a href="../uploads/nwrc/FPAN NW Newsletter_Winter 2012.pdf">FPAN Northwest Winter 2011/2012 Newsletter</a><br/>
Fall 2011 - <a href="../uploads/nwrc/FPAN NW Newsletter_Fall 2011.pdf">FPAN Northwest Fall 2011 Newsletter</a><br/>
Summer 2011 - <a href="../uploads/nwrc/FPAN NW Newsletter_Summer 2011.pdf">FPAN Northwest Summer 2011 Newsletter</a>
</div><!-- /.col -->
</div><!-- /.col /.row -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
/**
* Provides users a means to log in or out from the theme pages.
*
* Place a call on <var>printUserLogin_out()</var> where you want the link or form to appear.
*
* @author <NAME> (sbillard)
* @package plugins
* @subpackage users
*/
$plugin_is_filter = 900 | THEME_PLUGIN;
$plugin_description = gettext("Provides a means for users to login/out from your theme pages.");
$plugin_author = "<NAME> (sbillard)";
$option_interface = 'user_logout_options';
if (isset($_zp_gallery_page) && getOption('user_logout_login_form') > 1) {
setOption('colorbox_' . $_zp_gallery->getCurrentTheme() . '_' . stripSuffix($_zp_gallery_page), 1, false);
require_once(SERVERPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/colorbox_js.php');
if (!zp_has_filter('theme_head', 'colorbox::css')) {
zp_register_filter('theme_head', 'colorbox::css');
}
}
/**
* Plugin option handling class
*
*/
class user_logout_options {
function user_logout_options() {
setOptionDefault('user_logout_login_form', 0);
}
function getOptionsSupported() {
return array(gettext('Login form') => array('key' => 'user_logout_login_form', 'type' => OPTION_TYPE_RADIO,
'buttons' => array(gettext('None') => 0, gettext('Form') => 1, gettext('Colorbox') => 2),
'desc' => gettext('If the user is not logged-in display an <em>in-line</em> logon form or a link to a modal <em>Colorbox</em> form.'))
);
}
function handleOption($option, $currentValue) {
}
}
if (in_context(ZP_INDEX)) {
if (isset($_GET['userlog'])) { // process the logout.
if ($_GET['userlog'] == 0) {
if (!$location = Zenphoto_Authority::handleLogout()) {
$__redirect = array();
if (in_context(ZP_ALBUM)) {
$__redirect['album'] = $_zp_current_album->name;
}
if (in_context(ZP_IMAGE)) {
$__redirect['image'] = $_zp_current_image->filename;
}
if (in_context('ZP_ZENPAGE_PAGE')) {
$__redirect['title'] = $_zp_current_zenpage_page->getTitlelink();
}
if (in_context('ZP_ZENPAGE_NEWS_ARTICLE')) {
$__redirect['title'] = $_zp_current_zenpage_news->getTitlelink();
}
if (in_context('ZP_ZENPAGE_NEWS_CATEGORY')) {
$__redirect['category'] = $_zp_current_category->getTitlelink();
}
if (isset($_GET['p'])) {
$__redirect['p'] = sanitize($_GET['p']);
}
if (isset($_GET['searchfields'])) {
$__redirect['searchfields'] = sanitize($_GET['searchfields']);
}
if (isset($_GET['words'])) {
$__redirect['words'] = sanitize($_GET['words']);
}
if (isset($_GET['date'])) {
$__redirect['date'] = sanitize($_GET['date']);
}
if (isset($_GET['title'])) {
$__redirect['title'] = sanitize($_GET['title']);
}
if (isset($_GET['page'])) {
$__redirect['page'] = sanitize($_GET['page']);
}
$params = '';
if (!empty($__redirect)) {
foreach ($__redirect as $param => $value) {
$params .= '&' . $param . '=' . $value;
}
}
$location = FULLWEBPATH . '/index.php?fromlogout' . $params;
}
header("Location: " . $location);
exitZP();
}
}
}
/**
* Prints the logout link if the user is logged in.
* This is for album passwords only, not admin users;
*
* @param string $before before text
* @param string $after after text
* @param int $showLoginForm to display a login form
* to not display a login form set to 0
* to display a login form set to 1
* to display a login form in colorbox, set to 2, but you must have colorbox enabled for the theme pages where this link appears.)
* @param string $logouttext optional replacement text for "Logout"
*/
function printUserLogin_out($before = '', $after = '', $showLoginForm = NULL, $logouttext = NULL) {
global $__redirect, $_zp_current_admin_obj, $_zp_login_error, $_zp_gallery_page;
$excludedPages = array('password.php', 'register.php', 'favorites.php', '404.php');
$logintext = gettext('Login');
if (is_null($logouttext))
$logouttext = gettext("Logout");
$params = array("'userlog=0'");
if (!empty($__redirect)) {
foreach ($__redirect as $param => $value) {
$params[] .= "'" . $param . '=' . urlencode($value) . "'";
}
}
if (is_object($_zp_current_admin_obj)) {
if (!$_zp_current_admin_obj->logout_link) {
return;
}
} else {
if ($loginlink = zp_apply_filter('login_link', false)) {
if ($before) {
echo '<span class="beforetext">' . html_encodeTagged($before) . '</span>';
}
?>
<a href="<?php echo $loginlink; ?>" title="<?php echo $logintext; ?>"><?php echo $logintext; ?></a>
<?php
if ($after) {
echo '<span class="aftertext">' . html_encodeTagged($after) . '</span>';
}
return;
}
}
if (is_null($showLoginForm)) {
$showLoginForm = getOption('user_logout_login_form');
}
$cookies = Zenphoto_Authority::getAuthCookies();
if (empty($cookies) && !zp_loggedin()) {
if ($showLoginForm && !in_array($_zp_gallery_page, $excludedPages)) {
if ($showLoginForm > 1) {
if (zp_has_filter('theme_head', 'colorbox::css')) {
?>
<script type="text/javascript">
// <!-- <![CDATA[
$(document).ready(function() {
$(".logonlink").colorbox({
inline: true,
innerWidth: "400px",
href: "#passwordform",
close: '<?php echo gettext("close"); ?>',
open: $('#passwordform_enclosure .errorbox').length
});
});
// ]]> -->
</script>
<?php
}
if ($before) {
echo '<span class="beforetext">' . html_encodeTagged($before) . '</span>';
}
?>
<a href="#" class="logonlink" title="<?php echo $logintext; ?>"><?php echo $logintext; ?></a>
<span id="passwordform_enclosure" style="display:none">
<?php
}
?>
<div class="passwordform">
<?php printPasswordForm('', true, false); ?>
</div>
<?php
if ($showLoginForm > 1) {
?>
</span>
<?php
if ($after) {
echo '<span class="aftertext">' . html_encodeTagged($after) . '</span>';
}
}
}
} else {
if ($before) {
echo '<span class="beforetext">' . html_encodeTagged($before) . '</span>';
}
$logoutlink = "javascript:launchScript('" . FULLWEBPATH . "/',[" . implode(',', $params) . "]);";
?>
<a href="<?php echo $logoutlink; ?>"
title="<?php echo $logouttext; ?>"><?php echo $logouttext; ?></a>
<?php
if ($after) {
echo '<span class="aftertext">' . html_encodeTagged($after) . '</span>';
}
}
}
?><file_sep><?php
$pageTitle = "Explore";
$county = isset($_GET['county']) ? $_GET['county'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<!-- ********* ****************** *********** -->
<!-- ********* Explore Broward County ********** -->
<!-- ********* ****************** *********** -->
<?php if($county == 'broward'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Broward<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center"><img src="images/broward.jpg" alt="" class="img-responsive"></div>
</div>
</div>
<div class="col-md-6">
<h2>County Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.broward.org/history/">Broward County Historic Preservation Office</a></li>
</ul>
</div>
<h2>Historical Societies</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.oldfortlauderdale.org/">Fort Lauderdale</a></li>
<li><a target="_blank" href="http://www.hillsborolighthouse.org/">Hillsboro Lighthouse</a></li>
<li><a target="_blank" href="http://www.hollywoodhistoricalsociety.org/">Hollywood</a></li>
<li><a target="_blank" href="http://www.parklandhistoricalsociety.com/">Parkland</a></li>
<li><a target="_blank" href="http://www.plantation.org/museum/">Plantation</a></li>
<li><a target="_blank" href="http://www.pompanohistory.com/phc/">Pompano Beach</a></li>
</ul>
</div>
<h2>Shipwrecks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://dhr.dos.state.fl.us/archaeology/underwater/preserves/">SS Copenhagen Shipwreck</a></li>
</ul>
<p>This ship was a steam ship launched in 1898. It was transporting coal at the time it sank in 1900. The Captain was found to be at fault for the sinking because of improper navigation. The shipwreck now lies between 15 and 30 feet of water. See also the <a target="_blank" href="http://www.museumsinthesea.com/copenhagen/index.htm">Museums in the Sea website</a>.</p>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://pompanotoday.com/tag/indian-mound-park/">Indian Mound Park </a></li>
</ul>
<p>Located within this small park overlooking the Intracoastal waterway is a prehistoric Native American burial mound. The mound has a well-marked trail with informative signage relating to the Native American occupation of the site.</p>
<ul>
<li><a target="_blank" href="http://www.broward.org/PARKS/LONGKEYNATURALAREA/Pages/Default.aspx">Long Key Nature Center </a></li>
</ul>
<p>Long Key is the largest of the 'islands' known as <NAME>' Seven Islands. The park consists of 157 acres of oak hammocks and restored wetlands that was, as recently as 100 years ago, part of the Everglades. Records of human settlement on Long Key date back to at least 1000BC with the Tequesta Indians.</p>
<ul>
<li><a target="_blank" href="http://www.broward.org/PARKS/SNAKEWARRIORSISLAND/Pages/Default.aspx">Snake Warrior Island</a></li>
</ul>
<p>Snake Warrior Island historically was a tree island in the Eastern Everglades, and is now a 53 acre park. This park was home to Seminole tribal members as early as 1828. Interpretative signage for the historic use of this land circles a recreated marsh area.</p>
</div>
<h2>Other Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.semtribe.com/TourismAndEnterprises/Hollywood/Okalee.aspx">Seminole Okalee Indian Village </a></li>
</ul>
<p>
The Seminole Okalee Indian Village highlights culture and history of the Seminole People. The facility introduces visitors to the Tribal ways of life through live arts and crafts demonstrations in our authentic Seminole Village.
</p>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Miami-Dade County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'miamidade'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Miami-Dade<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center"><img src="images/miami-dade.jpg" alt="" class="img-responsive"></div>
</div>
</div>
<div class="col-md-6">
<h2>County Offices & Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.historicpreservationmiami.com/">Miami-Dade County Historic Preservation Office</a></li>
<li><a target="_blank" href="http://assf.tripod.com/">Archaeological Society of So. Florida</a></li>
</ul>
</div>
<h2>Universities</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.fiu.edu/orgs/socant/index.html">Florida International University Department of Anthropology</a></li>
<li><a target="_blank" href="http://www.as.miami.edu/anthropology/">University of Miami Department of Anthropology</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.historymiami.org/">Historical Museum Of Southern Florida</a></li>
</ul>
<p>The Historical Museum of Southern Florida has numerous permanent exhibitions including “Tropical Dreams: A People’s History of South Florida.” This exhibit explores South Florida history through five periods: First Arrivals, International Rivalry, Southward, Expansion, New People - New Technology and Gateway of the Americas. The “First Arrivals” exhibit includes an extensive interpretation of the Miami Circle excavations.</p>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Parks & Historic Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.miamidade.gov/parks/Parks/arch_creek.asp">Arch Creek Historic & Archaeological Park</a></li>
</ul>
<p>Arch Creek park was created around a natural limestone bridge formation that was once part of an important trail first used by the Tequesta around 2,000 years ago and later by the Seminoles in the 19th century. Middens dating to the Tequesta period and a 19th century coontie mill are also present in the park.</p>
<ul>
<li><a target="_blank" href="http://www.deeringestate.com/">Deering Estate At Cutler</a></li>
</ul>
<p>Located along the edge of Biscayne Bay, the 444-acre Deering Estate at Cutler is an environmental, archeological and historical preserve. The Estate offers daily tours of the historic houses – the Stone House and Richmond Cottage, as well as tours of the lush natural areas where fossil bones have been found as far back at 50,000 years.</p>
</div>
<h2>Shipwrecks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://dhr.dos.state.fl.us/archaeology/underwater/preserves/">Half Moon Shipwreck</a></li>
</ul>
<p>This ship was a two-masted racing sailboat that was built as a wedding present from a German socialite for her husband. This particular ship had many lives, many uses, and many owners. There was no cargo when the ship sunk as the ship was being used as a fishing barge and residence for the captain and his family. The shipwreck now lies between 8 to 10 feet of water. See also the <a target="_blank" href="http://www.museumsinthesea.com/halfmoon/index.htm">Museums in the Sea website</a>.</p>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Monroe County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'monroe'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Monroe<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center"><img src="images/monroe.jpg" alt="" class="img-responsive"></div>
</div>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.monroecounty-fl.gov/index.aspx?nid=317">Monroe County Historic Preservation Office</a></li>
<li><a target="_blank" href="http://www.historicfloridakeys.org/historicfloridakeys/Mission_&_History.html">Historic Florida Keys Foundation</a></li>
</ul>
</div>
<h2>Shipwrecks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://dhr.dos.state.fl.us/archaeology/underwater/preserves/"><NAME> Shipwreck</a></li>
</ul>
<p>This ship was part of the 1733 Spanish Galleon Fleet and was one merchant vessel among a fleet of 4 armed galleons and 17 other merchant vessels. The San Pedro was re-discovered in the 1960’s. See also the <a target="_blank" href="http://www.museumsinthesea.com/sanpedro/index.htm">Museums in the Sea</a> and <a target="_blank" href="http://dhr.dos.state.fl.us/archaeology/underwater/preserves/">Division of Historical Resources</a> websites on the San Pedro wreck.</p>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Parks and Historic Locations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/indiankey/default.cfm">Indian Key Historic State Park</a></li>
</ul>
<p>In 1840 Chakaika, leader of the “Spanish Indians,” led a raid on the settlement at Indian Key. Oral traditions of the Miccosukee Tribe of Indians of Florida assert that some members of their tribe are descendants of Chakaika’s group.</p>
<ul>
<li><a target="_blank" href="http://www.cranepoint.net/">Crane Point Museum, Nature Center and Historic Site</a></li>
</ul>
<p>Crane Point harbors evidence of human use dating back well over 700 years, to prehistoric Native American occupations. The first documented permanent settlers to this particular property were George and <NAME>, who lived here from 1902 until 1949.</p>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Palm Beach County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'palmbeach'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Palm Beach<small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<div class="text-center"><img src="images/palmbeach.jpg" alt="" class="img-responsive"></div>
</div>
</div>
<div class="col-md-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.pbcgov.com/publicsafety/emergencymanagement/resources/historical/">Palm Beach County Historic Review Board</a></li>
<li><a target="_blank" href="http://www.bocahistory.org/">Boca Raton Historical Society & Museum</a></li>
<li><a target="_blank" href="http://www.historicalsocietypbc.org/">Historical Society of Palm Beach County</a></li>
</ul>
</div>
<h2>Universities</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://wise.fau.edu/anthro/">Florida Atlantic University Department of Anthropology</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Parks & Preserves</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.lrhs.org/">Jupiter Inlet Historic & Archaeological Site & Dubois Park</a></li>
</ul>
<p>Dubois Park contains the remains of a village and shell midden occupied by the Jobe and their predecessors from 1,000 years ago. <NAME>, a Quaker merchant whose family and crew were shipwrecked in 1696, is through to have been held captive at this site. </p>
<ul>
<li><a target="_blank" href="http://www.pbcgov.com/parks/locations/riverbend.htm">Riverbend Park </a></li>
</ul>
<p>Riverbend park is the site of the Seminole War, Battle of the Loxahatchee, which took place on Jan. 24, 1838. Although interpretive signage has not yet been developed there interpretation of the site is available in “Guns Across the Loxahatchee” by <NAME>.</p>
<ul>
<li><a target="_blank" href="http://dhr.dos.state.fl.us/archaeology/underwater/preserves/">Lofthus Underwater Archaeological Preserve Manalapan</a> </li>
</ul>
<p>This ship, originally named the Cashmere, was a merchant vessel with false gun ports painted along her sides to deter Sumatran and Javanese pirates. The shipwreck now lies between 15 and 20 feet of water. See also the <a target="_blank" href="http://www.museumsinthesea.com/lofthus/index.htm">Museums in the Sea website</a>.</p>
</div>
</div><!-- /.col -->
<?php }else{ ?>
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-12 col-md-8 col-md-push-2">
<p>
The Southeast region offers many amazing historical and archaeological sites that you can visit. Click on any county below to discover sites in your area.
<hr/>
<!-- Interactive SVG Map -->
<div id="semap" class="center-block"></div>
</p>
<!-- <hr/>
<div class="col-sm-12 text-center">
<div class="image"><img src="" alt="" class="img-responsive" width="400" height="464"></div>
</div> -->
</div>
</div><!-- /.row -->
<?php } ?>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#semap').mapSvg({
source: 'images/se_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //North Central Region Marker
xy:[200,365],
tooltip:'Northeast Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Palm_Beach' :{popover:'<h3>Palm Beach</h3><p class="text-center"><a class="btn btn-primary" target="_blank" href="/serc/explore.php?county=palmbeach"> Explore Palm Beach County</a></p>'},
'Broward' :{popover:'<h3>Broward</h3><p class="text-center"><a class="btn btn-primary" target="_blank" href="/serc/explore.php?county=broward"> Explore Broward County</a></p>'},
'Miami-Dade' :{popover:'<h3>Miami-Dade</h3><p class="text-center"><a class="btn btn-primary" target="_blank" href="/serc/explore.php?county=miamidade"> Explore Miami-Dade County</a></p>'},
'Monroe' :{popover:'<h3>Monroe</h3><p class="text-center"><a class="btn btn-primary" target="_blank" href="/serc/explore.php?county=monroe"> Explore Monroe County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-dash">
</div>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Site Protection";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-dash">
<div class="text-center">
<div class="image text-center">
<img src="images/site_protection.jpg" class="img-responsive" width="500" />
<p>Commandant's house, Pensacola. <br/> Photo courtesy of State Archives of Florida, <em><a href="http://floridamemory.com" target="_blank">Florida Memory</a></em></p>
</div>
</div>
<p>Florida’s archaeology sites are a precious, nonrenewable resource. Here are some ways that citizens can help protect and preserve archaeology sites.</p>
<strong>Florida Master Site File</strong>
<p>Adding sites to the Florida Master Site File protects sites in two ways: it documents what is currently known about them, which can be helpful to archaeologists studying other sites nearby. Second, it creates a permanent record of the site that is provided when construction is set to take place in the area. If you believe you have a site on your property, please <a href="mailto:<EMAIL>">contact us</a>, and we will put you in touch with someone who can help assess and document the resource.</p>
<strong>Archaeological Ordinances:</strong>
<p>Sites can also be protected through local legislation. Though state and federal laws protect much public land, local governments can get involved to preserve local archaeological resources. <a href="../documents/BlankOrdinance.pdf">Here is a sample ordinance</a>.</p>
</div>
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Site Protection";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-dash">
<div class="text-center">
<div class="image text-center">
<img src="images/siteprotection.jpg" class="img-responsive" width="500" />
<p>Yulee Sugar Mill Ruins Historic State Park<br/> Photo courtesy of State Archives of Florida, <em><a href="http://floridamemory.com" target="_blank">Florida Memory</a></em></p>
</div>
</div>
<p>Florida’s archaeology sites are a precious, nonrenewable resource. Here are some ways that citizens can help protect and preserve archaeology sites.</p>
<h3>For the General Public</h3>
<p>There are three mechanisms to protect archaeological and historic sites. They occur at the local, state, and national levels. For information on each of these check out the links below. If you have questions please feel free to <a href="<EMAIL>">contact us.</a></p>
<strong>Florida Master Site File</strong>
<p>The <a href="http://www.flheritage.com/preservation/sitefile/" target="_blank">Florida Master Site File</a> is the State of Florida's official inventory of historical and cultural resources. Categories of resources recorded at the Site File include: archaeological sites, historical structures, historical cemeteries, historical bridges, historic districts. If you believe you have a site on your property, please <a href="mailt:<EMAIL>">contact us</a>, and we will help you fill out a site file form and submit it.</p>
<strong>Local Landmark Designation</strong>
<p>The strongest tools for preservation can be found at the local level. Cities and counties that participate in the Certified Local Government (CLG) program provide their citizens with ways to protect sites and historic structures at the local level. Check the list below, or check out the <a href="http://www.flheritage.com/preservation/clg/" target="_blank">Divison of Historical Resources page on CLGs</a>, to see if your community is a CLG and learn more about how you can participate in the local landmark designation process.</p>
<ul>
<li><a href="http://www.eustis.org/home/history.html">City of Eustis</a> - <a href="https://library.municode.com/HTML/13820/level2/SPAGEOR_CH46HIPR.html#TOPTITLE">Ordinance</a> </li>
<li><a href="http://www.cityofgainesville.org/PlanningDepartment/HistoricDistricts.aspx">City of Gainesville</a> - <a href="https://www.municode.com/library/fl/gainesville/codes/code_of_ordinances?nodeId=PTIICOOR_CH30LADECO_ARTVIRESPREUS_S30-112HIPRCO">Ordinance</a> </li>
<li><a href="https://www.leesburgflorida.gov/index.aspx?page=1228">City of Leesburg</a> - <a href="https://library.municode.com/HTML/10282/level2/PTIICOOR_CH30HIPR.html#TOPTITLE">Ordinance</a> </li>
<li><a href="http://www.micanopytown.com/CitizenBoards.html">Town of Micanopy</a> - <a href="http://www.micanopytown.com/files/Micanopy_Land_Development_Code_2013.pdf">Ordinance</a> </li>
<li><a href="http://ci.mount-dora.fl.us/index.aspx?NID=282">City of Mount Dora</a> - <a href="https://library.municode.com/HTML/10708/level3/SUHITA_LADECO_CHIIIZORE.html#SUHITA_LADECO_CHIIIZORE_3.6HIPR">Ordinance</a></li>
<li><a href="http://www.ci.newberry.fl.us/#!history/c1lb8">City of Newberry</a> - <a href="https://library.municode.com/HTML/13872/level3/PTIICOOR_APXBLADERE_ART11HISISTPRRE.html#TOPTITLE">Ordinance</a></li>
<li><a href="http://www.ocalafl.org/gm/GM3.aspx?id=2430">City of Ocala</a> - <a href="http://www.ocalafl.org/uploadedFiles/Development_Services/Growth_Management_Redesign/Historic Preservation Ordinance(2).pdf">Ordinance</a> </li>
</ul>
<strong>National Register of Historic Places</strong>
<p>Listing in the <a target="_blank" href="http://www.nps.gov/nr/">National Register of Historic Places</a> provides formal recognition of a property’s historical, architectural, or archeological significance based on national standards used by every state. If you have questions about a site’s eligibility, or would like more information on the nomination process <a href="mailto:<EMAIL>">contact us</a>.</p>
<h3>For Local and State Land Managers</h3>
<p>FPAN provides training on how to effectively manage archaeological and historical sites. Check the <a href="../workshops.php">Trainings and Workshops</a> page for more information or <a href="mailto:<EMAIL>">contact us</a> to set one up in your area.</p>
</div>
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
include 'header.php';
//Define table name for this form
$table = 'PressContact';
//if this is a new event, clear any potential leftover form data
if($_GET['new'])
$_SESSION['formVars'] = "";
//If event ID is supplied in URL, this event is being edited. Gather info from database and populate form.
if($_GET['id']){
setupEdit($_GET['id'], $table);
}
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true)
confirmSubmit($table);
//Form has been submitted but not confirmed. Display input values to check for accuracy
if(isset($_POST['submit'])&&!isset($_POST['confirmSubmission'])){
firstSubmit($_POST);
}elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="pressContact" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Press Contact</h2>
<p>Please fill out the information below to log this activity.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text"> /
<label for="element_1_1">MM</label>
</span>
<span>
<input id="element_1_2" name="day" class="element text" size="2" maxlength="2" value="<?php echo $formVars['day']; ?>" type="text"> /
<label for="element_1_2">DD</label>
</span>
<span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text">
<a class="red"> *</a>
<label for="element_1_3">YYYY</label>
</span>
<span id="calendar_1">
<img id="cal_img_1" class="datepicker" src="images/calendar.gif" alt="Pick a date.">
</span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</li>
<li id="li_3" >
<label class="description" for="element_3">Type of Media </label>
<div>
<select class="element select medium" id="element_3" name="typeMedia" required="required">
<option value="" selected="selected"></option>
<option value="Television" <?php if($formVars['typeMedia'] == "Television") echo 'selected="selected"';?> >Television</option>
<option value="Radio" <?php if($formVars['typeMedia'] == "Radio") echo 'selected="selected"';?>>Radio</option>
<option value="Magazine" <?php if($formVars['typeMedia'] == "Magazine") echo 'selected="selected"';?>>Magazine</option>
<option value="Newspaper" <?php if($formVars['typeMedia'] == "Newspaper") echo 'selected="selected"';?>>Newspaper</option>
<option value="Web" <?php if($formVars['typeMedia'] == "Web") echo 'selected="selected"';?>>Web</option>
<option value="Multiple Media Types" <?php if($formVars['typeMedia'] == "Multiple Media Types") echo 'selected="selected"';?>>Multiple Media Types</option>
<option value="Other"<?php if($formVars['typeMedia'] == "Other") echo 'selected="selected"';?> >Other</option>
</select>
<a class="red">*</a></div>
<p class="guidelines" id="guide_3"><small>Choose the most appropriate media type. If this contact involves more than one media type, please select "Multiple Media Types".</small></p>
</li>
<li id="li_4" >
<label class="description" for="element_4">Type of Contact </label>
<div>
<select class="element select medium" id="element_4" name="typeContact" required="required">
<option value="" selected="selected"></option>
<option value="Press Release" <?php if($formVars['typeContact'] == "Press Release") echo 'selected="selected"';?>>Press Release</option>
<option value="Interview" <?php if($formVars['typeContact'] == "Interview") echo 'selected="selected"';?> >Interview</option>
<option value="Announcement" <?php if($formVars['typeContact'] == "Announcement") echo 'selected="selected"';?> >Announcement</option>
<option value="Other" <?php if($formVars['typeContact'] == "Other") echo 'selected="selected"';?> >Other</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_5" >
<?php include("staffInvolved.php"); ?>
</li>
<li id="li_2" >
<label class="description" for="element_2">Comments </label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium"><?php echo $formVars['comments']; ?></textarea>
</div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close else ?>
<div id="footer"> </div>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "Explore";
$county = isset($_GET['county']) ? $_GET['county'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<!-- ********* ****************** ************** -->
<!-- ********* Explore Brevard County ********** -->
<!-- ********* ****************** ************** -->
<?php if($county == 'brevard'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Brevard <small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Brevard is located along central Florida’s Atlantic coast and is the host county for the East Central Region of the Florida Public Archaeology Network. This county not only houses NASA’s Kennedy Space Center, the Florida Historical Society, and beautiful beaches but is also the home of the Windover Pond Archaeological Site, a 7,000 year old mortuary pond in Titusville.</p>
</div>
</div>
<div class="col-md-8 col-md-push-2">
<h2>Sites of Interest</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://breavardmusuem.com/">Brevard Museum of History and Natural Science</a></li>
<li><a target="_blank" href="http://www.brevardcounty.us/EELProgram/Areas/SamsHouseSanctuary/Home">Sam’s House at Pine Island Conservation Area</a></li>
<li><a target="_blank" href="http://myfloridahistory.org/">Florida Historical Society</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Indian River County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'indianriver'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Indian River <small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Indian River County was created in 1925. It was named for the Indian River Lagoon, which runs through the eastern portion of the county. Previously this area was considered part of St. Lucie County. Prior to 1820 this area was known as the Territory of East Florida. It is home to numerous nature and wildlife organizations that celebrate and protect the county’s beautiful coastlines.</p>
</div>
</div>
<div class="col-md-8 col-md-push-2">
<h2>Sites of Interest</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.irchistorical.org/">Indian River Citrus Museum</a></li>
<li><a target="_blank" href="http://www.discoverelc.org/">Environmental Learning Center</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** **************** -->
<!-- ********* Explore Martin County ************* -->
<!-- ********* ****************** **************** -->
<?php }elseif($county == 'martin'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Martin <small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Martin County was named for <NAME>, governor of Florida from 1925 to 1929. It offers something for everyone: beachside and coastal towns where outdoor activities and nature take center stage; historic towns with tree-lined streets; ‘Old Florida’ towns where rodeos and orange groves, as well as cowboys still exist; and an old fishing village where fisherman still bring their catch to market each day.</p>
</div>
</div>
<div class="col-md-8 col-md-push-2">
<h2>Sites of Interest</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.elliottmuseumfl.org/">Elliot Museum</a></li>
<li><a target="_blank" href="http://www.houseofrefugefl.org/">House of Refuge</a></li>
<li><a target="_blank" href="http://www.floridaocean.org/">Florida Oceanographic Coastal Center</a></li>
<li><a target="_blank" href="http://www.martin.fl.us/portal/page?_pageid=354,4190167&_dad=portal&_schema=PORTAL">Indian Riverside Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/jonathandickinson/default.cfm">Jonathan Dickinson State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore Okeechobee County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'okeechobee'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Okeechobee <small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Okeechobee County was created in 1917. It was named for the lake Okeechobee, which was itself named for Hitchiti words oka (water) and chobi (big). Generations continue to carry on the heritage of their families through the dairy, beef, citrus and fishing industry.</p>
<p>Okeechobee Historical Society Museum & Schoolhouse: For more information, please call (863) 763-4344</p>
</div>
</div>
<div class="col-md-8 col-md-push-2">
<h2>Sites of Interest</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.okeechobeebattlefield.com/">Okeechobee Battlefield Historic State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** **************** -->
<!-- ********* Explore Orange County ************* -->
<!-- ********* ****************** **************** -->
<?php }elseif($county == 'orange'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Orange <small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Originally called Mosquito County in 1824, Orange County is home to the city of Orlando. Renamed Orange County after the citrus industry boomed in 1845 this county has experienced consistent change. With important historic sites such as Ft. Christmas and numerous early Florida settlements from the late 19th century, this county is seeing more attention from local archaeologists. Orange County also hosts the University of Central Florida.</p>
</div>
</div>
<div class="col-md-8 col-md-push-2">
<h2>Sites of Interest</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.oaktownusa.com/Pages/Preserve/index">Oakland Nature Preserve</a></li>
<li><a target="_blank" href="http://www.thehistorycenter.org/">Orange County Regional History Museum</a></li>
<li><a target="_blank" href="http://www.orangecountyfl.net/CultureParks/Parks.aspx?m=dtlvw&d=15#.U0619sdR2TQ">Fort Christmas Historical Park</a></li>
<li><a target="_blank" href="http://www.winterparkhistory.org/">Winter Park History Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** ***************** -->
<!-- ********* Explore Osceola County ************* -->
<!-- ********* ****************** ***************** -->
<?php }elseif($county == 'osceola'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Osceola <small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Named after the Second Seminole War leader, Osceola became Florida’s 40th county in 1887. Osceola County became a center of trade and commerce from railroads and riverboats. The lumber industry also played a big role in the history of the county. Previously home to Florida crackers and cowmen, the area has most recently experienced growth from its proximity to Walt Disney World. Osceola County has a long archaeological history that is still being investigated. </p>
</div>
</div>
<div class="col-md-8 col-md-push-2">
<h2>Sites of Interest</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="Osceola County Welcome Center and History Museum">Osceola County Welcome Center and History Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** ****************** -->
<!-- ********* Explore Seminole County ************* -->
<!-- ********* ****************** ****************** -->
<?php }elseif($county == 'seminole'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> Seminole <small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>Seminole County is the Northern county of FPAN’s East Central Region and boasts the motto, “Florida’s natural choice”. Along with much of Central Florida, Seminole County also has a strong past of Florida cracker culture. Seminole County is the home to many archaeological sites such as Fort Lane, a Second Seminole Indian War fort built in 1837. The fort is named after <NAME> who in 1836 served as a Lieutenant Colonel in command of the Creek Indian Regiment. Soon after, Lane went insane and committed suicide by plunging his sword into his head. Seminole County also hosts several beautiful nature parks like the Lower Wekiva River Preserve State Park and Lake Jessup Conservation Area.</p>
</div>
</div>
<div class="col-md-8 col-md-push-2">
<h2>Sites of Interest</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.seminolecountyfl.gov/parksrec/museum/index.aspx">Museum of Seminole County History</a></li>
<li><a target="_blank" href="http://www.publichistorycenter.cah.ucf.edu/">Public History Center</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/wekiwasprings/">Wekiwa Springs State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ****************** *************** -->
<!-- ********* Explore St. Lucie County ************* -->
<!-- ********* ****************** *************** -->
<?php }elseif($county == 'stlucie'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> St. Lucie <small> County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
<p>The current St. Lucie County was created in 1905 from the southern part of Brevard County. St. Lucie County is now a certified "Green County," joining the ranks of only five other Florida counties to receive this prestigious recognition. It is home to the Oxbow Eco Center and the St. Lucie County Marine Center, which houses the Smithsonian Marine Station.</p>
</div>
</div>
<div class="col-md-8 col-md-push-2">
<h2>Sites of Interest</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="St. Lucie County Regional History Center">St. Lucie County Regional History Center</a></li>
<li><a target="_blank" href="http://www.stlucieco.gov/zora/">Zora Neal Hurtson Dust Tracks Heritage Trail</a></li>
</ul>
</div>
</div><!-- /.col -->
<?php }else{ ?>
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-12 col-md-8 col-md-push-2">
<p>
The East Central region offers many amazing historical and archaeological sites that you can visit. Click on any county below to discover sites in your area.
<hr/>
<!-- Interactive SVG Map -->
<div id="ecmap" class="center-block"></div>
</p>
<!-- <hr/>
<div class="col-sm-12 text-center">
<div class="image"><img src="" alt="" class="img-responsive" width="400" height="464"></div>
</div> -->
</div>
</div><!-- /.row -->
<?php } ?>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#ecmap').mapSvg({
source: 'images/ec_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //North Central Region Marker
xy:[200,365],
tooltip:'Northeast Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Seminole' :{popover:'<h3>Seminole</h3><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=seminole"> Explore Seminole County</a></p>'},
'Brevard' :{popover:'<h3>Brevard</h3><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=brevard"> Explore Brevard County</a></p>'},
'Indian_River' :{popover:'<h3>Indian River</h3><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=indianriver"> Explore Indian River County</a></p>'},
'St._Lucie' :{popover:'<h3>St. Lucie</h3><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=stlucie"> Explore St. Lucie County</a></p>'},
'Martin' :{popover:'<h3>Martin</h3><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=martin"> Explore Martin County</a></p>'},
'Okechobee' :{popover:'<h3>Okeechobee</h3><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=okeechobee"> Explore Okeechobee County</a></p>'},
'Orange' :{popover:'<h3>Orange</h3><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=orange"> Explore Orange County</a></p>'},
'Osceola' :{popover:'<h3>Osceola</h3><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=osceola"> Explore Osceola County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Home";
include 'dbConnect.php';
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<td class="lg_mid" style="vertical-align:top">
<h3> Sponsors</h3>
<ul>
<li><a href="http://www.fasweb.org/" target="_blank">Florida Anthropological Society</a></li>
<li><a href="http://www.flheritage.com/" target="_blank">Division of Historical Resources</a></li>
<li><a href="http://www.dos.state.fl.us/" target="_blank">Florida Department of State</a></li>
<li><a href="http://www.flarchcouncil.org/" target="_blank">Florida Archaeological Council</a></li>
<li><a href="http://www.flpublicarchaeology.org/" target="_blank">Florida Public Archaeology Network</a></li>
<li><a href="http://www.floridastateparks.org/" target="_blank">Florida State Parks</a></li>
<li><a href="http://www.flmnh.ufl.edu/" target="_blank">The Florida Museum of Natural History</a></li>
<li><a href="http://uwf.edu/archaeology/" target="_blank">University of West Florida</a></li>
</ul>
<a name="chapters" />
<h3>Organized by local chapters of the Florida Anthropological Society</h3>
<ul>
<li><strong>Archaeological Society of Southern Florida</strong><br />
2495 N.W. 35th Ave., Miami, FL 33142<br />
<a href="http://assf.tripod.com/" target="_blank">http://assf.tripod.com</a></li>
<li><strong>Central Florida Anthropological Society</strong><br />
P.O. Box 947544, Maitland, FL 32794-7544<br />
<a href="http://centralflanthropologicalsociety.com/" target="_blank">http://web.usf.edu/%7Efas/central/index.html</a></li>
<li><strong>Central Gulf Coast Archaeological Society</strong><br />
P.O. Box 9507, Treasure Island, FL 33740 <br />
<a href="http://www.cgcas.org/" target="_blank">http://www.cgcas.org</a></li>
<li><strong>Emerald Coast Archaeological Society</strong><br />
333 Persimmon St., Freeport, FL 32439<br />
<a href="http://www.gnt.net/~jrube/ECAS" target="_blank">http://www.gnt.net/%7Ejrube/ECAS</a></li>
<li><strong>Gold Coast Anthropological Society</strong><br />
P.O. Box 11052, Fort Lauderdale, FL 33339<br />
<a href="http://www.pbmnh.org/ResearchandCollections/GCAS.htm" target="_blank">http://www.pbmnh.org/ResearchandCollections/GCAS.htm</a></li>
<li><strong>Indian River Anthropological Society</strong><br />
3705 S. Tropical Trail, Merritt Island, FL 32952<br />
<a href="http://www.nbbd.com/npr/archaeology-iras/index.html" target="_blank">http://www.nbbd.com/npr/archaeology-iras/index.html</a></li>
<li><strong>Kissimmee Valley Archaeological and Historical Conservancy</strong><br />
195 Huntley Oaks Blvd., Lake Placid, FL 33852<br />
<a href="http://web.usf.edu/~fas/kvahc/index.html" target="_blank">http://web.usf.edu/%7Efas/kvahc/index.html</a></li>
<li><strong>Panhandle Archaeological Society at Tallahassee</strong><br />
P.O. Box 20026, Tallahassee, FL 32316<br />
<a href="http://past-tallahassee.org/" target="_blank">http://past-tallahassee.org</a></li>
<li><strong>Pensacola Archaeological Society</strong><br />
P.O. Box 13251, Pensacola, FL 32591<br />
<a href="http://uwf.edu/archaeology/archsoc" target="_blank">http://uwf.edu/archaeology/archsoc</a></li>
<li><strong>St. Augustine Archaeological Association</strong><br />
P.O. Box 1301, St. Augustine, FL 32085<br />
<a href="http://www.fasweb.org/chapters/staugustine.htm" target="_blank">http://www.fasweb.org/chapters/staugustine.htm</a></li>
<li><strong>Southeast Florida Archaeological Society</strong><br />
P.O Box 2875, Stuart, FL 34995<br />
<a href="http://www.sefas.org/" target="_blank">http://www.sefas.org</a></li>
<li><strong>Southwest Florida Archaeological Society</strong><br />
P.O. Box 9965, Naples, FL 34101<br />
<a href="http://www.fasweb.org/chapters/southwest.htm" target="_blank">http://www.fasweb.org/chapters/southwest.htm</a></li>
<li><strong>Time Sifters Archaeology Society</strong><br />
P.O. Box 25642, Sarasota, FL 34277-2883<br />
<a href="http://web.usf.edu/~fas/time/index.htm" target="_blank">http://web.usf.edu/%7Efas/time/index.htm</a></li>
<li><strong>Volusia Anthropological Society</strong><br />
P.O. Box 1881, Ormond Beach, FL 32175<br />
<a href="http://www.fasweb.org/chapters/volusia.htm" target="_blank">http://www.fasweb.org/chapters/volusia.htm</a></li>
<li><strong>Warm Mineral Springs Archaeological Society</strong><br />
P.O. Box 7797, North Port, FL 34287<br />
<a href="http://www.fasweb.org/chapters/warmmineralsprings.htm" target="_blank">http://www.fasweb.org/chapters/warmmineralsprings.htm</a></li>
</ul></td>
</tr>
</table>
<? include 'calendar.php'; ?>
<? include 'eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include 'footer.php'; ?><file_sep><label class="description" >Staff Involved <a class="red"> *</a></label>
<span>
<table style="width:620px;">
<tr><td style="vertical-align:text-top; padding:5px; width:150px;">
<br/>
<?php
$regions = array("nwrc", "ncrc", "nerc", "crc", "wcrc", "ecrc", "serc", "swrc");
$columnCount = 0;
$regionCount = 0;
foreach($regions as $region){
$regionCount++;
$sql = "SELECT * FROM Employees WHERE id IN (SELECT employeeID from EmployeeRegion WHERE region = '$region');";
$listEmployees = mysql_query($sql);
echo "<strong>".strtoupper($region)."</strong>";
if(mysql_num_rows($listEmployees) != 0)
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName'] ." ". $employee['lastName'];
if(is_array($formVars['staffInvolved']))
$selected = in_array($employee['id'], $formVars['staffInvolved']);
else
$selected = false;
if(($employee['isActive']) || ($selected)){
?>
<input id="element_1_1"
name="staffInvolved[]"
class="element checkbox"
type="checkbox"
<?php if($selected==true) echo 'checked="checked"'; ?>
value="<?php echo $employee['id']; ?>" />
<label class="choice" for="element_1_1"><?php echo $employeeName; ?></label>
<?php } //end if
}//Close While loop
if($regionCount == 2){
$columnCount++;
$regionCount = 0;
if($columnCount < 4)
echo "</td><td style=\"vertical-align:text-top; padding:5px; width:150px;\">";
}
echo "<br/>";
}//close foreach
?>
</td></tr>
</table>
</span> <file_sep><?php
include 'header.php';
$table = 'ServiceToProfessionalSociety';
//if this is a new event, clear any potential leftover form data
if($_GET['new'])
$_SESSION['formVars'] = "";
//If event ID is supplied in URL, this event is being edited. Gather info from database and populate form.
if($_GET['id']){
setupServiceEdit($_GET['id'], $table);
}
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true){
confirmServiceSubmit($table);
}
//Form has been submitted but not confirmed. Display input values to check for accuracy
if(isset($_POST['submit'])&&!isset($_POST['confirmSubmission'])){
firstServiceSubmit($_POST);
}elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="serviceToProfessionalSociety" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Service to Professional Society</h2>
<p>Use this form to log service to a professional society for your <strong>self</strong> only.
<br/> This activity will be attributed to the individual currently logged in.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text" required="required">
/
<label for="element_1_1">MM</label>
</span><span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text" required="required"><a class="red"> *</a>
<label for="element_1_3">YYYY</label>
</span></li>
<li id="li_3" >
<label class="description" for="element_3">Type of Society </label>
<div>
<select class="element select small" id="element_3" name="typeSociety" required="required">
<option value="" selected="selected"></option>
<option value="local" <?php if($formVars['typeSociety'] == "local") echo 'selected="selected"'; ?> >local</option>
<option value="state" <?php if($formVars['typeSociety'] == "state") echo 'selected="selected"'; ?> >state</option>
<option value="regional" <?php if($formVars['typeSociety'] == "regional") echo 'selected="selected"'; ?> >regional</option>
<option value="national" <?php if($formVars['typeSociety'] == "national") echo 'selected="selected"'; ?> >national</option>
<option value="international" <?php if($formVars['typeSociety'] == "international") echo 'selected="selected"'; ?> >international</option>
</select><a class="red"> *</a>
</div>
</li>
<li id="li_2" >
<label class="description" for="element_2">Comments <a class="red"> *</a></label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium" onKeyDown="limitText(this.form.comments,this.form.countdown,2080);"
onKeyUp="limitText(this.form.comments,this.form.countdown,2080);" required="required"><?php echo $formVars['comments']; ?></textarea><br/>
<font size="1">(Maximum characters: 2080)<br>
You have <input readonly type="text" name="countdown" size="3" value="2080"> characters left.</font>
</div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close else ?>
<div id="footer"> </div>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "Home";
include 'header.php';
require_once("../rss/rsslib.php");
$url = "http://fpangoingpublic.blogspot.com/feeds/posts/default?alt=rss";
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Notice of Meetin</h1></th>
</tr>
<tr>
<td class="table_mid">
<p><strong>Florida Public Archaeology Network</strong></p>
<p><strong>Flagler College</strong></p>
<p>The Florida Public Archaeology Network announces a telephone conference call to which all persons are </p>
<p>invited.</p>
<p><strong>DATE AND TIME:</strong> April 8, 2014 10:00 A.M EST</p>
<p><strong>PLACE:</strong> Flagler College, 25 Markland Place, St. Augustine, FL 32085</p>
<p><strong>GENERAL SUBJECT MATTER TO BE CONSIDERED:</strong> To discuss potential projects to generate funds and </p>
<p>prepare for annual board meeting in May. A copy of the agenda may be obtained by contacting Sarah </p>
<p>Miller, Director for FPAN Northeast Region at email: <a href="mailto:<EMAIL>"><EMAIL></a> or phone: (904) 819-6476.</p>
<h4 align="center"> </h4>
<p> </p></td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include '../events/eventBox.php'; ?><br/>
<!-- Facebook Like Box -->
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th class="sm_header">
<h1>Facebook</h1></a>
</th>
</tr>
<tr>
<td class="table_mid">
<div class="fb-like-box" data-href="http://www.facebook.com/FPANNortheast" data-width="218" data-height="450" data-colorscheme="light" data-show-faces="true" data-header="false" data-stream="false" data-show-border="false"></div>
</td>
</tr>
<tr>
<td class="sm_bottom"></td>
</tr>
</table>
</div>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?>
<file_sep><?php
$pageTitle = "Event Advertising Statement & Criteria";
include('_header.php');
?>
<div class="page-content container connect">
<div class="page-header"><h1>Event <small>Advertising Statement & Criteria</small></h1></div>
<div class="row">
<div class="box-tab col-sm-8 col-sm-push-2">
<p>FPAN usually is pleased to help advertise and promote heritage events in Florida that are sponsored or hosted by other agencies and organizations, but they must meet the following*:</p>
<ul>
<li>Items for web-based calendar: click "Submit an Event" below and fill out the form at least 1 month in advance (the form will be reviewed by the FPAN Regional Director before posting on the calendar)</li> <li>Items for social media (Facebook, Twitter, etc): forward event fliers at least 2 weeks in advance to the nearest FPAN office</li>
<li>Items for mass email (where available): forward event fliers/info at least 6 weeks in advance with a 100-word description of event to the nearest FPAN office</li>
<li>Items for physical message board at FPAN office: forward any time to the nearest FPAN office</li>
</ul>
<p>*PLEASE NOTE: ALL NON-FPAN EVENTS SUBMITTED FOR PROMOTION MUST BE ARCHAEOLOGICALY ETHICAL AND RELEVANT TO FLORIDA HERITAGE, OPEN TO THE PUBLIC, AND ARE SUBJECT TO APPROVAL BY THE FPAN REGIONAL DIRECTOR AND/OR FPAN EXECUTIVE DIRECTOR. </p>
<p>FPAN follows the ethical principles and <a href="http://rpanet.org/displaycommon.cfm?an=1&subarticlenbr=3">code of conduct of the Register of Professional Archaeologists</a> (RPA).</p>
<p class="text-center">
<a href="https://casweb.wufoo.com/forms/fpan-event-form/" class="btn btn-primary">Submit an Event</a>
</p>
</div>
</div><!-- /.row -->
</div><!-- /.page-content -->
<?php include('_footer.php'); ?>
<file_sep><?php
include '../dbConnect.php';
$upcomingEvents = mysql_query("SELECT * FROM $table
WHERE eventDateTimeStart >= CURDATE()
ORDER BY eventDateTimeStart ASC;");
?>
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th class="sm_header"><a href="eventList.php" class="nav"><h1>Upcoming Events</h1></a> </th>
</tr>
<tr>
<td class="table_mid">
<?php
if(mysql_num_rows($upcomingEvents) != 0){
$numEvents = 5;
while(($event = mysql_fetch_array($upcomingEvents)) && ($numEvents > 0)){
$timestampStart = strtotime($event['eventDateTimeStart']);
$eventDate = date('M, j', $timestampStart);
$linkDate = date('m/d/Y', $timestampStart);
$eventTimeStart = date('g:i a', $timestampStart);
echo "<p class=\"small\"><strong style=\"font-size:12px;\">" . $eventDate . " @ " . "</strong>"
. $eventTimeStart;
if($event['eventTimeEnd'] != null){
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventTimeEnd = date('g:i a', $timestampEnd);
echo " - " . $eventTimeEnd;
}
echo "<br/>";
echo "<a href=\"eventDetail.php?eventID=$event[eventID]&eventDate=$linkDate\"><em>" . stripslashes($event['title']) . "</em></a></p>";
$numEvents--;
}
}
else
echo '<p style="font-size:12px;" align="center">No events currently scheduled. <br/> Check back soon!</p>';
?>
</td>
</tr>
<tr>
<td class="sm_bottom"></td>
</tr>
</table>
<file_sep><?php
$pageTitle = "Home";
$bg = array('jumbotron1.jpg','jumbotron2.jpg'); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
include('_header.php');
?>
<!-- page-content begins -->
<div class="page-content container">
<div class="row">
<div class="jumbotron-main col-md-10 col-md-push-1 col-sm-12 hidden-xs"
style="background: url(images/<?php echo $selectedBg; ?>) 0% no-repeat;">
</div>
</div>
<div class="row box-tab">
<div class="col-sm-7">
<h2>News & Press Releases</h2>
<strong>September 9, 2014</strong>
<p>The Florida Public Archaeology Network (FPAN) is opening a new temporary exhibit titled Lost Virtue: Pensacola’s Red Light District inside the Destination Archaeology Resource Center on September 19, 2014... (<a href="">read more</a>)</p>
<strong>August 18, 2014</strong>
<p>The Destination Archaeology Resource Center (DARC) and Ozone Pizza Pub are hosting Archaeology Café on Thursday, August 28 starting at 6 p.m. <NAME>, an archaeology graduate student at the University of West Florida, will present her research about the archaeology of Pensacola’s red light district... (<a href="">read more</a>)</p>
<strong>April 2, 2014</strong>
<p>The Florida Public Archaeology Network (FPAN) has opened a new museum exhibit titled Talking Smack: Northwest Florida’s Historical Red Snapper Industry inside the Destination Archaeology Resource Center... (<a href="">read more</a>)</p>
</div>
<div class="col-sm-5">
<div class="darc-events-box">
<h2>Upcoming Events<small>Northwest Region</small></h2>
<!-- Non-mobile list (larger) -->
<?php
$regionArray = array($table);
echoUpcomingEventsBox($regionArray,5);
?>
<p class="text-center">
<a class="btn btn-primary btn-sm" href="../nwrc/eventList.php">View more</a>
</p>
</div>
</div>
<div class="col-sm-10 col-sm-push-1">
<h2>About Us</h2>
<p>Located inside the <strong><a href="http://fpan.us">Florida Public Archaeology Network</a></strong> headquarters in downtown Pensacola, the <strong>Destination Archaeology Resource Center</strong> is an archaeology museum open to the public. Inside you will learn about the amazing archaeological sites that you can visit and experience throughout the state. Our exhibits include displays about both land and underwater archaeology sites. We showcase heritage sites open to the public within the eight regions of the FPAN with traditional and interactive displays, including touchscreens, tablet computers and artifacts. Additionally, our museum hosts a variety of free exhibits, events, and programs throughout the year.</p>
</div>
</div><!-- /.row -->
<div class="row">
<div class="col-md-4">
<div class="region-callout-box exhibits-callout">
<h1>Exhibits</h1>
<p>Discover current and previous exhibits.</p>
<a href="exhibits.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="region-callout-box programs-callout">
<h1>Programs</h1>
<p>See what kinds of programs we offer.</p>
<a href="programs.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="region-callout-box nw-explore">
<h1>Virtual Tours</h1>
<p>Take a virtual tour of different archaeological sites. </p>
<a href="tours-arcadia.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
</div><!-- /.row two -->
<div class="row">
<div class="ad-box">
<div class="col-sm-3">
<a href="http://unearthingflorida.org" target="_blank">
<img src="images/UnearthingFLoridaLogo.jpg" width="220" height="71" alt="Unearthing FL" class="ad img-responsive">
</a>
</div>
<div class="col-sm-3">
<a href="http://fpan.us/civilwar" target="_blank">
<img src="images/dcwButton.png" alt="Destination: Civil War" class="ad img-responsive">
</a>
</div>
<div class="col-sm-3">
<a href="http://www.nextexithistory.com" target="_blank">
<img src="images/NEH_logo.png" width="180" height="106" alt="Next Exit History" class="ad img-responsive">
</a>
</div>
<div class="col-sm-3">
<a href="http://www.tripadvisor.com/Attraction_Review-g34550-d4601694-Reviews-Destination_Archaeology_Resource_Center-Pensacola_Florida.html" target="_blank">
<img src="images/tripAdvisor.png" alt="" class="ad img-responsive">
</a>
</div>
</div><!--/.ad-box -->
</div><!-- /.row three -->
</div><!-- /.page-content /.container-fluid -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Programs";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Human Remains and the Law</h1></th>
</tr>
<tr>
<td><p>This half-day workshop focuses on Florida and US laws regulating the discovery of human remains and the management of Native American remains within museum collections. Geared toward land managers, this course provides guidance for dealing with inadvertent discoveries of human remains, discusses strategies for managing marked and unmarked cemeteries, presents a brief overview of the Native American Graves Protection and Repatriation Act (NAGPRA), and addresses issues of Native American remains within museum collections.</p><br />
<hr/>
<p>
<h4> <a href="http://www.flpublicarchaeology.org/programs/">< Go Back to Program List</a></h4>
</p>
</td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Florida Archaeology Month<?php if($pageTitle){echo " - ".$pageTitle;} ?></title>
<meta name="DESCRIPTION" content="">
<meta name="KEYWORDS" content="">
<link rel="stylesheet" type="text/css" href="http://flpublicarchaeology.org/FAM/style.css" media="all" />
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-7301672-15']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body id="radial-center">
<div id="main">
<div id="header">
<img src="http://flpublicarchaeology.org/FAM/images/header.jpg" alt="Florida Archaeology Month" />
</div>
<div id="navbar">
<p align="center"> <img src="http://flpublicarchaeology.org/FAM/images/line_left.png" />
<a href="#">About</a> <img src="http://flpublicarchaeology.org/FAM/images/seperator.png" />
<a href="#">Submit Event</a> <img src="http://flpublicarchaeology.org/FAM/images/seperator.png" />
<a href="#">Events</a> <img src="http://flpublicarchaeology.org/FAM/images/seperator.png" />
<a href="#">Links</a> <img src="http://flpublicarchaeology.org/FAM/images/seperator.png" />
<a href="#">Archives</a> <img src="http://flpublicarchaeology.org/FAM/images/line_right.png" />
</p>
</div>
<div class="clearFloat"></div>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<td class="lg_mid" style="vertical-align:top">
<h1 align="center"> Florida Archaeology Month 2012</h1>
<p><h2 align="center">Full Site Coming Soon!</h2></p>
<p align="center"><strong>Download the 2012 Archaeology Month Poster</strong><br />
<a href="posterArchives/2012-poster-front.jpg">2012 FAM Poster - Front</a><br/>
<a href="posterArchives/2012-poster-back.jpg">2012 FAM Poster - Back</a></p>
<p><strong>Florida Archaeology Month 2012</strong> explores how archaeology contributes to our understanding of the Civil War. Information about local events can be found on the Florida Anthropological Society (FAS) Website, and on local FAS chapter Websites that can be accessed from the main <a href="http://www.fasweb.org/index.html" target="_blank">FAS Webpage</a></p>
<p><strong>Florida Archaeology Month</strong> is coordinated by the Florida Anthropological Society, and supported by the Department of State, Division of Historical Resources. Additional sponsors for 2012 include the Florida Archaeological Council, Florida Public Archaeology Network, state and local museums, historical commissions, libraries, and public and private school systems. The 2012 poster and postcards are available through the local <a href="links.php#chapters">Florida Anthropological Society Chapters</a>.</p></td>
</tr>
</table>
<? include 'calendar.php'; ?>
<div class="clearFloat"></div>
</div>
<!-- Footer -->
<div id="footer">
</div>
<div class="clearFloat"></div>
</div><!-- End Main Div -->
</body>
</html>
<file_sep><?php
$pageTitle = "Home";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Southwest Region News</h1></th>
</tr>
<tr>
<td class="table_mid">
<?php include 'news/news.txt'?>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Welcome to the Southwest Region</h1></th>
</tr>
<tr>
<td class="table_mid">
<p align="center"><img src="http://flpublicarchaeology.org/swrc/images/southwestRegion.jpg" alt="Southwest Region" border="0" usemap="#map_sw" style="border: 0;" href="explore.php?county=charlotte" />
<map name="map_sw">
<area shape="poly" alt="Explore Brevard County"
coords="197,8,254,7,247,61,255,83,245,90,244,90,239,98,197,96,137,96,138,85,138,79,138,74,137,75,138,64,136,55,135,39,166,40,182,39,186,24,185,18"
href="explore.php?county=glades" />
<area shape="poly" coords="245,197,251,289,96,285,90,183,122,183,122,162,135,164,136,145,182,145,183,195" href="explore.php?county=collier" />
<area shape="poly" coords="22,43,134,43,135,94,55,94,23,95,2,63" href="explore.php?county=charlotte" />
<area shape="poly" coords="136,95,135,143,185,143,185,194,249,196,249,98" href="explore.php?county=hendry" />
<area shape="poly" coords="135,95,135,162,120,163,120,182,88,184,40,139,31,109,54,96" href="explore.php?county=lee" />
</map>
</p>
<p>
The Southwest Region serves Charlotte, Collier, Glades, Hendry and Lee counties.
</p>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include '../events/eventBox.php'; ?><br/>
<!-- Twitter Feed Box -->
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th class="sm_header">
<a href="http://twitter.com/FPANsouthwest" class="twitter">
<img src="http://flpublicarchaeology.org/images/twitter_bird.png" style="padding-left:25px; margin-right:-30px;" align="left"/>
<h1> Twitter Feed</h1></a>
</th>
</tr>
<tr>
<td class="table_mid">
<div align="center"><a href="http://twitter.com/FPANsouthwest">@FPANsouthwest</a></div>
<ul id="twitter_update_list"><li>Twitter feed loading...</li></ul>
</td>
</tr>
<tr>
<td class="sm_bottom"></td>
</tr>
</table>
</div>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?>
<file_sep><?php
include 'header.php' ;
$activityArray = array();
$db = new mysqli('fpanweb.powwebmysql.com', 'reports_user', ')OKM9ijn', 'fpan_dev_reports');
$regionActivityIDs = array('nwrc'=>'','ncrc'=>'','nerc'=>'','wcrc'=>'','crc'=>'','wcrc'=>'','ecrc'=>'','swrc'=>'','serc'=>'');
$sql = "SELECT activityID FROM EmployeeActivity WHERE employeeID IN
(SELECT employeeID FROM EmployeeRegion WHERE region = 'nwrc');";
$result = $db->query($sql) or die('There was an error running the query [' .$db->error. ']');
while($row = $result->fetch_assoc())
$regionActivityIDs['nwrc'][] = $row['activityID'];
$result->free();
$activityIDArray = join(',',$regionActivityIDs['nwrc']);
$sql.= "SELECT 'nwrc' AS 'Region',
SUM(numberAttendees) AS 'numberAttendees',
'PublicOutreach' AS 'eventType'
FROM `PublicOutreach`
WHERE id IN ($activityIDArray)
AND PublicOutreach.activityDate
BETWEEN '$startDate' AND '$endDate'
UNION ALL
SELECT 'nwrc' AS 'Region',
SUM(numberAttendees) AS 'numberAttendees',
'TrainingWorkshops' AS 'eventType'
FROM `TrainingWorkshops`
WHERE id IN ($activityIDArray)
AND TrainingWorkshops.activityDate
BETWEEN '$startDate' AND '$endDate'";
echo $sql;
?>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html>
<file_sep><?php
$pageTitle = "Home";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Welcome to the Northeast Region</h1></th>
</tr>
<tr>
<td class="table_mid">
<p align="center"><img src="images/NortheastRegion.jpg" alt="Northeast" border="0"
usemap="#map_ne" style="border: 0;" href="#" />
<map name="map_ne" id="map_ne">
<area shape="poly" coords="291,171,219,172,220,236,220,294,271,294,270,277,287,277,324,258" href="explore.php?county=highlands" />
<area shape="poly" coords="9,14,34,2,103,29,96,58,80,57,70,49,57,54,10,102" href="explore.php?county=nassau" />
<area shape="poly" coords="99,128,100,103,109,102,99,59,80,59,70,51,58,55,13,100,11,115,62,112,72,123" href="explore.php?county=duval" />
<area shape="circle" coords="-36,331,0" href="#" />
<area shape="poly" coords="13,118,12,196,29,188,35,180,48,175,77,173,76,157,74,143,67,133,65,123,66,118,60,115" href="explore.php?county=clay" />
<area shape="poly" coords="147,246,140,250,139,274,102,271,101,250,66,263,75,287,99,315,108,341,122,354,118,371,142,378,187,379,202,353" href="explore.php?county=volusia" />
<area shape="poly" coords="11,196,11,239,39,232,55,252,66,260,101,249,90,235,89,190,78,175,45,177" href="explore.php?county=putnam" />
<area shape="poly" coords="131,202,149,243,139,250,139,271,104,269,102,247,92,235,90,211" href="explore.php?county=flagler" />
<area shape="poly" coords="67,121,71,137,77,147,78,173,89,187,90,209,131,202,129,178,124,157,111,104,101,104,102,129,90,129" href="explore.php?county=stjohns" />
</map>
</p>
<p>The Northeast Region is located in St. Augustine, hosted by Flagler College and serves seven counties: Nassau, Duval, St. Johns, Flagler, Volusia, Clay, and Putnam. Click on the county to see some of the sites that are open and interpreted for the public. Check back as these pages are continually being updated. </p>
<p><strong>Download a copy of our two-sided Archaeology Map! </strong><br />
Side one features a walking tour of St. Augustine's most fascinating archaeology sites and exhibits. Side two marks some of the most exciting archaeological sites, museums, and displays that Northeast Florida has to offer.</p>
<p> <a href="documents/ArchyMap2010.pdf" target="_blank">Download it for free!</a></p></td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php include '../events/eventBox.php'; ?><br/>
<?php include '../events/calendar.php'; ?>
</div>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?>
<file_sep><?php
$pageTitle = "Home";
$bg = array('jumbotron2.jpg'); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
include('_header.php');
?>
<!-- page-content begins -->
<div class="page-content container">
<!-- Row One -->
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="col-sm-12">
<div class="jumbotron hidden-xs" style="background: url(images/<?php echo $selectedBg; ?>) 40% no-repeat; background-position:left;"> </div>
</div>
<div class="col-md-7">
<h2>Announcements</h2>
<div class="box-tab">
<p>No current announcements</p>
</div>
<div class="box-dash">
<p>The <span class="h4">Southwest</span> Region is hosted by <a href="http://wise.fau.edu/anthro/" target="_blank">Florida Atlantic University’s Department of Anthropology</a>. and serves Charlotte, Collier, Glades, Hendry and Lee counties. </p>
<!-- Interactive SVG Map -->
<div class="center-block hidden-xs" id="swmap"></div>
<img class="img-responsive visible-xs" src="images/sw_counties_map.svg" />
</div>
</div><!-- /.col -->
<div class="col-md-5">
<h2>Upcoming Events</h2>
<div class="box-tab events-box">
<!-- Non-mobile list (larger) -->
<div class="hidden-xs">
<?php
$regionArray = array($table);
echoUpcomingEventsBox($regionArray,5);
?>
</div>
<!-- Mobile events list -->
<div class="visible-xs">
<?php
$regionArray = array($table);
echoUpcomingEventsBox($regionArray,3);
?>
</div>
<p class="text-center">
<a class="btn btn-primary btn-sm" href="eventList.php">View more</a>
</p>
</div>
<!-- <h3>Newsletter <small>Signup</small></h3>
<form role="form" method="get" action="newsletter.php">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="email" placeholder="<EMAIL>">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form> -->
</div><!-- /.col -->
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div> <!-- /.col -->
</div><!-- /.row one -->
<div class="row">
<div class="col-md-4">
<div class="region-callout-box sw-handson">
<h1>Hands-On</h1>
<p>Activities for children.</p>
<a href="presentations.php#children" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="region-callout-box sw-explore">
<h1>Explore</h1>
<p>Discover historical and archaeological sites!</p>
<a href="explore.php" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
<div class="col-md-4">
<div class="region-callout-box ne-speakers">
<h1>Presentations</h1>
<p>We offer speaker presentations for adults!</p>
<a href="presentations.php#adults" class="btn btn-primary" role="button">Learn More</a>
</div>
</div><!-- /.col -->
</div><!-- /.row two -->
</div><!-- /.page-content /.container-fluid -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#swmap').mapSvg({
source: 'images/sw_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //North Central Region Marker
xy:[200,365],
tooltip:'Southeast Regional Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Charlotte' :{popover:'<h3>Charlotte</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=charlotte"> Explore Charlotte County</a></p>'},
'Glades' :{popover:'<h3>Glades</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=glades"> Explore Glades County</a></p>'},
'Hendry' :{popover:'<h3>Hendry</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=hendry"> Explore Hendry County</a></p>'},
'Lee' :{popover:'<h3>Lee</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=lee"> Explore Lee County</a></p>'},
'Collier' :{popover:'<h3>Collier</h3><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=collier"> Explore Collier County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep>/* Zenphoto administration javascript. */
function albumSwitch(sel, unchecknewalbum, msg1, msg2) {
var selected = sel.options[sel.selectedIndex];
var albumtext = document.getElementById("albumtext");
var publishtext = document.getElementById("publishtext");
var albumbox = document.getElementById("folderdisplay");
var titlebox = document.getElementById("albumtitle");
var checkbox = document.getElementById("autogen");
var newalbumbox = sel.form.newalbum;
var folder = document.getElementById("folderslot");
var exists = document.getElementById("existingfolder");
if (selected.value == "") {
newalbumbox.checked = true;
newalbumbox.disabled = true;
newalbumbox.style.display = "none";
} else {
if (unchecknewalbum) {
newalbumbox.checked = false;
}
newalbumbox.disabled = false;
newalbumbox.style.display = "";
}
var newalbum = selected.value == "" || newalbumbox.checked;
if (newalbum) {
albumtext.style.display = "block";
publishtext.style.display = "block";
albumbox.value = "";
folder.value = "";
titlebox.value = "";
exists.value = "false";
checkbox.checked = true;
document.getElementById("foldererror").style.display = "none";
toggleAutogen("folderdisplay", "albumtitle", checkbox);
} else {
albumtext.style.display = "none";
publishtext.style.display = "none";
albumbox.value = selected.value;
folder.value = selected.value;
titlebox.value = selected.text;
exists.value = "true";
}
var rslt = validateFolder(folder, msg1, msg2);
return rslt;
}
function contains(arr, key) {
var i;
for (i = 0; i < arr.length; i++) {
if (arr[i].toLowerCase() == key.toLowerCase()) {
return true;
}
}
return false;
}
function validateFolder(folderObj, msg1, msg2) {
var errorDiv = document.getElementById("foldererror");
var exists = $('#existingfolder').val() != "false";
var folder = folderObj.value;
$('#folderslot').val(folder);
if (!exists && albumArray && contains(albumArray, folder)) {
errorDiv.style.display = "block";
errorDiv.innerHTML = msg1;
return false;
} else if ((folder == "") || folder.substr(folder.length - 1, 1) == '/') {
errorDiv.style.display = "block";
errorDiv.innerHTML = msg2;
return false;
} else {
errorDiv.style.display = "none";
errorDiv.innerHTML = "";
return true;
}
}
function toggleAutogen(fieldID, nameID, checkbox) {
var field = document.getElementById(fieldID);
var name = document.getElementById(nameID);
if (checkbox.checked) {
window.folderbackup = field.value;
field.disabled = true;
return updateFolder(name, fieldID, checkbox.id);
} else {
if (window.folderbackup && window.folderbackup != "")
field.value = window.folderbackup;
field.disabled = false;
return true;
}
}
// Checks all the checkboxes in a group (with the specified name);
function checkAll(form, arr, mark) {
var i;
for (i = 0; i <= form.elements.length; i++) {
try {
if (form.elements[i].name == arr) {
form.elements[i].checked = mark;
}
} catch (e) {
}
}
}
function triggerAllBox(form, arr, allbox) {
var i;
for (i = 0; i <= form.elements.length; i++) {
try {
if (form.elements[i].name == arr) {
if (form.elements[i].checked == false) {
allbox.checked = false;
return;
}
}
}
catch (e) {
}
}
allbox.checked = true;
}
function toggleBigImage(id, largepath) {
var imageobj = document.getElementById(id);
if (!imageobj.sizedlarge) {
imageobj.src2 = imageobj.src;
imageobj.src = largepath;
imageobj.style.position = 'absolute';
imageobj.style.zIndex = '1000';
imageobj.sizedlarge = true;
} else {
imageobj.style.position = 'relative';
imageobj.style.zIndex = '0';
imageobj.src = imageobj.src2;
imageobj.sizedlarge = false;
}
}
function updateThumbPreview(selectObj) {
if (selectObj) {
var thumb = selectObj.options[selectObj.selectedIndex].style.backgroundImage;
selectObj.style.backgroundImage = thumb;
}
}
function update_direction(obj, element1, element2) {
no = obj.options[obj.selectedIndex].value;
switch (no) {
case 'custom':
$('#' + element1).show();
$('#' + element2).show();
break;
case 'manual':
case 'random':
case '':
$('#' + element1).hide();
$('#' + element2).hide();
break;
default:
$('#' + element1).show();
$('#' + element2).hide();
break;
}
}
// Uses jQuery
function deleteConfirm(obj, id, msg) {
if (confirm(msg)) {
$('#deletemsg' + id).show();
$('#' + obj).prop('checked', true);
} else {
$('#' + obj).prop('checked', false);
}
}
// Uses jQuery
// Toggles the interface for move/copy (select an album) or rename (text
// field for new filename) or none.
function toggleMoveCopyRename(id, operation) {
jQuery('#movecopydiv-' + id).hide();
jQuery('#renamediv-' + id).hide();
jQuery('#deletemsg' + id).hide();
jQuery('#move-' + id).prop('checked', false);
jQuery('#copy-' + id).prop('checked', false);
jQuery('#rename-' + id).prop('checked', false);
jQuery('#Delete-' + id).prop('checked', false);
if (operation == 'copy') {
jQuery('#movecopydiv-' + id).show();
jQuery('#copy-' + id).prop('checked', true);
} else if (operation == 'move') {
jQuery('#movecopydiv-' + id).show();
jQuery('#move-' + id).prop('checked', true);
} else if (operation == 'rename') {
jQuery('#renamediv-' + id).show();
jQuery('#rename-' + id).prop('checked', true);
}
}
function toggleAlbumMCR(prefix, operation) {
jQuery('#Delete-' + prefix).prop('checked', false);
jQuery('#deletemsg' + prefix).hide();
jQuery('#a-' + prefix + 'movecopydiv').hide();
jQuery('#a-' + prefix + 'renamediv').hide();
jQuery('#a-' + prefix + 'move').prop('checked', false);
jQuery('#a-' + prefix + 'copy').prop('checked', false);
jQuery('#a-' + prefix + 'rename').prop('checked', false);
if (operation == 'copy') {
jQuery('#a-' + prefix + 'movecopydiv').show();
jQuery('#a-' + prefix + 'copy').prop('checked', true);
} else if (operation == 'move') {
jQuery('#a-' + prefix + 'movecopydiv').show();
jQuery('#a-' + prefix + 'move').prop('checked', true);
} else if (operation == 'rename') {
jQuery('#a-' + prefix + 'renamediv').show();
jQuery('#a-' + prefix + 'rename').prop('checked', true);
}
}
// Toggles the extra info in the admin edit and options panels.
function toggleExtraInfo(id, category, show) {
var prefix = '';
if (id != null && id != '') {
prefix = '#' + category + '-' + id + ' ';
}
if (show) {
jQuery(prefix + '.' + category + 'extrainfo').show();
jQuery(prefix + '.' + category + 'extrashow').hide();
jQuery(prefix + '.' + category + 'extrahide').show();
} else {
jQuery(prefix + '.' + category + 'extrainfo').hide();
jQuery(prefix + '.' + category + 'extrashow').show();
jQuery(prefix + '.' + category + 'extrahide').hide();
}
}
// used to toggle fields
function showfield(obj, fld) {
no = obj.options[obj.selectedIndex].value;
document.getElementById(fld).style.display = 'none';
if (no == 'custom')
document.getElementById(fld).style.display = 'block';
}
// password field hide/disable
function toggle_passwords(id, pwd_enable) {
toggleExtraInfo('', 'password' + id, pwd_enable);
if (pwd_enable) {
jQuery('#password_enabled' + id).val('1');
} else {
jQuery('#password_enabled' + id).val('0');
}
}
function resetPass(id) {
$('#user_name' + id).val('');
$('#pass' + id).val('');
$('#pass_r' + id).val('');
$('.hint' + id).val('');
toggle_passwords(id, true);
}
// toggels the checkboxes for custom image watermarks
function toggleWMUse(id) {
if (jQuery('#image_watermark-' + id).val() == '') {
jQuery('#WMUSE_' + id).hide();
} else {
jQuery('#WMUSE_' + id).show();
}
}
String.prototype.replaceAll = function(stringToFind, stringToReplace) {
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
function addNewTag(id) {
var tag;
tag = $('#newtag_' + id).val();
if (tag) {
$('#newtag_' + id).val('');
var name = id + tag;
//htmlentities
name = encodeURI(name);
name = name.replaceAll('%20', '__20__');
name = name.replaceAll("'", '__27__');
name = name.replaceAll('.', '__2E__');
name = name.replaceAll('+', '__20__');
name = name.replaceAll('%', '__25__');
name = name.replaceAll('&', '__26__');
var lcname = name.toLowerCase();
var exists = $('#' + lcname).length;
if (exists) {
$('#' + lcname + '_element').remove();
}
html = '<li id="' + lcname + '_element"><label class="displayinline"><input id="' + lcname + '" name="' + name +
'" type="checkbox" checked="checked" value="1" />' + tag + '</label></li>';
$('#list_' + id).prepend(html);
}
}
<file_sep><div id="menu" role="navigation" class="region-menu">
<a href="/"> <img src="/images/FPAN_Vert.svg" class="img-responsive hidden-xs logo-vert"/> </a>
<h1 class="hidden-xs text-center"><a href="/serc">Southeast</a> <small>Region</small></h1>
<ul class="nav nav-pills nav-stacked">
<li class="<?=activeClassIfMatches('index')?>"><a href="index.php" > <span class="glyphicon glyphicon-home hidden-sm"></span> Home</a></li>
<li class="<?=activeClassIfMatches('eventList')?>"><a href="eventList.php"> <span class="glyphicon glyphicon-calendar hidden-sm"></span> Events</a></li>
<li class="<?=activeClassIfMatches('volunteer')?>"><a href="volunteer.php"> <span class="glyphicon glyphicon-user hidden-sm"></span> Volunteer</a></li>
<li class="<?=activeClassIfMatches('explore')?> dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><span class="glyphicon glyphicon-map-marker hidden-sm"></span> Explore <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li><a href="explore.php?county=broward">Broward</a></li>
<li><a href="explore.php?county=miamidade">Miami-Dade</a></li>
<li><a href="explore.php?county=monroe">Monroe</a></li>
<li><a href="explore.php?county=palmbeach">Palm Beach</a></li>
</ul>
</li>
<li class="<?=activeClassIfMatches('presentations')?>"><a href="presentations.php"> <span class="glyphicon glyphicon-bullhorn hidden-sm"></span> Presentations</a></li>
<li class="<?=activeClassIfMatches('siteprotection')?>"><a href="siteprotection.php"> <span class="glyphicon glyphicon-globe hidden-sm"></span> Site Protection</a></li>
<!-- <li class="<?=activeClassIfMatches('newsletter')?>"><a href="newsletter.php"> <span class="glyphicon glyphicon-comment hidden-sm"></span> Newsletter</a></li> --> <li class="<?=activeClassIfMatches('contact')?>"><a href="contact.php"> <span class="glyphicon glyphicon-phone hidden-sm"></span> Contact</a></li>
<li class="text-center visible-xs"><a href="#"><span class="glyphicon glyphicon-collapse-up"></span></a></li>
</ul>
</div>
<div class="text-center">
<a href="https://securelb.imodules.com/s/1647/giving.aspx?sid=1647&gid=2&pgid=518&fid=1147&gfid=191&dids=255" class="btn btn-donate btn-default center-block" target="_blank">
<small>Support public archaeology,</small><br/><span class="glyphicon glyphicon-gift hidden-sm"></span> Donate to FPAN!
</a>
</div>
<file_sep><?php
session_start();
include_once('dbConnect.php');
//If user is already logged in, redirect to main page
if(isset($_SESSION['my_email']) && ($_GET['logout'] != 1)){?>
<script type="text/javascript">
<!--
window.location = "main.php";
//-->
</script>
<?php }
//If the form was submitted
if($submit){
// Define $email and $password, protect against SQL injection
$email = mysql_real_escape_string( stripslashes($_POST['email']));
$password = mysql_real_escape_string( stripslashes($_POST['password']));
$_SESSION['aes_key'] = "<KEY>";
//Check database for user
$sql = "SELECT * FROM Employees WHERE email='$email' and password=<PASSWORD>('$password', '$_SESSION[aes_key]')";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
// If there is one row, username and password are correct
if($count==1){
$userInfo = mysql_fetch_array($result);
//Set session variables
$_SESSION['my_id'] = $userInfo['id'];
$_SESSION['my_role'] = $userInfo['role'];
$_SESSION['my_name'] = $userInfo['firstName'] ." ". $userInfo['lastName'];
$_SESSION['my_position'] = $userInfo['position'];
$_SESSION['my_email'] = $userInfo['email'];
//Check user for regions
$region_sql = "SELECT region FROM EmployeeRegion WHERE employeeID = '$_SESSION[my_id]'";
$region_result = mysql_query($region_sql);
while($row = mysql_fetch_assoc($region_result)){
$_SESSION['my_regions'][] = $row['region'];
}
//Redirect to main page
?>
<script type="text/javascript">
<!--
window.location = "main.php";
//-->
</script>
<?php
}else{
$msg = "Invalid username or password.";
$err = true;
}
}
//User tried to access page that requires login and was redirected here
if((!isset($_SESSION['my_email'])) && ($_GET['loggedIn'] == "no") && ($_GET['logout'] != 1)){
$msg = "You are not currently logged in.";
$err = true;
}
//User has logged out
if($_GET['logout'] == 1){
$msg = "You have logged out.";
//empty session array
$_SESSION = array();
//end session
session_destroy();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FPAN Activity Reports</title>
<link rel="stylesheet" type="text/css" href="resources/css/forms.css" media="all">
<link rel="stylesheet" type="text/css" href="resources/css/style.css" media="all">
<script type="text/javascript" src="resources/view.js"></script>
<script type="text/javascript" src="resources/calendar.js"></script>
<script type="text/javascript" src="resources/java.js"></script>
</head>
<body id="main_body" >
<img id="top" src="images/top.png" alt="">
<div id="form_container">
<div id="header">
<a href="main.php"><img src="images/sun.png" align="right" /></a>
<h1>FPAN Reports System </h1>
</div>
<p></p>
<table class="logTable">
<tr>
<td>
<?php
if($msg){
if($err) $class = "err_msg";
else $class = "msg";
echo "<p align=\"center\" class=\"$class\"> $msg </p>";
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" class="orange">
<table width="250" border="0" align="center" cellpadding="3" cellspacing="0" >
<tr>
<td><div align="right">Email:</div></td>
<td><input name="email" id="email" type="text" size="25" placeholder="<EMAIL>" autofocus >
</td>
</tr>
<tr>
<td><div align="right">Password:</div></td>
<td><input name="password" id="password" type="password" placeholder="default is '<PASSWORD>'" >
</td>
</tr>
<tr>
<td colspan="2" valign="middle"><div align="center"> <br />
<input name="submit" type="submit" value="Login" />
</div></td>
</tr>
<tr>
</tr>
</table>
</form>
<!--
<h2 align="center"> The system is currently down for maintenance. Please try again later.</h2>
-->
</td>
</tr>
</table>
<br/>
</div>
</body>
</html>
<file_sep><?php
$pageTitle = "Presentations";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?> <small>& Programs</small> </h1>
</div>
<div class="box-dash">
<p>FPAN can help facilitate speakers for meetings of your civic group, community organization,
youth club, or heritage society, and for lecture series and special events.</p>
<p>Most presentations last about 30-45 minutes with additional time for questions, although
programs usually can be tailored for your needs. Specific topics are dependent on speaker
availability, so book early! There is no charge for presentations, although donations are
gratefully accepted to support FPAN educational programs.</p>
<p>Presentation topics are divided into two sections: </p>
<div class="col-sm-12 text-center">
<p>
<a href="#children" class="btn btn-info">Activities for Children</a>
<a href="#adults" class="btn btn-info">Presentation Topics for Adults</a>
</p>
</div>
<p>Take a look at our offerings, then <a href="https://casweb.wufoo.com/forms/northeast-speaker-request-form/">
submit the form below</a> and let us
know what you’d like to learn about! If you don’t see what you’re looking for, ask us and we’ll do our
best to accommodate you.</p>
<p class="text-center"><em>Know what you want?</em> <br/> <a class="btn btn-primary"
href="https://casweb.wufoo.com/forms/northeast-speaker-request-form/" target="_blank">Submit a Speaker Request Form</a> </p>
</div>
<h2 id="children">Hands-On <small>Activities for Children</small></h2>
<div class="box-tab row">
<p>FPAN staff is available to visit your classroom, camp or club and provide hands-on archaeology education activities. If interested, select from presentation list below and fill out our program request form at the top of the page. Programs are free for public schools, public libraries, local museums and non-profit organizations. Florida Archaeology Month (March) and Summer calendars fill up fast so please schedule as soon as possible in advance.</p>
<div class="col-sm-6">
<ul>
<li><a href="#timu">Timucuan Pyrotechnology</a></li>
<li><a href="#tools">Tools of the Trade</a> </li>
<li><a href="#pbj">PB&J: How (and why!) Archaeologists Find Sites </a></li>
<li><a href="#prepot">Prehistoric Pottery</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#underwater">Underwater Archaeology</a></li>
<li><a href="#kingsley">Kingsley Slave Cabin Archaeology</a></li>
<li><a href="#prefl">Make Prehistoric Florida your Home </a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div id="timu" class="col-sm-12">
<h3>Timucuan Pyrotechnology</h3>
<p>This activity introduces students to Timucuan culture, focusing on ways that local prehistoric people used fire to meet their daily needs. A hands-on experiment provides a bang as students use balloons (and water balloons!) to explore how prehistoric people could cook prior to the advent of pottery.</p>
</div>
<div id="tools" class="col-sm-12">
<h3>Tools of the Trade </h3>
<p>One of the best ways to show people how we study a site is to share our tool kit. Students observe the tools we use in the field and infer the reasoning behind our choices. For example, many people may know we use a trowel, but what's the difference between the pointy ones versus the flat edge blades? What would we do that? Tools include trowels (yes, plural!), munsell color chart, line levels, various measuring devices, and root clippers. The most important? Our pencil and sharpie for recording our findings. </p>
</div>
<div id="pbj" class="col-sm-12">
<h3>PB&J: How (and why!) Archaeologists Find Sites </h3>
<p>A classic! Students systematically excavate a peanut butter and jelly sandwich to explore the concepts of stratigraphy and survey, emphasizing how archaeologists use the scientific method in the field. If Power Point is available, this activity can include pictures of real tools, fieldwork, and sites to enhance learning.</p>
</div>
<div id="prepot" class="col-sm-12">
<h3>Prehistoric Pottery</h3>
<p>Students learn about the advent of pottery in Florida, and do hands-on experimentation using play-doh to explore pottery-making and -decorating technology. The lesson also teaches about how pottery can help archaeologists understand a site and its prehistoric people.</p>
</div>
<div id="underwater" class="col-sm-12">
<h3>Underwater Archaeology</h3>
<p>This lesson uses on the book Shipwreck: Fast Forward to explore how underwater sites form, and the excavation processes used to retrieve information about them. Kids then try their own hand at using Cartesian coordinates by playing an adapted version of Battleship to “map” each other’s shipwrecks, and they get to map a real, 100-year-old anchor!</p>
</div>
<div id="kingsley" class="col-sm-12">
<h3>Kingsley Slave Cabin Archaeology</h3>
<p>Recent excavations at Kingsley Plantation have radically changed our understanding of what life was like for the enslaved people living there. This lesson tasks students with mapping artifacts exactly where they were found in the cabin, just like archaeologists do. After mapping, they work in teams to classify artifacts. Finally, as a group we discuss explore what we can understand about this population by looking at these artifacts in context (where they were found and with what other objects).</p>
</div>
<div id="prefl" class="col-sm-12">
<h3>Make Prehistoric Florida your Home </h3>
<p>Geared toward younger adults (but good for adults also), this presentation teaches the natural resources available to Native Americans, and how they could be used to construct their campsites and villages. What did an ancient Native American town look like? How did they build their houses and shelter? How did they construct giant mounds? What did they make their tools and clothing out of? All ages enjoy learning how ancient peoples used the natural environment to hunt, fish, build towns, and make a living in prehistoric Florida. </p>
</div>
</div><!-- /.box /.row -->
<h2 id="adults">Presentation<small> Topics for Adults</small></h2>
<div class="box-tab row">
<p>FPAN staff is available to come talk to local libraries, civic organizations, historical societies and any other group interested in hearing more about Florida archaeology. Below are some of the standard talks we give in the region but we are often able to custom make a talk based on your interest. Select a title from the list below to fill out the program request form at the top of the page or get in touch with us at <a href="mailto:<EMAIL>"><EMAIL></a>. Programs are free and subject to staff availability for scheduling.</p>
<div class="col-sm-6">
<ul>
<li><a href="#16th">In Search of 16th-Century St. Augustine</a></li>
<li><a href="#stjohns">Archaeology Along the St. Johns River</a></li>
<li><a href="#fantastic">Fantastic Archaeology: Florida Frauds, Myths, and Mysteries</a> </li>
<li><a href="#coquina">Coquina: Florida's Pet Rock</a> </li>
<li><a href="#preweap">Prehistoric Weaponry</a> </li>
<li><a href="#preweaptool">Prehistoric Weaponry and Tools</a></li>
<li><a href="#timutech">Timucuan Technology</a></li>
<li><a href="#archfl">Archaeology in Florida State Parks</a> </li>
<li><a href="#grit">Grit Tempered II: Famous Women in Florida Archaeology</a></li>
<li><a href="#flwars">How the Florida Wars Changed Us All</a></li>
<li><a href="#somber">From Somber Tombs to Grand Memorials: The Cemetery Movement in the US</a></li>
<li><a href="#losttribe">Searching for the Lost Tribes: The Ais and the Mayaca</a></li>
<li><a href="#meanwhile">Meanwhile, in Florida... A Brief History of Odd Happenings in the Sunshine State</a></li>
<li><a href="#prepot101">Prehistoric Pottery 101</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#shiptime">A Florida Shipwreck through Time</a> </li>
<li><a href="#histcem">Historic Cemeteries as Outdoor Museums</a></li>
<li><a href="#prehist">14,000 Years of Florida Prehistory</a> </li>
<li><a href="#paleo">Paleoenvironments</a> </li>
<li><a href="#shells">Shells</a> </li>
<li><a href="#archshells">Archaeology and Shells</a></li>
<li><a href="#minorca">Prehistory and Maritime Archaeology of Minorca</a></li>
<li><a href="#cemshells">The Shells of Florida’s Historic Cemeteries</a></li>
<li><a href="#prepen">Prehistoric Peninsula</a></li>
<li><a href="#graffiti">Ancient Graffiti</a></li>
<li><a href="#gpr">Visualizing the Unseen: Ground Penetrating Radar and Archaeology</a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div id="16th" class="col-sm-12">
<h3>In Search of 16th-Century St. Augustine</h3>
<p>Walking the streets of St. Augustine can confuse the visitor in search of the 16th century, but 450-year-old sites are there—often beneath their feet. This presentation synthesizes work done by archaeologists over the past century and focuses on small objects that bring ordinary people in the 16th century to life. Those planning to partake in the city's birthday party will benefit from the presentation’s culmination of “Ten Things to Do to Prepare for the 450th.” </p>
</div>
<div id="stjohns" class="col-sm-12">
<h3>Archaeology Along the St. Johns River</h3>
<p>The St. Johns River has played an ever-changing role in the lives of Floridians for thousands of years. Prehistorically, the river provided food, transportation, and a geographic connection between cultures living from the source to the mouth. Historically, the river supported missions, plantations, and military outposts. Exploration is not limited to land; famous archaeological sites on the river's bottom add to our knowledge of Florida's past. </p>
</div>
<div id="fantastic" class="col-sm-12">
<h3>Fantastic Archaeology: <small>Florida Frauds, Myths, and Mysteries</small> </h3>
<p>Celebrate Florida archaeology by learning what archaeology is, and importantly what it is not. This educational and entertaining talk will focus on the misuse and abuse of Florida's past. Moving from historical to modern day examples we discuss the many ways “belief in nonsense can be dangerous (<NAME>).” </p>
</div>
<div id="coquina" class="col-sm-12">
<h3>Coquina: Florida's Pet Rock </h3>
<p>Coquina is a conglomerate rock unique to Florida’s east coast. Since the 1590s when the Spanish first established quarries, coquina was used to build every type of structure from the historic period: forts, plantations, sugar mills, houses, businesses, even cemeteries. Drawing from resources developed for the <em><a href="http://www.coquinaqueries.com" target="_blank">Coquina Queries</a></em> teacher activity guide, this talk introduces participants to the sweeping array of coquina ruins they can visit in northeast Florida, including formation, excavation, and preservation. </p>
</div>
<div id="preweap" class="col-sm-12">
<h3>Prehistoric Weaponry</h3>
<p>The difference between a tool and a weapon is a matter of intent. While this can be difficult to ascribe archaeologically, humans have used tools as weapons for hundreds of thousands of years. This presentation looks at the tool kits of prehistoric Timucuans and focuses on the atl-atl as the weapon of choice. Hands-on atl-atl demonstration available depending on time and outdoor space requirements. </p>
</div>
<div id="preweaptool" class="col-sm-12">
<h3>Prehistoric Weaponry and Tools</h3>
<p>We often don’t think of prehistoric peoples in Florida as being technologically advanced, but archaeological and historical data shows that native peoples were incredibly sophisticated in their tool use. This presentation can be tailored for all group levels, children to adult. Learn how Florida’s native people utilized their environment to make tools and what kinds of weapons they produced. This presentation also discusses how and why we know about these tools through archaeological investigations and historical document research. </p>
</div>
<div id="timutech" class="col-sm-12">
<h3>Timucuan Technology</h3>
<p>As Florida turned 500 we looked to how people met their basic needs before Spanish arrival. Tools made from plant and animal sources were used to hunt, provide shelter, and strengthen ties between the people who spoke the Timucuan language. Drawing from biotechnology plans developed for the <a href="../resources/timucuan">Timucuan Technology activity guide</a>, this presentation is available as a general discussion of tools or specialized lectures by material type: plants, animals, shells, pottery, or pyrotechnology. </p>
</div>
<div id="archfl" class="col-sm-12">
<h3>Archaeology in Florida State Parks </h3>
<p>When people first realize archaeology happens in Florida, it often surprises them to hear of how many active permits are issued to do work in state parks. Some of the digs are by field school where students learn the ABCs of excavation, while other digs are done in advance of construction or improvements to a park. This lecture emphasizes visitation of the many parks that feature archaeology interpreted for the public including Ft. Mose, Hontoon Island, Crystal River, Bulow Sugar Mill, Ft. Clinch, De Leon Springs, and many more. </p>
</div>
<div id="grit" class="col-sm-12">
<h3>Grit Tempered II: <small>Famous Women in Florida Archaeology</small></h3>
<p>In 1991 the book <NAME>ed: Early Women Archaeologists in the Southeastern United States was published to highlight to contributions of women who made archaeology what it is today. Since that time, the tradition of strong women archaeologists has continued. This talk presupposes a Grit Tempered II sequel and nominates five phenomenal Florida women for consideration: <NAME> (St. Augustine), <NAME> (Pensacola), <NAME> (Tallahassee), <NAME> (Amelia Island) and <NAME> (Gulf Coast). Come learn more about these women, their enduring impact on how we understand our past, and the sites that made them famous.</p>
</div>
<div id="flwars" class="col-sm-12">
<h3>How the Florida Wars Changed Us All</h3>
<p>Between 1817 and 1858, Florida was the location of three wars fought over land ownership and cultural differences. The Seminoles turned out to be the longest Indian conflict in US history. Learn how these wars shaped the people and landscape of Florida and discover how archaeologists are uncovering clues about them almost two centuries later.</p>
</div>
<div id="somber" class="col-sm-12">
<h3>From Somber Tombs to Grand Memorials:<small> The Cemetery Movement in the US</small></h3>
<p>Cemeteries today are peaceful parks that can help us remember our loved ones. But this was not always so! Learn about the cemetery movement in the United States, from colonial burying grounds to rolling memorial parks, and how our ideas of death helped shape our final resting places.</p>
</div>
<div id="losttribe" class="col-sm-12">
<h3>Searching for the Lost Tribes: <small>The Ais and the Mayaca</small></h3>
<p>Native peoples lived along Florida’s east coast for thousands of years before the explorers arrived from across the sea. Yet none of these cultures survived today. Join archaeologists on the search for the lost tribes of the Ais and Mayaca, contact-period tribes living near the Indian River. Learn how archaeology can help us uncovered information about these peoples who were lost to disease, displacement and changing cultures.</p>
</div>
<div id="meanwhile" class="col-sm-12">
<h3>Meanwhile, in Florida…A Brief History of Odd Happenings in the Sunshine State</h3>
<p>Florida has a long history of odd behaviors, interesting characters and fierce natural environs. Learn how natives remained hunter/gatherers until the Spanish arrived, why runaway slaves sought new lives St. Augustine and how an oil barren spent his fortune on Florida.</p>
</div>
<div id="prepot101" class="col-sm-12">
<h3>Prehistoric Pottery 101</h3>
<p>Did you know that some of the oldest pottery in North America started in Florida 4500 years ago? Learn all about how native Floridians made pottery, the common identifiers and types in your area and how archaeologists learn about people of the past through potsherds!</p>
</div>
<div id="shiptime" class="col-sm-12">
<h3>A Florida Shipwreck through Time </h3>
<p>Based on the book <a href="http://www.amazon.com/Shipwreck-Leap-Through-Claire-Aston/dp/1901323587/ref=sr_1_2?s=books&ie=UTF8&qid=1283977267&sr=1-2">Shipwreck: Leap through Time</a>, this talk takes the audience through the stages of a shipwreck--from ship construction to underwater museum. The issue of piracy in archaeology is addressed, as well as expanding known submerged resources beyond maritime themes. </p>
</div>
<div id="histcem" class="col-sm-12">
<h3>Historic Cemeteries as Outdoor Museums</h3>
<p>We encourage families and classes to get into the cemeteries within their communities and put archaeological principles to the test. This presentation can be brought via Powerpoint or introduced on-site at an actual cemetery. Iconography, dating of headstones, and change of style over time (seriation) are emphasized along with lessons in cemetery preservation. </p>
</div>
<div id="prehist" class="col-sm-12">
<h3>14,000 Years of Florida Prehistory </h3>
<p>This lecture discusses the chronology of Florida’s prehistoric Native Americans, and discusses their major technological achievements through time. 14k Years of FL Prehistory presents the four archaeological time periods in the southeastern United States, and how archaeologists use them to differentiate among different culture groups. This presentation is perfect for those looking for a broad overview of prehistoric archaeology in Florida. </p>
</div>
<div id="paleo" class="col-sm-12">
<h3>Paleoenvironments </h3>
<p>How do archaeologists learn what past environments were like? This lecture covers the study of archaeological bones, shells, and other faunal artifacts, and also pollen and other plant remains to learn about ancient environments. It also discusses sediment coring to investigate different geological layers. ‘Paleoenvironments’ is a wonderful lecture if you’re interested in how Florida’s environment has changed affected Natives over time. </p>
</div>
<div id="shells" class="col-sm-12">
<h3>Shells </h3>
<p>The shell workshop includes both lecture- and activity-based components. It introduces participants to common Florida shells, found in both prehistoric middens and along today’s modern beaches and tidal flats. The lecture portion emphasizes the physical characteristics of species, but also discusses their ecology, how they were used by Native Americans and Europeans, and how archaeologists use them to understand past peoples and environments. The activities include shell-related games for kids, and fun shell midden scenarios/problems for adults to solve. </p>
</div>
<div id="archshells" class="col-sm-12">
<h3>Archaeology and Shells </h3>
<p>The shell workshop includes both lecture- and activity-based components. It introduces participants to common Florida shells, found in both prehistoric middens and along today’s modern beaches and tidal flats. The lecture portion emphasizes the physical characteristics of the species, their ecology, how they were used by Native Americans, and how archaeologists use them to learn about past peoples and places. </p>
</div>
<div id="minorca" class="col-sm-12">
<h3>Prehistory and Maritime Archaeology of Minorca</h3>
<p>An excellent fit for northeast Floridians interested in our region’s connection to the Mediterranean during the British period, this lecture features a discussion of ongoing maritime research in Minorca, as well as daily life and culture in the major cities. The second half features a prehistoric and historic chronology of island, and the political context of the immigration to northeast and east-central Florida.</p>
</div>
<div id="cemshells" class="col-sm-12">
<h3>The Shells of Florida’s Historic Cemeteries</h3>
<p>Have you ever seen large conch shells at a historic cemetery? Where did these shells come from, and how did they get there? What cultures use shells at burial markers? What do they mean? Find out the answers to these questions and more over the course of this presentation.</p>
</div>
<div id="prepen" class="col-sm-12">
<h3>Prehistoric Peninsula</h3>
<p>We often don’t think of prehistoric peoples in Florida as being technologically advanced, but archaeological and historical data shows that native peoples were incredibly sophisticated in their tool use. This presentation can be tailored for all group levels, children to adult. Learn how Florida’s native people utilized their environment to make tools and what kinds of weapons they produced. This presentation also discusses how and why we know about these tools through archaeological investigations and historical document research.</p>
</div>
<div id="graffiti" class="col-sm-12">
<h3>Ancient Graffiti</h3>
<p>To some, graffiti is a nuisance. To others, graffiti is art. To archaeologists, graffiti can provide valuable insight to otherwise intangible aspects of past cultures. This presentation can be suited for all ages and discusses the role of graffiti in cultures past and present.</p>
</div>
<div id="gpr" class="col-sm-12">
<h3>Visualizing the Unseen: Ground Penetrating Radar and Archaeology</h3>
<p>Over the past several decades new technology has been increasingly used by archaeologists to visualize archaeological features beneath the surface without invasive testing. Ground Penetrating Radar is one of the most popular of these geophysical survey methods. This presentation is geared for adult audiences and discusses GPR operation, gives case studies of its use, and discusses the wider realm of technology within archaeology with a focus on future applications. </p>
</div>
</div><!-- /.box /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
// force UTF-8 Ø
if (!defined('WEBPATH'))
die();
?>
<!DOCTYPE html>
<html>
<head>
<?php zp_apply_filter('theme_head'); ?>
<?php printHeadTitle(); ?>
<meta charset="<?php echo LOCAL_CHARSET; ?>">
<meta http-equiv="content-type" content="text/html; charset=<?php echo LOCAL_CHARSET; ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="<?php echo $_zp_themeroot; ?>/style.css" />
<?php jqm_loadScripts(); ?>
</head>
<body>
<?php zp_apply_filter('theme_body_open'); ?>
<div data-role="page" id="mainpage">
<?php jqm_printMainHeaderNav(); ?>
<div class="ui-content" role="main">
<div class="content-primary">
<?php printGalleryDesc(); ?>
<?php
if (function_exists('printLatestImages')) {
?>
<h2><?php echo gettext('Latest images'); ?></h2>
<?php $latestimages = getImageStatistic(8, 'latest', '', false, 0, 'desc'); ?>
<div class="ui-grid-c">
<?php
$count = '';
foreach ($latestimages as $image) {
$count++;
switch ($count) {
case 1:
$imgclass = ' ui-block-a';
break;
case 2:
$imgclass = ' ui-block-b';
break;
case 3:
$imgclass = ' ui-block-c';
break;
case 4:
$imgclass = ' ui-block-d';
$count = ''; // reset to start with a again;
break;
}
?>
<a class="image<?php echo $imgclass; ?>" href="<?php echo html_encode($image->getLink()); ?>" title="<?php echo html_encode($image->getTitle()); ?>">
<img src="<?php echo $image->getCustomImage(null, 230, 230, 230, 230, null, null, true, NULL); ?>" alt="<?php echo $image->getTitle(); ?>">
</a>
<?php
}
}
?>
</div>
<br class="clearall" />
<br />
<?php if (function_exists('next_news')) { ?>
<ul data-role="listview" data-inset="true" data-theme="a" class="ui-listview ui-group-theme-a">
<li data-role="list-divider"><h2><?php echo gettext('Latest news'); ?></h2></li>
<?php while (next_news()): ?>
<li>
<a href="<?php echo html_encode(jqm_getLink()); ?>" title="<?php printBareNewsTitle(); ?>">
<?php printNewsTitle(); ?> <small>(<?php printNewsDate(); ?>)</small>
</a>
</li>
<?php
endwhile;
?>
</ul>
<?php
}
?>
</div>
<div class="content-secondary">
<?php jqm_printMenusLinks(); ?>
</div>
</div><!-- /content -->
<?php jqm_printBacktoTopLink(); ?>
<?php jqm_printFooterNav(); ?>
</div><!-- /page -->
<?php zp_apply_filter('theme_body_close'); ?>
</body>
</html>
<file_sep><?php
$pageTitle = "Volunteer";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-dash">
<div class="text-center">
<!-- <div class="image center-block" style="max-width:400px;">
<img src="images/getinvolved.jpg" alt="" class="img-responsive" >
<p> </p>
</div> -->
<p>The Southwest Region of the Florida Public Archaeology Network does not have on-going volunteer opportunities, but we are happy to guide you toward appropriate heritage-minded organizations within our community. <a href="mailto:<EMAIL>">Contact us to learn more</a></p>
</div>
</div><!-- /.box-tab -->
<h2>Get Involved</h2>
<div class="box-tab">
<p>There are many Organizations you can join to pursue an interest in archaeology. Here are some of our favorites:</p>
<h3>State Organizations</h3>
<ul>
<li><a target="_blank" href="http://www.fasweb.org/">Florida Anthropological Society</a></li>
<li><a target="_blank" href="http://www.flamuseums.org/">Florida Association of Museums</a></li>
<li><a target="_blank" href="http://www.floridatrust.org/">Florida Trust</a></li>
</ul>
<h3>National & International Organizations</h3>
<ul>
<li><a target="_blank" href="http://www.saa.org/">Society for American Anthropology</a></li>
<li><a target="_blank" href="http://www.sha.org/">Society for Historical Archaeology</a></li>
<li><a target="_blank" href="http://www.southeasternarchaeology.org/">Southeastern Archaeological Conference</a></li>
<li><a target="_blank" href="http://www.interpnet.com/">National Association for Interpretation</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Virtual Florida Fieldtrips";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Virtual Florida Fieldtrips</h1></th>
</tr>
<tr>
<td class="table_mid">
<table style="margin-left:auto; margin-right:auto;">
<tr>
<td><p><img src="images/vff.jpg" alt="Virtual Florida Fieldtrips" /></p>
<p><a href="http://www.flpublicarchaeology.org/resources/videos.php?video=MalaCompra">MALA COMPRA</a></p>
<p><a href="http://www.flpublicarchaeology.org/resources/videos.php?video=NombreDeDios">NOMBRE DE DIOS</a></p>
<p><a href="http://www.flpublicarchaeology.org/resources/videos.php?video=Smyrnea">THE SMYRNEA SETTLEMENT</a></p>
<p><a href="http://www.flpublicarchaeology.org/resources/videos.php?video=SugarMills">SUGAR MILLS </a></p>
<p><a href="http://www.flpublicarchaeology.org/resources/videos.php?video=CastilloDeSanMarcos">CASTILLO DE SAN MARCOS</a> </p>
<p><a href="http://www.flpublicarchaeology.org/resources/videos.php?video=KingsleyPlantation">KINGSLEY PLANTATION </a></p>
<p><a href="http://www.flpublicarchaeology.org/resources/videos.php?video=XimenezFatio">XIMENEZ-FATIO HOUSE </a></p>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
include 'header.php';
$serviceArray = array();
$typeService = $_GET['typeService'];
$serviceID = $_GET['id'];
$title = getTitle($typeService);
$page = getPage($typeService);
//Delete service
if($_GET['submit'] == 'Delete'){
$sql = "DELETE FROM $typeService WHERE id = $serviceID; ";
mysql_query($sql) ? $err = false : $err = true;
$sql = "DELETE FROM EmployeeActivity WHERE activityID = $serviceID; ";
mysql_query($sql) ? $err = false : $err = true;
$sql = "DELETE FROM Activity WHERE id = $serviceID; ";
mysql_query($sql) ? $err = false : $err = true;
if(!$err)
$msg = "Event was successfully deleted!";
else
$msg = "Error: Event was unable to be deleted.";
echo "<div class=\"summary\">";
echo "<br/><br/><h3>".$msg."</h3><br/><br/><br/><br/>";
echo "<a href=\"viewTypeActivities.php?typeActivity=$typeService\">View other ".$title." services.</a>";
echo " or <a href=\"main.php\">return to main menu</a>. <br/><br/>";
echo "</div>";
}else{
?>
<table width="600" border="0" cellspacing="2" align="center">
<tr>
<td valign="top">
<h2 align="center"><?php echo $title; ?></h2>
<hr/>
<?php
$thisServiceArray = getService($typeService, $serviceID);
printService($thisServiceArray);
//Only show edit/delete buttons for authorized users
if(canEdit()){
?>
<div align="center">
<form method="get" action="<?php echo $page; ?>">
<input type="hidden" name="id" value="<?php echo $serviceID; ?>" />
<input type="submit" name="submit" value="Edit" />
</form>
<form method="get" action="<?php curPageUrl(); ?>" onsubmit="return confirm('Are you SURE you wish to delete this?');">
<input type="hidden" name="id" value="<?php echo $serviceID; ?>" />
<input type="hidden" name="typeService" value="<?php echo $typeService; ?>" />
<input type="submit" name="submit" value="Delete" />
</form>
</div>
</td>
</tr>
</table>
<?php
} //end canEdit if
} //endif ?>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "Presentations";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?> <small>& Programs</small> </h1>
</div>
<div class="box-dash">
<p>FPAN can help facilitate speakers for meetings of your civic group, community organization,
youth club, or heritage society, and for lecture series and special events.</p>
<p>Most presentations last about 30-45 minutes with additional time for questions, although
programs usually can be tailored for your needs. Specific topics are dependent on speaker
availability, so book early! There is no charge for presentations, although donations are
gratefully accepted to support FPAN educational programs.</p>
<p>Take a look at our offerings, then <a href="https://casweb.wufoo.com/forms/southeast-speaker-request-form/">
submit the form below</a> and let us
know what you’d like to learn about! If you don’t see what you’re looking for, ask us and we’ll do our
best to accommodate you.</p>
<p class="text-center"><em>Know what you want?</em> <br/> <a class="btn btn-primary"
href="https://casweb.wufoo.com/forms/southeast-speaker-request-form/" target="_blank">Submit a Speaker Request Form</a> </p>
</div>
<h2 id="adults">Presentation Topics</h2>
<div class="box-tab row">
<div class="col-sm-6">
<ul>
<li><a href="#presnow">Prehistoric Snowbirds</a></li>
<li><a href="#medplants">Native American Medicinal Plants</a></li>
<li><a href="#weeds">Weeds and Seeds: A History of Dining in Southern Florida</a> </li>
<li><a href="#newriver">History and Prehistory of the New River</a></li>
<li><a href="#everglades">Who Made the Everglades?</a> </li>
<li><a href="#whatarch">What the Heck is Archaeology</a></li>
<li><a href="#hiddenhistory">Hidden History of the Dry Tortugas: Writings on the Walls</a></li>
<li><a href="#art">Art and Artifacts</a></li>
<li><a href="#iceage">Florida’s Ice Age</a></li>
</ul>
</div>
<div class="col-sm-6">
<ul>
<li><a href="#civwar">More than a Trifling Affair: The Archaeology of the Civil War in Southwest Florida</a></li>
<li><a href="#curious">The Curious Archaeology of Spanish Explorers in Florida</a></li>
<li><a href="#cemeteries">As You Are Now, So Once Was I: Decoding Florida’s Cemeteries</a></li>
<li><a href="#booze">Pay no attention to the man behind the boat!: The Archaeology of Booze and Beverages</a></li>
<li><a href="#deep">Dispatches from the Deep: The Archaeology of Florida’s Spanish Shipwrecks</a></li>
</ul>
</div>
<div class="col-sm-12">
<hr/>
</div>
<div id="presnow" class="col-sm-12">
<h3>Prehistoric Snowbirds</h3>
<p>We are not the first people to realize the wonders of Southern Florida; people have been living here for over 10,000 years. Come learn about these prehistoric snowbirds and the evidence they left, as they made seasonal rounds throughout the United States. See if people have been traveling your route for thousands of years!</p>
</div>
<div id="medplants" class="col-sm-12">
<h3>Native American Medicinal Plants</h3>
<p>Medicinal plants have a long history of use and are still the most commonly used medicine in the world today. Come learn about medicinal plants used by Native Americans; these plants can be an interesting, and beautiful, addition to your landscaping plan.</p>
</div>
<div id="weeds" class="col-sm-12">
<h3>Weeds and Seeds: A History of Dining in Southern Florida </h3>
<p>This lecture examines various plants utilized by early Floridians as well as some of the ‘meatier’ issues of early diet in South Florida. Learn how the wealth of natural resources in southern Florida has made it a unique dining experience for over 10,000 years.</p>
</div>
<div id="newriver" class="col-sm-12">
<h3>History and Prehistory of the New River</h3>
<p>The New River is an important landmark in the history and prehistory of the Fort Lauderdale area. In this talk we will explore the ways that the river shaped the lives of its caretakers for over 2000 years.</p>
</div>
<div id="everglades" class="col-sm-12">
<h3>Who Made the Everglades? </h3>
<p>This talk will explore the geological and cultural history of the Everglades. In particular, we will look at the role of early Native Americans and initial tree island formations.</p>
</div>
<div id="whatarch" class="col-sm-12">
<h3>What the Heck is Archaeology</h3>
<p>Join us for a quick and dirty introduction into archaeology! This fun talk is perfect for those who want to learn what it’s like to work as an archaeologist. We take a look at the basics of fieldwork and hear about the interesting clues that archaeologists have dug up about Florida’s past.</p>
</div>
<div id="hiddenhistory" class="col-sm-12">
<h3>Hidden History of the Dry Tortugas: Writings on the Walls</h3>
<p>Although much of the military and architectural history of Fort Jefferson is well-documented, there are some interesting details that have not been studied. Historic visitors have left messages on the walls of the Fort using a variety of materials. These inscriptions span the first few decades of the 20th century, a time when the fort was not being officially utilized. This graffiti represents the only records of the Fort being used during periods of its abandonment.</p>
</div>
<div id="art" class="col-sm-12">
<h3>Art and Artifacts</h3>
<p>The disciplines of art history and archaeology tend to be compartmentalized. While, on the one hand, an object found in an archaeological context adds data to the record of human behavior, but it also exists as an object of artistic importance (and often, as you’ll see, with a high level of craftsmanship). Artifact, art, or both? Objects from Florida’s past are used to demonstrate this interesting duality.</p>
</div>
<div id="iceage" class="col-sm-12">
<h3>Florida’s Ice Age</h3>
<p>With a cooler climate and roaming mastodons, Florida used to be much different place 10,000 years ago. Learn about how Florida’s first people survived and thrived in this environment by counting on a paleo-diet (before it was all the rage).</p>
</div>
<div id="civwar" class="col-sm-12">
<h3>More than a Trifling Affair: The Archaeology of the Civil War in Southwest Florida</h3>
<p>Learn about Florida’s vital role in the Civil War. How did a national struggle play out in our local communities? What was life like for those at home? What archaeological evidence of this tumultuous time was left and how did it shape southwest Florida as we know it today?</p>
</div>
<div id="curious" class="col-sm-12">
<h3>The Curious Archaeology of Spanish Explorers in Florida</h3>
<p>We’ve all heard the tales: Leon’s ingenious discovery, Navaez’s tragic expedition, De Soto’s monumental trek towards the southeast. We have old Spanish documents recounting their feats- but can their stories hold up to the archaeological facts? Come and learn about what previous field work has told us about the first Spanish visitors to Florida and how current, cutting-edge archaeology is changing the story.</p>
</div>
<div id="cemeteries" class="col-sm-12">
<h3>As You Are Now, So Once Was I: Decoding Florida’s Cemeteries</h3>
<p>Florida’s cemeteries are not as quiet as one might think. Instead, these burial places are rich with hidden symbols, public proclamations, and old, sometimes odd, traditions. From public playgrounds to austere resting places to high-tech memory storage, studies of cemeteries can bring to life families, communities, and cultures long after they’ve left Florida far behind.</p>
</div>
<div id="booze" class="col-sm-12">
<h3>Pay no attention to the man behind the boat!: The Archaeology of Booze and Beverages</h3>
<p>Before supermarkets and vending machines, how did the residents of southwest Florida get their beverages? How did this all change on January 16, 1919 with the passing of the 21st amendment? Listen to the evidence archaeologists and historians have for the role Florida’s maritime heritage played in keeping the good times rolling.</p>
</div>
<div id="deep" class="col-sm-12">
<h3>Dispatches from the Deep: The Archaeology of Florida’s Spanish Shipwrecks</h3>
<p>Spanish ships have been navigating Florida’s waters for more than 500 years. This talk will highlight the evidence underwater archaeologists have uncovered over the years about failed colonies, far-ranging trade networks, and doomed fleets. See the evidence and learn how you can visit these unique Florida resources.</p>
</div>
</div><!-- /.box /.row -->
</div>
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Programs";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Historical & Archaeological Resources Training (HART)</h1></th>
</tr>
<tr>
<td><p class="center">
<img src="images/hart.jpg" class="padded" alt="Historical Archaeological Resources Training" /></p>
<p>
Designed for county and municipal governmental administrators, land managers, and planners, this interesting and informative one-day seminar describes archaeological and historical resources, how best to manage these resources, and methods for promoting the resources for the benefit of counties, cities, and towns. Topics covered include:</p>
<p>
<ul>
<li>cultural resource management</li>
<li>archaeological and historic preservation law</li>
<li>the role of the Florida Division of Historical Resources</li>
<li>DHR compliance review process</li>
<li>nominating sites to the National Register and designating as a State Archaeological Landmark</li>
<li>funding opportunities</li>
<li>incorporating and promoting public access to historic sites and structures</li>
<li>best management practices for cultural sites</li>
<li>economic impacts of historic preservation </li>
<li>local organizations that can assist you</li>
</ul>
</p>
<p><em>Taught in partnership with the Florida Bureau of Archaeological Research.</em></p>
<hr/>
<p>
<h4> <a href="http://www.flpublicarchaeology.org/programs/">< Go Back to Program List</a></h4>
</p>
</td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?><file_sep><?php
$pageTitle = "Links";
include 'header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Links</h1></th>
</tr>
<tr>
<td class="table_mid"><p><strong class="color">Archaeological Ordinances: </strong></p>
<p><a href="documents/ClayCounty.pdf">Clay County </a><br />
<a href="documents/NewSmyrna.pdf">New Smyrna</a><br />
<a href="documents/PonceInlet.pdf">Ponce Inlet</a><br />
<a href="documents/St.Augustine.pdf">St. Augustine </a><br />
<a href="documents/St.JohnsCounty.pdf">St. Johns County </a><br />
<a href="documents/VolusiaCounty.pdf">Volusia</a><br />
<a href="documents/BlankOrdinance.pdf">Blank Ordinance </a>
</p>
<p><strong class="color">Follow us! </strong></p>
<p>FPAN on Twitter: <a href="http://twitter.com/FPANNortheast">http://twitter.com/FPANNortheast</a><br />
FPAN on facebook: <a href="http://www.facebook.com/FPANnortheast">http://www.facebook.com/FPANnortheast</a></p>
</p>
<p>
<strong class="color">Sites of General Interest: </strong><br />
<a href="http://www.archaeology.org">Archaeology Magazine</a><br/>
<a href="http://www.flheritage.com/archaeology/">Division of Historical Resources</a><a href="http://www.flmnh.ufl.edu/histarch/"><br />
Florida Museum of Natural History</a><br />
<a href="http://www.museumsinthesea.com">Florida's "Museums in the Sea"</a><br />
<a href="http://www.nps.gov/history/goldcres/">Golden Crescent</a><br />
<a href="http://www.nps.gov/timu/historyculture/kp.htm">Kingsley Plantation</a><br />
<a href="http://www.nps.gov/timu/historyculture/index.htm">Timucuan Ecological and Historic Preserve and Fort Caroline National Memorial</a><br />
</p>
<p><strong class="color">Resources for Teachers: </strong><br />
<a href="http://www.nps.gov/cana/">Canaveral National Seashore</a><br />
<a href="http://www.nps.gov/casa/">Castillo de San Marcos</a><br />
<a href="http://www.nps.gov/foma/">Fort Matanzas</a><br />
<a href="http://www.nps.gov/timu/historyculture/kp.htm">Kingsley Plantation</a><br />
<a href="http://www.saa.org/public/home/home.html">Society for American Archaeology</a><br />
<a href="http://www.sha.org/EHA/secondary/teachers.cfm">Society for Historical Archaeology</a></p>
<p><strong class="color">Lesson Plans:</strong><br />
<a href="http://coquinaqueries.org/">Coquina Queries</a><br />
<a href="http://www.flpublicarchaeology.org/nerc/timucuan/">Timucuan Technology</a></p>
<p><strong class="color">Organizations:</strong><br />
<a href="http://www.fasweb.org/">Florida Anthropological Society</a><br />
<a href="http://www.flarchcouncil.org/">Florida Archaeological Council</a><br />
<a href="http://www.flamuseums.org/">Florida Association of Museums</a><br />
<a href="http://www.floridatrust.org/">Florida Trust</a><br />
<a href="http://www.saa.org/">Society for American Archaeology</a><br />
<a href="http://www.sha.org/">Society for Historical Archaeology</a><br />
<a href="http://www.saaa.shutterfly.com">St. Augustine Archaeological Association</a><br />
<a href="http://www.tolomatocemetery.com/">Tolomato Cemetery Preservation Association</a><br />
<a href="http://www.fasweb.org/chapters/volusia.htm">Volusia Anthropological Society</a></p></td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
include("../dbConnect.php");
$upcomingEvents = mysql_query("SELECT * FROM nwrc
WHERE nwrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM nerc
WHERE nerc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM ncrc
WHERE ncrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM wcrc
WHERE wcrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM crc
WHERE crc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM ecrc
WHERE ecrc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM serc
WHERE serc.eventDateTimeStart >= CURDATE()
UNION ALL
SELECT * FROM swrc
WHERE swrc.eventDateTimeStart >= CURDATE()
ORDER BY 2,3;");
@date_default_timezone_set("GMT");
$xml = new XMLWriter();
$xml->openURI('php://output');
$xml->openMemory();
$xml->startDocument('1.0','UTF-8');
$xml->setIndent(4);
//Start Root element
$xml->startElement('events');
if(mysql_num_rows($upcomingEvents) != 0 )
while($event = mysql_fetch_array($upcomingEvents))
{
//Start Event Element
$xml->startElement('event');
$xml->writeElement('eventID', $event['eventID']);
$xml->writeElement('region', $event['region']);
$xml->writeElement('eventDateTimeStart',$event['eventDateTimeStart']);
$xml->writeElement('eventDateTimeEnd', $event['eventDateTimeEnd']);
$xml->writeElement('title', stripslashes($event['title']));
$xml->writeElement('location', stripslashes($event['location']));
$xml->writeElement('description', html_entity_decode(stripslashes($event['description'])));
$xml->writeElement('relation', $event['relation']);
$xml->writeElement('link', $event['link']);
$xml->writeElement('flyerLink', $event['flyerLink']);
//End Event Element
$xml->endElement();
}
//End Root Element
$xml->endElement();
$xml->endDocument();
echo $xml->outputMemory();
?><file_sep><?php
$_SESSION['excludeKeys'] = array('id', 'month', 'day', 'year', 'endMonth', 'endDay', 'endYear', 'staffInvolved', 'submit', 'submit_id', 'confirmSubmission', 'countdown');
/*************************************************************************************************************************************************/
/************************************************************ FPAN Activity Form Functions ******************************************************/
/*************************************************************************************************************************************************/
function setupEdit($id, $table){
$_SESSION['edit'] = true;
$_SESSION['editID'] = $id;
$_SESSION['oldStaffInvolved'] = array();
//Get event info from database
$sql = "SELECT * FROM $table WHERE id = '$_SESSION[editID]';";
$results = mysql_query($sql);
//Set form variables
if(mysql_num_rows($results) != 0)
$formVars = mysql_fetch_assoc($results);
//Set form date variables
$dateString = strtotime($formVars['activityDate']);
$formVars['month'] = date("m", $dateString);
$formVars['day'] = date("d", $dateString);
$formVars['year'] = date("Y", $dateString);
if($formVars['endDate']){
$endDateString = strtotime($formVars['endDate']);
$formVars['endMonth'] = date("m", $dateString);
$formVars['endDay'] = date("d", $dateString);
$formVars['endYear'] = date("Y", $dateString);
}
//Get staffInvolved array from EmployeeActivity table, also store in a second array for comparison after edits
$sql = "SELECT employeeID FROM EmployeeActivity
WHERE activityID = '$_SESSION[editID]'";
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results)){
$formVars['staffInvolved'][] = $row['employeeID'];
$_SESSION['oldStaffInvolved'][] = $row['employeeID'];
}
$_SESSION['formVars'] = $formVars;
//Strip slashes from stored values
foreach($formVars as $var){
//...except for array values
if(!is_array($var))
stripslashes($var);
}
}
//Take $_POST variables from form submission, display to user and ask for confirmation
function firstSubmit($postVars){
// Sanitize Data from form
foreach($postVars as $key => $value){
if($key != "staffInvolved"){
$newValue = mysql_real_escape_string($value);
$postVars[$key] = $newValue;
}
}
//Store POST form variables in local array, convert date to one variable
$formVars = array();
if($postVars['day']){
$formVars['activityDate'] = $postVars['year'] ."-". $postVars['month'] ."-". $postVars['day'];
if($postVars['endDay'])
$formVars['endDate'] = $postVars['endYear'] ."-". $postVars['endMonth'] ."-". $postVars['endDay'];
}
else{
$formVars['activityDate'] = $postVars['year'] ."-". $postVars['month'] ."-01";
if($postVars['endDay'])
$formVars['endDate'] = $postVars['endYear'] ."-". $postVars['endMonth'] ."-01";
}
$formVars = array_merge($formVars,$postVars);
//Store in session variable
$_SESSION['formVars'] = $formVars;
//Before inserting into database, display entered data so user can check for correctness
echo "<div class=\"summary\">";
echo "<div style=\"text-align:left; margin-left:100px;\">";
//Loop formVars array and print key and value of each element
foreach($formVars as $key => $value){
if(!in_array($key, $_SESSION['excludeKeys'])){
$varName = ucfirst($key);
$varName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $varName);
echo "<strong>".$varName.": </strong>".$value."<br/>";
}
}
//Display staff involved, if there were any
if($formVars['staffInvolved']){
$sql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($sql);
echo "<strong>The staff involved:</strong> <br/>";
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName']." ".$employee['lastName'];
if(in_array($employee['id'], $formVars['staffInvolved']))
echo "<span style=\"margin-left:10px;\">". $employeeName."</span><br/>";
}
}
echo "</div>";
//Ask for confirmation
echo "<br/><br/>If any of this is incorrect, please <a href=\"".$_SERVER['PHP_SELF']."\"> go back and correct it</a>. <br/><br/>";
echo "Otherwise, please confirm your submission: <br/><br/>";
echo "<form id=\"submissionForm\" method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">";
echo "<input type=\"hidden\" name=\"confirmSubmission\" value=\"true\" />";
echo "<input type=\"submit\" name=\"submit\" value=\"Confirm\" />";
echo "</form><br/><br/>";
echo "</div>";
}
function confirmSubmit($table){
$formVars = array();
$formVars = $_SESSION['formVars'];
//******************************************* This is a NEW activity *******************************************
if(!$_SESSION['edit']){
//Insert new Activity ID
$sql = "INSERT INTO Activity VALUES (NULL);";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
//For each staff member checked, insert entry into EmployeeActivity to associate that employee with this activity
foreach($formVars['staffInvolved'] as $employeeID){
$sql = "INSERT INTO EmployeeActivity VALUES ($employeeID, LAST_INSERT_ID());";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
}
//Remove any formVars not going into the database
foreach($formVars as $key => $value)
if(in_array($key, $_SESSION['excludeKeys']))
unset($formVars[$key]);
//Make arrays of just keys and just values
//$formKeys = array_keys($formVars);
//$formValues = array_values($formVars);
//Generate SQL from form variables
$sql = "INSERT INTO $table (id, submit_id, ";
foreach($formVars as $key => $value){
if($value != "")
$sql .= $key.", ";
}
$sql .= ") ";
$sql .= "VALUES (LAST_INSERT_ID(), '$_SESSION[my_id]', ";
foreach($formVars as $key => $value){
if($value != "")
$sql .= "'".$value."', ";
}
$sql .= ");";
//Remove extra comma and space from last element
$sql = str_replace(", )", ")", $sql);
//echo $sql;
//Run query
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
if($err != true)
$msg = "Activity was successfully logged!";
//******************************************* This is an activity edit *******************************************
}else{
//Compare old staff involved array to new one. Delete any entries not in new array.
foreach($_SESSION['oldStaffInvolved'] as $employeeID){
if(!in_array($employeeID, $formVars['staffInvolved'])){
$sql = "DELETE FROM EmployeeActivity WHERE employeeID = '$employeeID' AND activityID = '$_SESSION[editID]'";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
}
}
//Compare new staff involved array to old one. Add any staff not in the old array.
foreach($formVars['staffInvolved'] as $employeeID){
if(!in_array($employeeID, $_SESSION['oldStaffInvolved'])){
$sql = "INSERT INTO EmployeeActivity VALUES ('$employeeID', '$_SESSION[editID]');";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
}
}
//Remove any formVars not going into the database
foreach($formVars as $key => $value)
if(in_array($key, $_SESSION['excludeKeys']))
unset($formVars[$key]);
//Update activity info
$sql = "UPDATE $table SET ";
foreach($formVars as $key => $value){
if($value != "")
$sql .= " ".$key." = '".$value."', ";
}
$sql .= "WHERE id = '$_SESSION[editID]';";
//Remove final comma
$sql = str_replace(", WHERE", " WHERE", $sql);
//echo $sql;
if(!mysql_query($sql)){
$err = true;
$msg .= ' Error: ' . mysql_error()."<br/>";
}
if($err != true)
$msg = "Activity was successfully edited!";
}
//If there were no erorrs while inserting or updating: Clear temporary event array, reset editing flag, display success message
if($err != true){
$_SESSION['formVars'] = "";
$_SESSION['edit'] = false;
$_SESSION['editID'] = 0;
$_SESSION['oldStaffInvolved'] = "";
}
$formName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $table);
echo "<div class=\"summary\">";
echo "<br/><br/><h3>".$msg."</h3><br/><br/><br/><br/>";
echo "<a href=\"". $_SERVER['PHP_SELF']."\">Enter another".$formName." activity</a>";
echo " or <a href=\"main.php\">return to main menu</a>. <br/><br/>";
echo "</div>";
}
/*************************************************************************************************************************************************/
/************************************************************ Professional Service Form Functions ***********************************************/
/*************************************************************************************************************************************************/
//Get form values from database to display via form
function setupServiceEdit($id, $table){
$_SESSION['edit'] = true;
$_SESSION['editID'] = $id;
//Get event info from database
$sql = "SELECT * FROM $table WHERE id = '$_SESSION[editID]';";
$results = mysql_query($sql);
//Set form variables
if(mysql_num_rows($results) != 0)
$formVars = mysql_fetch_assoc($results);
//Set form date variables
$dateString = strtotime($formVars['serviceDate']);
$formVars['month'] = date("m", $dateString);
$formVars['year'] = date("Y", $dateString);
$_SESSION['formVars'] = $formVars;
foreach($formVars as $var)
stripslashes($var);
}
//Take $_POST variables from form submission, display to user and ask for confirmation
function firstServiceSubmit($postVars){
// Sanitize Data from form
foreach($postVars as $key => $value){
$newValue = mysql_real_escape_string($value);
$postVars[$key] = $newValue;
}
//Store POST form variables in local array, convert date to one variable
$formVars = array();
$formVars['serviceDate'] = $postVars['year'] ."-". $postVars['month']; //."-01";
$formVars = array_merge($formVars,$postVars);
//Store in session variable
$_SESSION['formVars'] = $formVars;
//Before inserting into database, display entered data so user can check for correctness
echo "<div class=\"summary\">";
echo "<div style=\"text-align:left; margin-left:100px;\">";
//Loop formVars array and print key and value of each element
foreach($formVars as $key => $value){
if(!in_array($key, $_SESSION['excludeKeys'])){
//Display service date with full month title
if($key == "serviceDate"){
$timestamp = strtotime($value);
$value = date("F, Y", $timestamp);
}
$varName = ucfirst($key);
$varName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $varName);
echo "<strong>".$varName.": </strong>".$value."<br/>";
}
}
//Display staff involved, if there were any
echo "<strong>The staff involved: </strong>".$_SESSION['my_name'];
echo "<br/>";
echo "</div>";
//Ask for confirmation
echo "<br/><br/>If any of this is incorrect, please <a href=\"".$_SERVER['PHP_SELF']."\"> go back and correct it</a>. <br/><br/>";
echo "Otherwise, please confirm your submission: <br/><br/>";
echo "<form id=\"submissionForm\" method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">";
echo "<input type=\"hidden\" name=\"confirmSubmission\" value=\"true\" />";
echo "<input type=\"submit\" name=\"submit\" value=\"Confirm\" />";
echo "</form><br/><br/>";
echo "</div>";
}
function confirmServiceSubmit($table){
$formVars = array();
$formVars = $_SESSION['formVars'];
$formVars['serviceDate'] .= "-01";
//******************************************* This is a NEW activity *******************************************
if(!$_SESSION['edit']){
//Insert new Activity ID
$sql = "INSERT INTO Activity VALUES (NULL);";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
//Insert entry into EmployeeActivity to associate logged-in employee with this activity
$sql = "INSERT INTO EmployeeActivity VALUES ('$_SESSION[my_id]', LAST_INSERT_ID());";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
//Remove any formVars not going into the database
foreach($formVars as $key => $value)
if(in_array($key, $_SESSION['excludeKeys']))
unset($formVars[$key]);
//Generate SQL from form variables
$sql = "INSERT INTO $table (id, submit_id, ";
foreach($formVars as $key => $value){
if($value != "")
$sql .= $key.", ";
}
$sql .= ") ";
$sql .= "VALUES (LAST_INSERT_ID(), '$_SESSION[my_id]', ";
foreach($formVars as $key => $value){
if($value != "")
$sql .= "'".$value."', ";
}
$sql .= ");";
//Remove extra comma and space from last element
$sql = str_replace(", )", ")", $sql);
//echo $sql;
//Run query
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error()."<br/>";
}
if($err != true)
$msg = "Activity was successfully logged!";
//******************************************* This is an activity edit *******************************************
}else{
//Remove any formVars not going into the database
foreach($formVars as $key => $value)
if(in_array($key, $_SESSION['excludeKeys']))
unset($formVars[$key]);
//Update event info
$sql = "UPDATE $table SET ";
foreach($formVars as $key => $value){
if($value != "")
$sql .= " ".$key." = '".$value."', ";
}
$sql .= "WHERE id = '$_SESSION[editID]';";
//Remove final comma
$sql = str_replace(", WHERE", " WHERE", $sql);
//echo $sql;
if(!mysql_query($sql)){
$err = true;
$msg .= ' Error: ' . mysql_error()."<br/>";
}
if($err != true)
$msg = "Activity was successfully edited!";
}
//If there were no erorrs while inserting or updating: Clear temporary event array, reset editing flag, display success message
if($err != true){
$_SESSION['formVars'] = "";
$_SESSION['edit'] = false;
$_SESSION['editID'] = 0;
}
$formName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $table);
echo "<div class=\"summary\">";
echo "<br/><br/><h3>".$msg."</h3><br/><br/><br/><br/>";
echo "<a href=\"". $_SERVER['PHP_SELF']."\">Enter another".$formName." activity</a>";
echo " or <a href=\"main.php\">return to main menu</a>. <br/><br/>";
echo "</div>";
}
?><file_sep><?php
$pageTitle = "Volunteer";
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="box-tab">
<div class="text-center">
<div class="image center-block" style="max-width:400px;">
<img src="images/volunteer.jpg" alt="" class="img-responsive" >
<p> Volunteers assist with taking measurements of an anchor in Apalachicola.</p>
</div>
</div>
<p>The North Central Regional FPAN Center is always looking for a few reliable volunteers to assist in the
office and/or help with public outreach events.</p>
<p>Office volunteers will be asked to assist with tasks such as completing the quarterly newsletter, updating
Facebook and Twitter, writing blogs, helping with event planning and assisting with other similar tasks.
An interest in and some basic knowledge of archaeology and /or history would be helpful, as would
basic computer skills. Creativity and the ability to work independently are also a plus. Any necessary
training can be provided and FPAN staff will be available to provide direction to volunteers.
If you are interested in assisting with public outreach events (such as festival booths, tours, special
events, etc) you must have a willingness to interact with the public in a respectful and positive way. An
interest in and some basic knowledge of archaeology and/or history would be very helpful, as would
the ability to speak to large groups. The ability to interact with children is also a plus, as is creativity
and reliability. Many of these types of events take place on the weekends, so please take that into
consideration. </p>
<p>If you are interested in learning more about these volunteer opportunities, please contact us at
<a href="mailto:<EMAIL>"><EMAIL></a>.</p>
</div><!-- /.box-tab -->
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div>
</div> <!-- /.row -->
</div> <!-- /.container -->
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Virtual Tours - Arcadia Mill";
include '../../admin/dbConnect.php';
include '../header.php';
$flashvars = "file=http://www.flpublicarchaeology.org/resources/videos/destinationArchaeologyTour.flv&screencolor=000000";
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0" >
<tr>
<th class="lg_header"><h1>Virtual Tours</h1></th>
</tr>
<tr>
<td class="lg_mid" style="vertical-align:top">
<h2 align="center">Arcadia Mill Archaeological Site</h2>
<p align="center">American Territorial Period (1821-1845) - Early Statehood & Antebellum Period (1845-
1860)</p>
<br/>
<img src="images/arcadiasign.jpg" style="display:block; margin:0 auto 1em auto"/>
<h3>Milton, Santa Rosa County</h3>
<p>The Arcadia Mill Archaeological Site represents the largest 19th-century water-powered industrial complex in Northwest Florida. Between 1817 and 1855 this was the site of a multi-faceted operation that included a sawmill, lumber mill, grist mill, shingle mill, and cotton textile mill. Additional buildings rounded out this complex, including housing for enslaved female workers, a kitchen, storehouse, blacksmith shop, and community well. Arcadia Mill offers the visitor an historical experience as well as the opportunity to visit a unique wetland ecosystem. Today the site is open to the public and managed by the UWF Historic Trust. It includes a visitor center, museum, and outdoor exhibits. Free guided tours are available. </p>
<img src="images/arcadiaboardwalk.jpg" style="display:block; margin:0 auto 1em auto"/>
<p>
<h3>DID YOU KNOW...</h3>
</p>
<ul>
<li>The University of West Florida Department of Anthropology and Archaeology Institute holds field schools at the site every summer. </li>
<li>Elevated board walk with interpretive waysides leads visitors through the archaeological remains of the mills, across Pond Creek, and through adjacent swamps.</li>
<li>Historical newspapers indicate that in 1840 forty female slaves were purchased from Virginia to work in the textile mill. By 1850 African American men and children lived and worked at the site.</li>
</ul>
<img src="images/arcadiainside.jpg" style="display:block; margin:0 auto 1em auto"/>
<h4 align="center"><a href="http://www.historicpensacola.org/arcadia.cfm" target="_blank">Arcadia Mill Homepage</a></h4>
<p align="center">5709 Mill Pond Lane in Milton, Florida.</p>
</td>
</tr>
</table>
<? include '../calendar.php'; ?>
<? include '../eventsBox.php'; ?>
<div class="clearFloat"></div>
</div>
<?php include '../footer.php'; ?><file_sep><?php
include 'header.php';
$link = mysql_connect('fpanweb.powwebmysql.com', 'fam_user', ')OKM9ijn');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(fam_events);
//Assign date from URL and apply SQL injection protection!
$thisDate = $_GET["eventDate"];
$eventID = $_GET["eventID"];
$formatDate = new DateTime($thisDate);
$displayDate = $formatDate->format('l, M j, Y');
if($eventID != null)
$events = "SELECT * FROM $table WHERE eventID = '" . mysql_real_escape_string($eventID) . "';";
else
$events = "SELECT * FROM $table WHERE eventDateTimeStart LIKE '" . mysql_real_escape_string($thisDate) . "%' ORDER BY eventDateTimeStart ASC;";
$query = mysql_query($events);
function prefix_protocol($url, $prefix = 'http://')
{
if (!preg_match("~^(?:f|ht)tps?://~i", $url))
{
$url = $prefix . $url;
}
return $url;
}
?>
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<td class="lg_mid">
<h1 align="center"><?php echo $displayDate; ?></h1>
<div style="margin-left:20px; margin-right:20px;">
<?php
$num_events = 0;
while($event = mysql_fetch_array($query))
{
echo "<br/><img src=\"images/hrLine.png\"/><br/><br/>";
$timestampStart = strtotime($event['eventDateTimeStart']);
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventTimeStart = date('g:i a', $timestampStart);
$eventTimeEnd = date('g:i a', $timestampEnd);
echo "<h2>".stripslashes($event['eventTitle']). "</h2>";
echo "<p><strong>Time: </strong><em>".$eventTimeStart;
if($event['eventDateTimeEnd'] != "0000-00-00 00:00:00")
echo " til " .$eventTimeEnd;
echo "</em></p>";
echo "<p><strong>Location: </strong><em> " .stripslashes($event['eventLocation']). "</em></p>";
echo "<p><strong>Address: </strong><em> " .stripslashes($event['eventAddress']). ", " .$event['eventCity'];
echo "</em></p>";
echo "<p><strong>Description:</strong><em> " .nl2br(strip_tags(stripslashes($event['eventDescription']))). " </em></p>";
if($event['eventURL'] != null){
echo '<p><strong>Related link:</strong> <a href="'.prefix_protocol($event['eventURL']).'"> Click Here!</a></p>';
}
echo "<p><strong>Contact: </strong>".stripslashes($event['contactName']).
" - <a href=\"mailto:".stripslashes($event['contactEmail'])."\">".stripslashes($event['contactEmail'])."</a>";
echo " - ".$event['contactPhone']."</p>";
$num_events+=1;
}
?>
</div>
</td>
</tr>
</table>
<?php
include 'calendar.php';
echo "<br/>";
include 'eventsBox.php';
?>
<div class="clearFloat"></div>
</div>
<?php include 'footer.php'; ?><file_sep><?php
include 'header.php';
$table = 'TrainingCertificationEducation';
//if this is a new event, clear any potential leftover form data
if($_GET['new'])
$_SESSION['formVars'] = "";
//If event ID is supplied in URL, this event is being edited. Gather info from database and populate form.
if($_GET['id']){
setupServiceEdit($_GET['id'], $table);
}
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true){
confirmServiceSubmit($table);
}
//Form has been submitted but not confirmed. Display input values to check for accuracy
if(isset($_POST['submit'])&&!isset($_POST['confirmSubmission'])){
firstServiceSubmit($_POST);
}elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="trainingCertificationEducation" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Training, Certification and Education</h2>
<p>Use this form to log any training, certification or education completed by your <strong>self</strong> only.
<br/> This activity will be attributed to the individual currently logged in.</p>
</div>
<ul>
<li id="li_1" >
<label class="description" for="element_1">Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text" required="required">
/
<label for="element_1_1">MM</label>
</span><span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text" required="required"><a class="red"> *</a>
<label for="element_1_3">YYYY</label>
</span></li>
<li id="li_3" >
<label class="description" for="element_3">Type </label>
<div>
<select class="element select small" id="element_3" name="typeTraining" required="required">
<option value="" selected="selected"></option>
<option <?php if($formVars['typeTraining'] == "NAI") echo 'selected="selected"'; ?> value="NAI" >NAI</option>
<option <?php if($formVars['typeTraining'] == "ARPA") echo 'selected="selected"'; ?> value="ARPA" >ARPA</option>
<option <?php if($formVars['typeTraining'] == "SCUBA") echo 'selected="selected"'; ?> value="SCUBA" >SCUBA</option>
<option <?php if($formVars['typeTraining'] == "CPR / First Aid / O2") echo 'selected="selected"'; ?> value="CPR / First Aid / O2" >CPR / First Aid / O2</option>
<option <?php if($formVars['typeTraining'] == "Master Gardener") echo 'selected="selected"'; ?> value="Master Gardener" >Master Gardener</option>
<option <?php if($formVars['typeTraining'] == "Project Archaeology") echo 'selected="selected"'; ?> value="Project Archaeology" >Project Archaeology</option>
<option <?php if($formVars['typeTraining'] == "Other") echo 'selected="selected"'; ?> value="Other" >Other</option>
</select><a class="red"> *</a>
</div>
</li>
<li id="li_2" >
<label class="description" for="element_2">Comments </label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium" onKeyDown="limitText(this.form.comments,this.form.countdown,2080);"
onKeyUp="limitText(this.form.comments,this.form.countdown,2080);"><?php echo $formVars['comments']; ?></textarea><br/>
<font size="1">(Maximum characters: 2080)<br>
You have <input readonly type="text" name="countdown" size="3" value="2080"> characters left.</font>
</div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close else ?>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "Regions of FPAN";
include('_header.php');
?>
<div class="page-content container">
<div class="row">
<div class="page-header"><h1>Regions<small> of FPAN </small> </h1></div>
<div class="box-dash box-serif col-sm-8 col-sm-push-2">
The Florida Public Archaeology Network has regional centers in 8 distinct regions of the state.
Refer to the map and list of counties below to see how the regions are defined.
</div>
<div class="box-line col-sm-12 ">
<div id="map" class="hidden-xs"></div>
<span><img src="images/fl_regions_sm.svg" class="visible-xs img-responsive"/></span>
</div>
</div>
<div class="row">
<h2 class="text-center">Counties <small>by Region</small></h2>
<div class="col-sm-6 col-md-3">
<div class="box-tab nw-tab">
<h2>Northwest</h2>
<ul>
<li>Bay</li>
<li>Calhoun</li>
<li>Escambia</li>
<li>Gulf</li>
<li>Holmes</li>
<li>Jackson</li>
<li>Okaloosa</li>
<li>Santa Rosa</li>
<li>Walton</li>
<li>Washington</li>
</ul>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region nw-btn" href="nwrc"> Northwest Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab nc-tab">
<h2>North Central</h2>
<ul>
<li>Baker</li>
<li>Columbia</li>
<li>Dixie</li>
<li>Franklin</li>
<li>Gadsden</li>
<li>Hamilton</li>
<li>Jefferson</li>
<li>Lafayette</li>
<li>Leon</li>
<li>Liberty</li>
<li>Madison</li>
<li>Suwannee</li>
<li>Taylor</li>
<li>Union</li>
<li>Wakulla</li>
</ul>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region nc-btn" href="ncrc"> North Central Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab ne-tab">
<h2>Northeast</h2>
<ul>
<li>Clay</li>
<li>Duval</li>
<li>Flagler</li>
<li>Nassau</li>
<li>Putnam</li>
<li>St. Johns</li>
<li>Volusia</li>
</ul>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region ne-btn" href="ncrc"> Northeast Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab ec-tab">
<h2>East Central</h2>
<ul>
<li>Brevard</li>
<li>Indian River</li>
<li>Martin</li>
<li>Okeechobee</li>
<li>Orange</li>
<li>Osceola</li>
<li>Seminole</li>
<li>St. Lucie</li>
</ul>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region ec-btn" href="ecrc"> East Central Region</a> website.</p>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
<div class="row">
<div class="col-sm-6 col-md-3">
<div class="box-tab c-tab">
<h2>Central</h2>
<ul>
<li>Alachua</li>
<li>Bradford</li>
<li>Citrus</li>
<li>Gilchrist</li>
<li>Hernando</li>
<li>Lake</li>
<li>Levy</li>
<li>Marion</li>
<li>Sumter</li>
</ul>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region c-btn" href="crc"> Central Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab wc-tab">
<h2>West Central</h2>
<ul>
<li>Desoto</li>
<li>Hardee</li>
<li>Highlands</li>
<li>Hillsborough</li>
<li>Manatee</li>
<li>Pasco</li>
<li>Pinellas</li>
<li>Polk</li>
<li>Sarasota</li>
</ul>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region wc-btn" href="wcrc"> West Central Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab sw-tab">
<h2>Southwest</h2>
<ul>
<li>Charlotte</li>
<li>Collier</li>
<li>Glades</li>
<li>Hendry</li>
<li>Lee</li>
</ul>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region sw-btn" href="swrc"> Southwest Region</a> website.</p>
</div>
</div><!-- /.col -->
<div class="col-sm-6 col-md-3">
<div class="box-tab se-tab">
<h2>Southeast</h2>
<ul>
<li>Broward</li>
<li>Miami-Dade</li>
<li>Monroe</li>
<li>Palm Beach</li>
</ul>
<hr/>
<p class="text-center"> Visit the <a class="btn btn-region se-btn" href="serc"> Southeast Region</a> website.</p>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content -->
<!-- Interactive SVG Map scripts -->
<script type="text/javascript" src="_js/jquery.js"></script>
<script type="text/javascript" src="_js/raphael.js"></script>
<script type="text/javascript" src="_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#map').mapSvg({
source: 'images/fl_regions.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:225},
marks:[
{ //Northwest Region Marker
xy:[64,147],
tooltip:'Northwest Regional Center & Coordinating Center',
attrs: {src:'images/pin_orange.png'}},
{ //North Central Region Marker
xy:[410,145],
tooltip:'North Central Regional Center',
attrs: {src:'images/pin_orange.png'}},
{ //Northeast Region Marker
xy:[745,215],
tooltip:'Northeast Regional Center',
attrs: {src:'images/pin_blue.png'}},
{ //East Central Region Marker
xy:[810,430],
tooltip:'East Central Regional Center',
attrs: {src:'images/pin_blue.png'}},
{ //Central Region Marker
xy:[596,360],
tooltip:'Central Regional Center',
attrs: {src:'images/pin_red.png'}},
{ //West Central Region Marker
xy:[617,456],
tooltip:'West Central Regional Center',
attrs: {src:'images/pin_red.png'}},
{ //Southeast Region Marker
xy:[883,710],
tooltip:'Southeast Regional Center',
attrs: {src:'images/pin_yellow.png'}},
{ //Southwest Region Marker
xy:[683,643],
tooltip:'Southwest Regional Center',
attrs: {src:'images/pin_yellow.png'}},
],
regions:{
'Escambia' :{popover:'<h3>Escambia</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=escambia">Explore Escambia County</a></p>'},
'Santa_Rosa' :{popover:'<h3>Santa Rosa</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=santarosa">Explore Santa Rosa County</a></p>'},
'Okaloosa' :{popover:'<h3>Okaloosa</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=okaloosa">Explore Okaloosa County</a></p>'},
'Walton' :{popover:'<h3>Walton</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=walton">Explore Walton County</a></p>'},
'Holmes' :{popover:'<h3>Holmes</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=holmes">Explore Holmes County</a></p>'},
'Washington' :{popover:'<h3>Washington</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=washington">Explore Washington County</a></p>'},
'Bay' :{popover:'<h3>Bay</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=bay">Explore Bay County</a></p>'},
'Gulf' :{popover:'<h3>Gulf</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=gulf">Explore Gulf County</a></p>'},
'Jackson' :{popover:'<h3>Jackson</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=jackson"> Explore Jackson County</a></p>'},
'Calhoun' :{popover:'<h3>Calhoun</h3><p class="text-center">Visit the<br/><a href="/nwrc" class="btn btn-region nw-btn">Northwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=calhoun"> Explore Calhoun County</a></p>'},
'Gadsden' :{popover:'<h3>Gadsden</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=gadsden"> Explore Gadsden County</a></p>'},
'Leon' :{popover:'<h3>Leon</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=leon"> Explore Leon County</a></p>'},
'Liberty' :{popover:'<h3>Liberty</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=liberty"> Explore Liberty County</a></p>'},
'Franklin' :{popover:'<h3>Franklin</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=franklin"> Explore Franklin County</a></p>'},
'Wakulla' :{popover:'<h3>Wakulla</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=wakulla"> Explore Wakulla County</a></p>'},
'Jefferson' :{popover:'<h3>Jefferson</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=jefferson"> Explore Jefferson County</a></p>'},
'Madison' :{popover:'<h3>Madison</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=madison"> Explore Madison County</a></p>'},
'Taylor' :{popover:'<h3>Taylor</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=taylor"> Explore Taylor County</a></p>'},
'Hamilton' :{popover:'<h3>Hamilton</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=hamilton"> Explore Hamilton County</a></p>'},
'Suwannee' :{popover:'<h3>Suwannee</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=suwannee"> Explore Suwannee County</a></p>'},
'Lafayette' :{popover:'<h3>Lafayette</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=lafayette"> Explore Lafayette County</a></p>'},
'Dixie' :{popover:'<h3>Dixie</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=dixie"> Explore Dixie County</a></p>'},
'Columbia' :{popover:'<h3>Columbia</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=columbia"> Explore Columbie County</a></p>'},
'Baker' :{popover:'<h3>Baker</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=baker"> Explore Baker County</a></p>'},
'Union' :{popover:'<h3>Union</h3><p class="text-center">Visit the<br/><a href="/ncrc" class="btn btn-region nc-btn">North Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ncrc/explore.php?county=union"> Explore Union County</a></p>'},
'Nassau' :{popover:'<h3>Nassau</h3><p class="text-center">Visit the<br/><a href="/nerc" class="btn btn-region ne-btn">Northeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=nassau"> Explore Nassau County</a></p>'},
'Duval' :{popover:'<h3>Duval</h3><p class="text-center">Visit the<br/><a href="/nerc" class="btn btn-region ne-btn">Northeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=duval"> Explore Duval County</a></p>'},
'Clay' :{popover:'<h3>Clay</h3><p class="text-center">Visit the<br/><a href="/nerc" class="btn btn-region ne-btn">Northeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=clay"> Explore Clay County</a></p>'},
'Putnam' :{popover:'<h3>Putnam</h3><p class="text-center">Visit the<br/><a href="/nerc" class="btn btn-region ne-btn">Northeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=putnam"> Explore Putnam County</a></p>'},
'St._Johns' :{popover:'<h3>St. Johns</h3><p class="text-center">Visit the<br/><a href="/nerc" class="btn btn-region ne-btn">Northeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=stjohns"> Explore St. Johns County</a></p>'},
'Flagler' :{popover:'<h3>Flagler</h3><p class="text-center">Visit the<br/><a href="/nerc" class="btn btn-region ne-btn">Northeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=flagler"> Explore Flagler County</a></p>'},
'Volusia' :{popover:'<h3>Volusia</h3><p class="text-center">Visit the<br/><a href="/nerc" class="btn btn-region ne-btn">Northeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/nerc/explore.php?county=volusia"> Explore Volusia County</a></p>'},
'Seminole' :{popover:'<h3>Seminole</h3><p class="text-center">Visit the<br/><a href="/ecrc" class="btn btn-region ec-btn">East Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=seminole"> Explore Seminole County</a></p>'},
'Brevard' :{popover:'<h3>Brevard</h3><p class="text-center">Visit the<br/><a href="/ecrc" class="btn btn-region ec-btn">East Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=brevard"> Explore Brevard County</a></p>'},
'Indian_River' :{popover:'<h3>Indian River</h3><p class="text-center">Visit the<br/><a href="/ecrc" class="btn btn-region ec-btn">East Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=indianriver"> Explore Indian River County</a></p>'},
'St._Lucie' :{popover:'<h3>St. Lucie</h3><p class="text-center">Visit the<br/><a href="/ecrc" class="btn btn-region ec-btn">East Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=stlucie"> Explore St. Lucie County</a></p>'},
'Martin' :{popover:'<h3>Martin</h3><p class="text-center">Visit the<br/><a href="/ecrc" class="btn btn-region ec-btn">East Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=martin"> Explore Martin County</a></p>'},
'Okeechobee' :{popover:'<h3>Okeechobee</h3><p class="text-center">Visit the<br/><a href="/ecrc" class="btn btn-region ec-btn">East Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=okeechobee"> Explore Okeechobee County</a></p>'},
'Orange' :{popover:'<h3>Orange</h3><p class="text-center">Visit the<br/><a href="/ecrc" class="btn btn-region ec-btn">East Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=orange"> Explore Orange County</a></p>'},
'Osceola' :{popover:'<h3>Osceola</h3><p class="text-center">Visit the<br/><a href="/ecrc" class="btn btn-region ec-btn">East Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/ecrc/explore.php?county=osceola"> Explore Osceola County</a></p>'},
'Bradford' :{popover:'<h3>Bradford</h3><p class="text-center">Visit the<br/><a href="/crc" class="btn btn-region c-btn">Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=bradford"> Explore Bradford County</a></p>'},
'Alachua' :{popover:'<h3>Alachua</h3><p class="text-center">Visit the<br/><a href="/crc" class="btn btn-region c-btn">Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=alachua"> Explore Alachua County</a></p>'},
'Gilchrist' :{popover:'<h3>Gilchrist</h3><p class="text-center">Visit the<br/><a href="/crc" class="btn btn-region c-btn">Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=gilchrist"> Explore Gilchrist County</a></p>'},
'Levy' :{popover:'<h3>Levy</h3><p class="text-center">Visit the<br/><a href="/crc" class="btn btn-region c-btn">Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=levy"> Explore Levy County</a></p>'},
'Marion' :{popover:'<h3>Marion</h3><p class="text-center">Visit the<br/><a href="/crc" class="btn btn-region c-btn">Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=marion"> Explore Marion County</a></p>'},
'Lake' :{popover:'<h3>Lake</h3><p class="text-center">Visit the<br/><a href="/crc" class="btn btn-region c-btn">Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=lake"> Explore Lake County</a></p>'},
'Sumter' :{popover:'<h3>Sumter</h3><p class="text-center">Visit the<br/><a href="/crc" class="btn btn-region c-btn">Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=sumter"> Explore Sumter County</a></p>'},
'Citrus' :{popover:'<h3>Citrus</h3><p class="text-center">Visit the<br/><a href="/crc" class="btn btn-region c-btn">Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=citrus"> Explore Citrus County</a></p>'},
'Hernando' :{popover:'<h3>Hernando</h3><p class="text-center">Visit the<br/><a href="/crc" class="btn btn-region c-btn">Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/crc/explore.php?county=hernando"> Explore Hernando County</a></p>'},
'Pasco' :{popover:'<h3>Pasco</h3><p class="text-center">Visit the<br/><a href="/wcrc" class="btn btn-region wc-btn">West Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=pasco"> Explore Pasco County</a></p>'},
'Hillsborough' :{popover:'<h3>Hillsborough</h3><p class="text-center">Visit the<br/><a href="/wcrc" class="btn btn-region wc-btn">West Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=hillsborough"> Explore Hillsborough County</a></p>'},
'Pinellas' :{popover:'<h3>Pinellas</h3><p class="text-center">Visit the<br/><a href="/wcrc" class="btn btn-region wc-btn">West Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=pinellas"> Explore Pinellas County</a></p>'},
'Manatee' :{popover:'<h3>Manatee</h3><p class="text-center">Visit the<br/><a href="/wcrc" class="btn btn-region wc-btn">West Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=manatee"> Explore Manatee County</a></p>'},
'Sarasota' :{popover:'<h3>Sarasota</h3><p class="text-center">Visit the<br/><a href="/wcrc" class="btn btn-region wc-btn">West Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=sarasota"> Explore Sarasota County</a></p>'},
'Polk' :{popover:'<h3>Polk</h3><p class="text-center">Visit the<br/><a href="/wcrc" class="btn btn-region wc-btn">West Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=polk"> Explore Polk County</a></p>'},
'Hardee' :{popover:'<h3>Hardee</h3><p class="text-center">Visit the<br/><a href="/wcrc" class="btn btn-region wc-btn">West Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=hardee"> Explore Hardee County</a></p>'},
'Highlands' :{popover:'<h3>Highlands</h3><p class="text-center">Visit the<br/><a href="/wcrc" class="btn btn-region wc-btn">West Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=highlands"> Explore Highlands County</a></p>'},
'Desoto' :{popover:'<h3>Desoto</h3><p class="text-center">Visit the<br/><a href="/wcrc" class="btn btn-region wc-btn">West Central Region</a></p><p class="text-center"><a class="btn btn-primary" href="/wcrc/explore.php?county=desoto"> Explore Desoto County</a></p>'},
'Charlotte' :{popover:'<h3>Charlotte</h3><p class="text-center">Visit the<br/><a href="/swrc" class="btn btn-region sw-btn">Southwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=charlotte"> Explore Charlotte County</a></p>'},
'Glades' :{popover:'<h3>Glades</h3><p class="text-center">Visit the<br/><a href="/swrc" class="btn btn-region sw-btn">Southwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=glades"> Explore Glades County</a></p>'},
'Hendry' :{popover:'<h3>Hendry</h3><p class="text-center">Visit the<br/><a href="/swrc" class="btn btn-region sw-btn">Southwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=hendry"> Explore Hendry County</a></p>'},
'Lee' :{popover:'<h3>Lee</h3><p class="text-center">Visit the<br/><a href="/swrc" class="btn btn-region sw-btn">Southwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=lee"> Explore Lee County</a></p>'},
'Collier' :{popover:'<h3>Collier</h3><p class="text-center">Visit the<br/><a href="/swrc" class="btn btn-region sw-btn">Southwest Region</a></p><p class="text-center"><a class="btn btn-primary" href="/swrc/explore.php?county=collier"> Explore Collier County</a></p>'},
'Palm_Beach' :{popover:'<h3>Palm Beach</h3><p class="text-center">Visit the<br/><a href="/serc" class="btn btn-region se-btn">Southeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/serc/explore.php?county=palmbeach"> Explore Palm Beach County</a></p>'},
'Broward' :{popover:'<h3>Broward</h3><p class="text-center">Visit the<br/><a href="/serc" class="btn btn-region se-btn">Southeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/serc/explore.php?county=broward"> Explore Broward County</a></p>'},
'Miami-Dade' :{popover:'<h3>Miami-Dade</h3><p class="text-center">Visit the<br/><a href="/serc" class="btn btn-region se-btn">Southeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/serc/explore.php?county=miamidade"> Explore Miami-Dade County</a></p>'},
'Monroe' :{popover:'<h3>Monroe</h3><p class="text-center">Visit the<br/><a href="/serc" class="btn btn-region se-btn">Southeast Region</a></p><p class="text-center"><a class="btn btn-primary" href="/serc/explore.php?county=monroe"> Explore Monroe County</a></p>'}
}
});
</script>
<?php include('_footer.php'); ?><file_sep><?php
/**
* Initialize globals for Admin
* @package admin
*/
// force UTF-8 Ø
define('UPLOAD_ERR_QUOTA', -1);
define('UPLOAD_ERR_BLOCKED', -2);
require_once(dirname(__FILE__) . '/functions-basic.php');
zp_session_start();
require_once(SERVERPATH . '/' . ZENFOLDER . '/admin-functions.php');
httpsRedirect();
$_SESSION['adminRequest'] = @$_COOKIE['zp_user_auth']; // Allow "unprotected" i.php if the request came from an admin session
$zenphoto_tabs = array();
require_once(SERVERPATH . "/" . ZENFOLDER . '/rewrite.php');
if (OFFSET_PATH != 2 && !getOption('license_accepted')) {
require_once(dirname(__FILE__) . '/license.php');
}
$sortby = array(gettext('Filename') => 'filename',
gettext('Date') => 'date',
gettext('Title') => 'title',
gettext('ID') => 'id',
gettext('Filemtime') => 'mtime',
gettext('Owner') => 'owner',
gettext('Published') => 'show'
);
// setup sub-tab arrays for use in dropdown
if ($_zp_loggedin) {
if ($_zp_current_admin_obj->reset) {
$_zp_loggedin = USER_RIGHTS;
} else {
if ($_zp_loggedin & ADMIN_RIGHTS) {
$_zp_loggedin = ALL_RIGHTS;
} else {
if ($_zp_loggedin & MANAGE_ALL_ALBUM_RIGHTS) {
// these are lock-step linked!
$_zp_loggedin = $_zp_loggedin | ALBUM_RIGHTS;
}
if ($_zp_loggedin & MANAGE_ALL_NEWS_RIGHTS) {
// these are lock-step linked!
$_zp_loggedin = $_zp_loggedin | ZENPAGE_NEWS_RIGHTS;
}
if ($_zp_loggedin & MANAGE_ALL_PAGES_RIGHTS) {
// these are lock-step linked!
$_zp_loggedin = $_zp_loggedin | ZENPAGE_PAGES_RIGHTS;
}
}
}
if ($_zp_loggedin & OVERVIEW_RIGHTS) {
$zenphoto_tabs['overview'] = array('text' => gettext("overview"),
'link' => WEBPATH . "/" . ZENFOLDER . '/admin.php',
'subtabs' => NULL);
}
$zenphoto_tabs['upload'] = NULL;
if ($_zp_loggedin & ALBUM_RIGHTS) {
$zenphoto_tabs['edit'] = array('text' => gettext("albums"),
'link' => WEBPATH . "/" . ZENFOLDER . '/admin-edit.php',
'subtabs' => NULL);
}
if (extensionEnabled('zenpage')) {
if ($_zp_loggedin & ZENPAGE_PAGES_RIGHTS) {
$zenphoto_tabs['pages'] = array('text' => gettext("pages"),
'link' => WEBPATH . "/" . ZENFOLDER . '/' . PLUGIN_FOLDER . '/zenpage/admin-pages.php',
'subtabs' => NULL);
}
if ($_zp_loggedin & ZENPAGE_NEWS_RIGHTS) {
$zenphoto_tabs['news'] = array('text' => gettext("news"),
'link' => WEBPATH . "/" . ZENFOLDER . '/' . PLUGIN_FOLDER . '/zenpage/admin-news-articles.php',
'subtabs' => array(gettext('articles') => PLUGIN_FOLDER . '/zenpage/admin-news-articles.php?page=news&tab=articles',
gettext('categories') => PLUGIN_FOLDER . '/zenpage/admin-categories.php?page=news&tab=categories'),
'default' => 'articles');
}
}
if ($_zp_loggedin & TAGS_RIGHTS) {
$zenphoto_tabs['tags'] = array('text' => gettext("tags"),
'link' => WEBPATH . "/" . ZENFOLDER . '/admin-tags.php',
'subtabs' => NULL);
}
if ($_zp_loggedin & USER_RIGHTS) {
$zenphoto_tabs['users'] = array('text' => gettext("users"),
'link' => WEBPATH . "/" . ZENFOLDER . '/admin-users.php?page=users',
'subtabs' => NULL);
}
$subtabs = array();
$optiondefault = '';
if ($_zp_loggedin & OPTIONS_RIGHTS) {
if ($_zp_loggedin & ADMIN_RIGHTS) {
$optiondefault = '&tab=general';
$subtabs[gettext("general")] = 'admin-options.php?page=options&tab=general';
} else {
$optiondefault = '&tab=gallery';
}
$subtabs[gettext("gallery")] = 'admin-options.php?page=options&tab=gallery';
if ($_zp_loggedin & ADMIN_RIGHTS) {
$subtabs[gettext("security")] = 'admin-options.php?page=options&tab=security';
}
$subtabs[gettext("image")] = 'admin-options.php?page=options&tab=image';
}
if ($_zp_loggedin & ADMIN_RIGHTS) {
if (empty($optiondefault))
$optiondefault = '&tab=plugin';
$subtabs[gettext("plugin")] = 'admin-options.php?page=options&tab=plugin';
}
if ($_zp_loggedin & OPTIONS_RIGHTS) {
$subtabs[gettext("search")] = 'admin-options.php?page=options&tab=search';
if ($_zp_loggedin & THEMES_RIGHTS) {
if (empty($optiondefault))
$optiondefault = '&tab=theme';
$subtabs[gettext("theme")] = 'admin-options.php?page=options&tab=theme';
}
$zenphoto_tabs['options'] = array('text' => gettext("options"),
'link' => WEBPATH . "/" . ZENFOLDER . '/admin-options.php?page=options' . $optiondefault,
'subtabs' => $subtabs,
'default' => 'gallery');
}
if ($_zp_loggedin & THEMES_RIGHTS) {
$zenphoto_tabs['themes'] = array('text' => gettext("themes"),
'link' => WEBPATH . "/" . ZENFOLDER . '/admin-themes.php',
'subtabs' => NULL);
}
if ($_zp_loggedin & ADMIN_RIGHTS) {
list($subtabs, $default) = getPluginTabs();
$zenphoto_tabs['plugins'] = array('text' => gettext("plugins"),
'link' => WEBPATH . "/" . ZENFOLDER . '/admin-plugins.php',
'subtabs' => $subtabs,
'default' => $default);
}
if ($_zp_loggedin & ADMIN_RIGHTS) {
list($subtabs, $default) = getLogTabs();
$zenphoto_tabs['logs'] = array('text' => gettext("logs"),
'link' => WEBPATH . "/" . ZENFOLDER . '/admin-logs.php?page=logs',
'subtabs' => $subtabs,
'default' => $default);
}
if (!$_zp_current_admin_obj->getID()) {
$filelist = safe_glob(SERVERPATH . "/" . BACKUPFOLDER . '/*.zdb');
if (count($filelist) > 0) {
$zenphoto_tabs['restore'] = array('text' => gettext("Restore"),
'link' => WEBPATH . "/" . ZENFOLDER . '/utilities/backup_restore.php?page=backup',
'subtabs' => NULL);
}
}
$zenphoto_tabs = zp_apply_filter('admin_tabs', $zenphoto_tabs);
foreach ($zenphoto_tabs as $tab => $value) {
if (is_null($value)) {
unset($zenphoto_tabs[$tab]);
}
}
// so as to make it generally available as we make much use of it
if (OFFSET_PATH != 2) {
require_once(SERVERPATH . '/' . ZENFOLDER . '/' . PLUGIN_FOLDER . '/colorbox_js.php');
}
loadLocalOptions(false, $_zp_gallery->getCurrentTheme());
}
?>
<file_sep><?php
$pageTitle = "Prak Ranger Workshop";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Park Ranger Workshop</h1></th>
</tr>
<tr>
<td>
<p class="center"> <img src="images/rangerWorkshop2.jpg" class="padded"/> </p>
<p>Many park rangers and public land managers come from an environmental, biology, or wildlife ecology background, and yet still are required to manage cultural resources located on their property. This one-day training is designed to assist rangers and park personnel in the identification, protection, interpretation, and effective management of historical and archaeological resources. Attendees receive a workbook filled with information and additional contacts, as well as hands-on practice in filling out archaeological site forms and tips on providing interpretive information about their sites for visitors.</p>
<hr/>
<p>
<h4> <a href="http://www.flpublicarchaeology.org/programs/">< Go Back to Program List</a></h4>
</p>
</td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?><file_sep><?php
include 'appHeader.php';
//suppress notices
error_reporting(E_ALL ^ E_NOTICE);
//Connect to database
include 'dbConnect.php';
session_start();
//If user is already logged in, redirect to control panel
if(isset($_SESSION['email']) && ($_GET['logout'] != 1))
header("location:adminHome.php");
//If the form was submitted
if($_POST['submit']){
// To protect MySQL injection
$email = stripslashes($_POST['email']);
$password = stripslashes($_POST['password']);
$email = mysqli_real_escape_string($dblink, $email);
$password = mysqli_real_escape_string($dblink, $password);
$_SESSION['aes_key'] = "<KEY>";
//Check database for user
$sql = "SELECT * FROM users WHERE email='$email' and password=AES_ENCRYPT('$password', '$_SESSION[aes_key]')";
if($result = mysqli_query($dblink, $sql)){
if(mysqli_num_rows($result)==1){
$userInfo = mysqli_fetch_array($result);
$_SESSION['region'] = $userInfo['region'];
// Set session var for email to verify login
$_SESSION['email']=$email;
//Redirect to control panel
?>
<script type="text/javascript">
window.location = "adminHome.php";
</script>
<?php
//Login was invalid
}else{
$msg = "Invalid username or password.";
$err = true;
}
}
}
//User is not logged in
if((!isset($_SESSION['email'])) && ($_GET['loggedIn'] == "no") && ($_GET['logout'] != 1)){
$msg = "You are not currently logged in.";
$err = true;
}
//User has logged out
if(isset($_GET['logout'])){
$msg = "You have logged out.";
session_destroy();
}
include '_header.php';
?>
<div class="container">
<div class="row">
<div class="page-header">
<h1> Administration Login</h1>
</div>
<div class="col-sm-8 col-sm-push-2 col-lg-6 col-lg-push-3">
<?php
if(isset($msg)){
if($err) $class = "alert-danger";
else $class = "alert-success";
echo "<div class=\"alert $class\" role=\"alert\"> $msg </div>";
}
?>
<form role="form" action="index.php" method="post">
<div class="form-group">
<label for="email">Email:</label>
<input class="form-control" name="email" id="email" type="text" size="35" placeholder="<EMAIL>" />
</div>
<div class="form-group">
<label for="password">Password:</label>
<input class="form-control" name="password" id="password" type="password" placeholder="<PASSWORD>"/>
</div>
<input name="submit" type="submit" value="Login" class="btn btn-primary" />
</form>
</div><!-- ./col -->
</div><!-- /.row -->
</div><!-- /.container -->
<?php include '_footer.php';?><file_sep><?php
$pageTitle = "";
include('../_header.php');
?>
<div class="container">
<div class="page-header">
<h1>Archaeology Works</h1>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 ">
<div class="row box box-line">
<div class="col-sm-12">
<img src="images/archworks.jpg" class="img-responsive center-block" alt="" />
</div><!-- /.col -->
<p>These hands-on workshops focus on different archaeological subjects but are designed for people of all ages. Participants explore archaeological topics through a short presentation then activities, demonstrations, and real artifacts in order to investigate the past like an archaeologist. Archaeology Works workshops are generally 2 hours long and are meant for the general public. Past workshop topics have included: flotation, shells, pottery, hunting technology, food, dating, shipwrecks, dirt, bones, fishing, and ceramics. Contact your <a href="../regions.php">local FPAN regional center</a> if you are interested in attending or setting up one of these programs in your area.</p>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container -->
<?php include('../_footer.php'); ?><file_sep><?php
$pageTitle = "Programs";
include 'header.php';
?>
<!-- Main Middle -->
<script type="text/javascript">
showElement('projects_sub');
</script>
<div id="middle">
<div id="med_tables">
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th class="med_header"><h1>Programs</h1></th>
</tr>
<tr>
<td class="table_mid">
<table style="margin-left:auto; margin-right:auto;" cellpadding="5">
<tr>
<td><img src="images/allprograms.gif" /></td>
</tr>
<tr>
<td><ul>
<li> <h2><a href="ongoingPrograms.php">Ongoing Programs</a></h2> </li>
<li> <h2><a href="workshops.php">Workshop List</a></h2> </li>
<li> <h2><a href="programlist.php">Programs List</a></h2> </li>
</ul>
</table>
</td>
</tr>
<tr>
<td class="med_bottom"></td>
</tr>
</table>
</div>
<div id="sm_tables">
<?php
include '../events/eventBox.php';
echo "<br/>";
include '../events/calendar.php';
?>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep><?php
$pageTitle = "Contact";
include 'header.php';
?>
<!-- Main Middle -->
<div class="middle">
<?php
include '../events/eventBox.php';
?>
<table class="med_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Newsletter Archives</h1></th>
</tr>
<tr>
<td>
<!-- <p>The Northwest Region of the Florida Public Archaeology Network is hosted by the <a href="http://www.uwf.edu">University of West Florida</a> in Pensacola, and is based in the historic <a href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=207+east+main+st+pensacola&sll=37.0625,-95.677068&sspn=50.777825,114.169922&ie=UTF8&hq=&hnear=207+E+Main+St,+Pensacola,+Escambia,+Florida+32502&z=17" target="_blank"> L&N Marine Terminal at 207 East Main St</a>. The Northwest Region shares offices with the Network Coordinating Center, <a href="mailto:<EMAIL>">Dr. <NAME></a>, Executive Director, and <a href="mailto:<EMAIL>"><NAME></a>, Office & Contracts Manager.</p>-->
<ul>
<li><a href="http://flpublicarchaeology.org/uploads/nwrc/FPAN%20NW%20Newsletter%20Spring%202014.pdf">Spring 2014</a></li>
<li><a href="http://flpublicarchaeology.org/uploads/nwrc/FPAN%20NW%20Newsletter%20Winter%201314.pdf">Winter 2013/2014</a></li>
<li><a href="http://flpublicarchaeology.org/uploads/nwrc/FPAN NW Newsletter Fall 2013small.pdf">Fall 2013</a></li>
<li><a href="http://flpublicarchaeology.org/uploads/nwrc/FPAN NW Newsletter Summer_2013.pdf">Summer 2013</a></li>
<li><a href="../uploads/nwrc/FPAN NW Newsletter_Spring 2013.pdf">Spring 2013</a></li>
<li><a href="../uploads/nwrc/FPAN NW Newsletter_Winter_2012_2013.pdf">Winter 2012/2013</a></li>
<li><a href="../uploads/nwrc/FPAN NW Newsletter_Fall 2012.pdf">Fall 2012</a></li>
<li><a href="../uploads/nwrc/FPAN NW Newsletter_Summer 2012.pdf">Summer 2012</a></li>
<li><a href="../uploads/nwrc/FPAN NW Newsletter_Winter 2012.pdf">Winter 2011/2012</a></li>
<li><a href="../uploads/nwrc/FPAN NW Newsletter_Fall 2011.pdf">Fall 2011</a></li>
<li><a href="../uploads/nwrc/FPAN NW Newsletter_Summer 2011.pdf">Summer 2011</a></li>
</ul>
<br/></td>
</tr>
</table>
<table class="med_table" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<th><h1>Northwest Region Newsletter Signup</h1></th>
</tr>
<tr>
<td>
<div align="center">
<form method="post" action="/newsletter/northwest/process.php">
<input type="hidden" name="formSubmitted" value="1">
<div class="notes">
<p><span class="required"></span> Let us know a little about yourself:</p>
</div>
<table style="width:400px;">
<tbody><tr>
<td align="right"><label class="required" for="email"><strong>Your Email:</strong></label></td>
<td><input type="text" size="32" maxlength="60" name="Email" id="email" value="">*</td>
</tr>
<tr>
<td align="right"><label for="field1">First Name:</label></td>
<td><input type="text" size="32" name="d[1]" id="field1"></td>
</tr><tr>
<td align="right"><label for="field2">Last Name:</label></td>
<td><input type="text" size="32" name="d[2]" id="field2"></td>
</tr><tr>
<td align="right"><label for="field5">County:</label></td>
<td>
<select name="d[5]" id="field5">
<option value="">Choose Selection</option>
<option>Escambia</option>
<option>Santa Rosa</option>
<option>Okaloosa</option>
<option>Walton</option>
<option>Holmes</option>
<option>Washington</option>
<option>Bay</option>
<option>Jackson</option>
<option>Calhoun</option>
<option>Gulf</option>
<option>Other in FL</option>
<option>Other outside FL</option>
</select>
</td>
</tr><tr>
<td align="right"><label for="field6">Which best describes you?:</label></td>
<td>
<select name="d[6]" id="field6">
<option value="">Choose Selection</option>
<option>Volunteer/Advocational</option>
<option>Heritage Professional</option>
<option>Teacher/Educator</option>
<option>Land Manager/Planner</option>
<option>Other Interested Person</option>
</select>
</td>
</tr>
</tbody></table>
<br>
<div class="buttons">
<input type="hidden" name="pommo_signup" value="true">
<input type="submit" name="pommo_signup" value="Subscribe">
</div>
</form>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?><file_sep>//provided by Apple, Inc.
function updateOrientation()
{
var orientation=window.orientation;
switch(orientation)
{
case 0:
document.body.setAttribute("class","portrait");
break;
case 90:
document.body.setAttribute("class","landscape");
break;
case -90:
document.body.setAttribute("class","landscape");
break;
}
window.scrollTo(0,1);
}
window.onorientationchange=updateOrientation;
<file_sep><?php
$pageTitle = "CRPT Conference";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th><h1>Cemetery Resource Protection Training (CRPT) Conference</h1></th>
</tr>
<tr>
<td>
<script type="text/javascript" src="https://formscentral.acrobat.com/Clients/Current/FormsCentral/htmlClient/scripts/adobe.form.embed.min.js"></script>
<script type="text/javascript">;ADOBEFORMS.EmbedForm({formId:"n6ji1NEKq3OTNGttj47-Qg"});</script>
</td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?><file_sep><?php
$pageTitle = "Then and Now: Life Along the New River";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Then and Now: Life Along the New River</h1></th>
</tr>
<tr>
<td class="table_mid">
<?php include 'nav.php'?>
<img src="images/logosm.png" align="left" style="margin:10px; border:1px solid #000" />
<p><br/><br/>
The Florida Public Archaeology Network’s Southeast Region hosted an exhibit to commemorate Fort Lauderdale’s 100th anniversary. “Then & Now: Life along the New River” is a celebration of Fort Lauderdale’s rich past, told through the stories of those who lived along the banks of New River. Although the entire story of the New River is too complex to tell here, this exhibit highlights a sample of narratives that drift from the river’s memory. The story of the New River is ultimately about the people who have lived along its banks. Prehistoric artifacts, historic objects and photographs reveal how the river has shaped the cultures and communities of Fort Lauderdale’s rich past, and how it continues to influence the city’s dynamic present.<br/>
<br/>
<strong>Educators:</strong> Also have a look at our accompanying <a href="EveryPictureTellsAStory.pdf">educational module</a></p>
<h2 align="center"><a href="boating.php">Enter >></a></h2>
<br/>
<p align="center">
<br/>
<a href="Bibliography.docx">Bibliography</a>
</p>
<hr/>
<br/>
<p align="center">
<!-- <object style="height: 390px; width: 640px; margin-left:auto; margin-right:auto;">
<param name="movie" value="http://youtu.be/piVuDH6Wyqo"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always">
<embed src="http://youtu.be/piVuDH6Wyqo" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="360">
</object>-->
<iframe width="640" height="390" src="http://www.youtube.com/embed/piVuDH6Wyqo" frameborder="0" allowfullscreen></iframe>
</p></td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?>
<file_sep><?php
include 'header.php' ;
$startDate = "2013-01-01";
$endDate = "2013-03-31";
$displayLimit = 99999999;
$activityArray = array();
//Assign POST display limiting variables
if($_POST['submit']){
$startDate = $_POST['startYear']."-".$_POST['startMonth']."-".$_POST['startDay'];
$endDate = $_POST['endYear']."-".$_POST['endMonth']."-".$_POST['endDay'];
}
if($_POST['reset']){
$startDate = NULL;
$endDate = NULL;
$_POST = NULL;
}
?>
<table cellspacing="15" align="center" class="limitOptions">
<tr>
<td>
<form action="<?php echo curPageUrl(); ?>" method="post">
<label class="description" for="element_1">Start Date </label>
<span>
<input id="element_1_1" name="startMonth" class="element text" size="2" maxlength="2" value="<?php echo $_POST['startMonth']; ?>" type="text" >
-
</span> <span>
<input id="element_1_2" name="startDay" class="element text" size="2" maxlength="2" value="<?php echo $_POST['startDay']; ?>" type="text">
-
</span> <span>
<input id="element_1_3" name="startYear" class="element text" size="4" maxlength="4" value="<?php echo $_POST['startYear']; ?>" type="text">
</span> <span id="calendar_1"> <img id="cal_img_1" class="datepicker" src="images/calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</td>
<td>
<label class="description" for="element_2">End Date </label>
<span>
<input id="element_2_1" name="endMonth" class="element text" size="2" maxlength="2" value="<?php echo $_POST['endMonth']; ?>" type="text">
-
</span> <span>
<input id="element_2_2" name="endDay" class="element text" size="2" maxlength="2" value="<?php echo $_POST['endDay']; ?>" type="text" >
-
</span> <span>
<input id="element_2_3" name="endYear" class="element text" size="4" maxlength="4" value="<?php echo $_POST['endYear']; ?>" type="text" >
</span> <span id="calendar_2"> <img id="cal_img_2" class="datepicker" src="images/calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_2_3",
baseField : "element_2",
displayArea : "calendar_2",
button : "cal_img_2",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</td>
</tr>
<tr><td colspan="2" style="text-align:center;">
<input type="submit" name="submit" value="Go"/>
<input type="submit" name="reset" value="Reset"/>
</form>
</td>
</tr>
</table>
<hr />
<h2 align="center"> Activity Summary </h2>
<h2 align="center"><?php if($startDate && $endDate) echo $startDate ." - ".$endDate;?> </h2>
<div align="center">
<hr/>
<?php
if($startDate && $endDate){
$eventSummaryByRegionArray = rangedEventSummaryByRegion($startDate, $endDate);
foreach(getRegionArray() as $region){ ?>
<?php echo "<h3 align=\"center\">".getRegionName($region)."</h3>"; ?>
<?php echo "<table class=\"tablesorter\" id=\"resultsTable".$region."\" style=\"width:90%\">"; ?>
<thead>
<tr>
<th>Activity Type</th>
<th>Events</th>
<th>Attendees</th>
<th>Counties</th>
</tr>
</thead>
<tbody>
<?php
foreach($eventSummaryByRegionArray[$region] as $key => $value){ ?>
<tr>
<td style="width:120px" > <?php echo getTitle($key); ?> </td>
<td style="width:60px" > <?php echo $value['numEvents']; ?> </td>
<td style="width:80px"> <?php echo $value['numAttendees']; ?> </td>
<td> <?php if($value['counties'] != NULL) echo implode(", ", $value['counties']); ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
<hr/>
<?php } ?>
<h3 align="center">Volunteers and Volunteer Hours by Region</h3>
<table class="tablesorter" id="volunteerResultsTable" style="width:50%">
<thead>
<tr>
<th>Region</th>
<th>Number of Volunteers</th>
<th>Volunteer Hours</th>
</tr>
</thead>
<tbody>
<?php
foreach(volunteerSummary($startDate, $endDate) as $key => $value){ ?>
<tr>
<td> <?php echo getRegionName($value['Region']); ?> </td>
<td> <?php echo $value['numberVolunteers']; ?> </td>
<td> <?php echo $value['volunteerHours']; ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
<h3 align="center">Attendees by Region</h3>
<table class="tablesorter" id="attendeesResultsTable" style="width:50%">
<thead>
<tr>
<th>Region</th>
<th>Number of Attendees</th>
<th>Event Type</th>
</tr>
</thead>
<tbody>
<?php
foreach(attendeeSummary($startDate, $endDate) as $key => $value){ ?>
<tr>
<td> <?php echo getRegionName($value['Region']); ?> </td>
<td> <?php echo $value['numberAttendees']; ?> </td>
<td> <?php echo $value['eventType']; ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
<?php }else{ ?>
<h3 align="center" style="color:red;">Please enter a date range.</h3>
<?php } ?>
</div>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html>
<file_sep><?php
include 'appHeader.php';
$eventID = mysql_real_escape_string($_POST['eventID']);
$page = "eventEdit.php"; //Redirect here if error occurs
//If event is being deleted
/*
if($del){
$eventID = mysql_real_escape_string($_GET['eventID']);
if($eventID == null){
$msg = "Cannot delete, no eventID was specified!";
event_error($msg,"eventList.php");
}
else{
$sql = "DELETE FROM $table WHERE eventID = $eventID;";
if(!mysql_query($sql)){
$err = true;
$msg = 'Error: ' . mysql_error();
}
else
$msg = "Event successfully deleted.";
if($_GET['archived'] == true)
header("location:eventArchive.php?msg=$msg&err=$err");
else
header("location:eventList.php?msg=$msg&err=$err");
die();
}
}*/
// File upload config
/*
if($flyerFile){
$filename = $_FILES['flyerFile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes)){
$msg = 'The file you attempted to upload is not allowed.';
event_error($msg,$page);
}
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['flyerFile']['tmp_name']) > $max_filesize){
$msg = 'The file you attempted to upload is too large.';
event_error($msg,$page);
}
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($uploadDirectory)){
$msg = 'You cannot upload to the specified directory.';
event_error($msg,$page);
}
// Upload the file to your specified path.
if(!move_uploaded_file($_FILES['flyerFile']['tmp_name'],$uploadDirectory . $filename)){
$msg = 'There was an error during the file upload. Please try again.';
event_error($msg,$page);
}
}
*/
/****** Sanitize Data ******/
//Get POST variables from form, strip slashes and convert HTML characters. Store in an array to maintain form data in case of error
$eventVars['eventDate'] = mysql_real_escape_string($_POST['eventDate']);
$eventVars['eventTimeStart'] = mysql_real_escape_string($_POST['eventTimeStart']);
$eventVars['eventTimeEnd'] = mysql_real_escape_string($_POST['eventTimeEnd']);
$eventVars['startAMPM'] = $_POST['startAMPM'];
$eventVars['endAMPM'] = $_POST['endAMPM'];
$eventVars['eventTitle'] = mysql_real_escape_string(addslashes($_POST['title']));
$eventVars['eventLocation'] = mysql_real_escape_string(addslashes($_POST['location']));
$eventVars['eventAddress'] = mysql_real_escape_string(addslashes($_POST['address']));
$eventVars['eventCity'] = mysql_real_escape_string(addslashes($_POST['city']));
$eventVars['eventRegion'] = $_POST['region'];
$eventVars['eventDescription'] = mysql_real_escape_string(addslashes($_POST['description']));
$eventVars['eventURL'] = mysql_real_escape_string($_POST['url']);
$eventVars['contactName'] = mysql_real_escape_string($_POST['contactName']);
$eventVars['contactEmail'] = mysql_real_escape_string($_POST['contactEmail']);
$eventVars['contactPhone'] = mysql_real_escape_string($_POST['contactPhone']);
$_SESSION['eventVars'] = $eventVars;
/****** Check Input ******/
//Required field, cannot be blank, must have proper format
$eventDate = $eventVars['eventDate'];
check_input($eventDate, "You must enter a date.");
check_date($eventDate);
//Required fields, cannot be blank, must have proper format
$eventTimeStart = $eventVars['eventTimeStart'];
$eventTimeEnd = $eventVars['eventTimeEnd'];
check_input($eventTimeStart, "You must enter a start time.");
check_time($eventTimeStart);
check_input($eventTimeEnd, "You must enter an end time.");
check_time($eventTimeEnd);
//Append 'am' or 'pm' to eventTime strings for proper conversion to 24hr times
$eventTimeStart .= ' ' . $eventVars['startAMPM'];
$eventTimeEnd .= ' ' . $eventVars['endAMPM'];
//Convert times and dates to 24hr PHP timestamp
$timestampStart = strtotime($eventDate . $eventTimeStart);
$timestampEnd = strtotime($eventDate . $eventTimeEnd);
//Convert times and dates to 24hr MySQL time format
$eventDateTimeStart = date('Y-m-d H:i:s', $timestampStart);
$eventDateTimeEnd = date('Y-m-d H:i:s', $timestampEnd);
$title = $eventVars['eventTitle'];
$location = $eventVars['eventLocation'];
$address = $eventVars['eventAddress'];
$city = $eventVars['eventCity'];
$region = $eventVars['eventRegion'];
$description = $eventVars['eventDescription'];
$url = $eventVars['eventURL'];
$contactName = $eventVars['contactName'];
$contactEmail = $eventVars['contactEmail'];
//$contactPhone = formatPhone($eventVars['contactPhone']);
check_input($title,"You must enter a title.");
check_input($location,"You must enter a location.");
check_input($address,"You must enter a address.");
check_input($city,"You must enter a city.");
check_input($description,"You must enter a description.");
check_input($region,"You must choose a region.");
check_input($contactName,"You must enter a contact.");
check_input($contactEmail,"You must enter a contact email address.");
check_input($contactPhone,"You must enter a contact phone number.");
/****** Put the Event in the Database ******/
//If eventID is defined, event is being edited
if($_POST['eventID'] != null){
$sql = "UPDATE $table
SET eventDateTimeStart = '$eventDateTimeStart',
eventDateTimeEnd = '$eventDateTimeEnd',
eventTitle = '$title',
eventLocation = '$location',
eventAddress = '$address',
eventCity = '$city',
eventDescription = '$description',
eventRegion = '$region',
eventURL = '$url',
contactName = '$contactName',
contactEmail = '$contactEmail',
contactPhone = '$contactPhone'
WHERE eventID = $eventID;";
if(!mysql_query($sql)){
$err = true;
$msg = 'Error: ' . mysql_error();
}
else
$msg = "Event successfully updated.";
//Clear temporary event array
$_SESSION['eventVars'] = "";
//Redirect to event listing with messages and errors
header("location:eventSubmitted.php?msg=$msg&err=$err");
//Else if eventID is not defined, new event is being added
}else{
$sql = "INSERT INTO $table (eventDateTimeStart, eventDateTimeEnd, eventTitle, eventLocation, eventAddress,
eventCity, eventRegion, eventURL, eventDescription, contactName, contactEmail, contactPhone)
VALUES ('$eventDateTimeStart', '$eventDateTimeEnd', '$title', '$location', '$address', '$city', '$region', '$url',
'$description', '$contactName', '$contactEmail', '$contactPhone');";
if(!mysql_query($sql)){
$err = true;
$msg = 'Error: ' . mysql_error();
}
else
$msg = "Event successfully added.";
//Clear temporary event array
$_SESSION['eventVars'] = "";
//Redirect to event listing with messages and errors
header("location:eventSubmitted.php?msg=$msg&err=$err");
}
?><file_sep><?php
//initialized some vars
$rowsperpage = 6; // number of events to show per page
// ********** Setup SQL queries ********** //
//If eventDate is define in URL, show only events for that day
if(isset($_GET['eventDate'])){
$eventDate = $_GET['eventDate'];
$sql = "SELECT * FROM $table WHERE eventDateTimeStart LIKE '$eventDate%' ORDER BY eventDateTimeStart ASC;";
//if eventDate is not set, show all upccoming events
}else{
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM $table
WHERE eventDateTimeStart >= CURDATE()";
$result = mysqli_query($dblink, $sql);
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
}else{
$currentpage = 1;
}
if ($currentpage > $totalpages)
$currentpage = $totalpages;
if ($currentpage < 1)
$currentpage = 1;
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT * FROM $table
WHERE eventDateTimeStart >= CURDATE()
ORDER BY eventDateTimeStart ASC
LIMIT $offset, $rowsperpage";
}
function showEvents(){
global $dblink, $sql, $archiveURL;
// ******** Run dem queries, print results ********* //
$listEvents = mysqli_query($dblink, $sql);
//If events found, print out events
if(mysqli_num_rows($listEvents) != 0){
echo "<hr/>";
while($event = mysqli_fetch_array($listEvents)){
$timestampStart = strtotime($event['eventDateTimeStart']);
$timestampEnd = strtotime($event['eventDateTimeEnd']);
$eventDate = date('F j', $timestampStart);
$eventTimeStart = date('g:ia', $timestampStart);
$eventTimeEnd = date('g:ia', $timestampEnd);
?>
<div class="row event-list">
<p class="col-md-5 text-center">
<strong><span class="event-date"><?php echo $eventDate?></span> <span class="event-separator">@</span><br/>
<?php echo $eventTimeStart ?> <span class="event-separator">til</span> <?php echo $eventTimeEnd;?></strong>
</p>
<p class="col-md-7 text-center">
<?php echo "<a href=\"eventDetail.php?eventID=".$event['eventID']."\">".stripslashes($event['title'])."</a>"; ?>
</p>
</div>
<hr/>
<?php
}//end while
}else{
echo '<p class="text-center">No events are currently scheduled.</p>';
}
}
function showPaginationLinks(){
global $totalpages, $currentpage, $archiveURL;
/****** build the pagination links ******/
if($totalpages > 1){
echo "<ul class=\"pagination pagination-sm\">";
// range of num links to show on either side of current page
$range = 1;
// if not on page 1, show back links
if ($currentpage > 1) {
echo "<li><a href='{$_SERVER['PHP_SELF']}?currentpage=1'> « </a></li>";
// get previous page num
$prevpage = $currentpage - 1;
echo "<li><a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'> < </a></li>";
}
// if on page 1, disable back links
if ($currentpage == 1) {
echo "<li class=\"disabled\"><a href=''> « </a></li>";
echo "<li class=\"disabled\"><a href=''> < </a></li>";
}
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
echo "<li class=\"active page-link\"><a class=\"btn btn-primary btn-md\" href=''> $x </a></li>";
// if not current page...
} else {
// make it a link
echo "<li class=\"page-link\"><a class=\"btn btn-primary btn-md\" href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a></li>";
}
}
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
echo "<li> <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'> > </a></li>";
echo "<li> <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'> » </a></li>";
} // end if
if ($currentpage == $totalpages) {
echo "<li class=\"disabled\"> <a href=''>></a> </li>";
echo "<li class=\"disabled\"> <a href=''>»</a> </li>";
}
echo "</ul>";
}
/****** end build pagination links ******/
}
?>
<file_sep><?php
/**
* user_groups log--tabs
* @author <NAME> (sbillard)
* @package plugins
*/
define('OFFSET_PATH', 1);
require_once(dirname(__FILE__) . '/admin-globals.php');
admin_securityChecks(NULL, currentRelativeURL());
if (isset($_GET['action'])) {
$action = sanitize($_GET['action'], 3);
$what = sanitize($_GET['filename'], 3);
$file = SERVERPATH . '/' . DATA_FOLDER . '/' . $what . '.log';
XSRFdefender($action);
if (zp_apply_filter('admin_log_actions', true, $file, $action)) {
switch ($action) {
case 'clear_log':
$_zp_mutex->lock();
$f = fopen($file, 'w');
if (@ftruncate($f, 0)) {
$class = 'messagebox';
$result = sprintf(gettext('%s log was emptied.'), $what);
} else {
$class = 'errorbox';
$result = sprintf(gettext('%s log could not be emptied.'), $what);
}
fclose($f);
clearstatcache();
$_zp_mutex->unlock();
if (basename($file) == 'security.log') {
zp_apply_filter('admin_log_actions', true, $file, $action); // have to record the fact
}
break;
case 'delete_log':
$_zp_mutex->lock();
@chmod($file, 0777);
if (@unlink($file)) {
$class = 'messagebox';
$result = sprintf(gettext('%s log was removed.'), $what);
} else {
$class = 'errorbox';
$result = sprintf(gettext('%s log could not be removed.'), $what);
}
clearstatcache();
$_zp_mutex->unlock();
unset($_GET['tab']); // it is gone, after all
if (basename($file) == 'security.log') {
zp_apply_filter('admin_log_actions', true, $file, $action); // have to record the fact
}
break;
case 'download_log':
include_once(SERVERPATH . '/' . ZENFOLDER . '/lib-zipStream.php');
$zip = new ZipStream(sanitize($_GET['tab'], 3) . '.zip');
$zip->add_file_from_path(basename($file), $file);
$zip->finish();
break;
}
}
}
list($subtabs, $default) = getLogTabs();
$zenphoto_tabs['logs'] = array('text' => gettext("logs"),
'link' => WEBPATH . "/" . ZENFOLDER . '/admin-logs.php?page=logs',
'subtabs' => $subtabs,
'default' => $default);
printAdminHeader('logs', $default);
echo "\n</head>";
?>
<body>
<?php printLogoAndLinks(); ?>
<div id="main">
<?php
printTabs();
?>
<div id="content">
<?php
if ($default) {
$logfiletext = str_replace('_', ' ', $default);
$logfiletext = strtoupper(substr($logfiletext, 0, 1)) . substr($logfiletext, 1);
$logfile = SERVERPATH . "/" . DATA_FOLDER . '/' . $default . '.log';
if (file_exists($logfile) && filesize($logfile) > 0) {
$logtext = explode("\n", file_get_contents($logfile));
} else {
$logtext = array();
}
?>
<h1><?php echo gettext("View logs:"); ?></h1>
<?php $subtab = printSubtabs(); ?>
<!-- A log -->
<div id="theme-editor" class="tabbox">
<?php zp_apply_filter('admin_note', 'logs', $subtab); ?>
<?php
if (isset($result)) {
?>
<div class="<?php echo $class; ?> fade-message">
<h2><?php echo $result; ?></h2>
</div>
<?php
}
?>
<form method="post" action="<?php echo WEBPATH . '/' . ZENFOLDER . '/admin-logs.php'; ?>?action=change_size&page=logs&tab=<?php echo html_encode($subtab) . '&filename=' . html_encode($subtab); ?>" >
<span class="button buttons">
<a href="<?php echo WEBPATH . '/' . ZENFOLDER . '/admin-logs.php?action=delete_log&page=logs&tab=' . html_encode($subtab) . '&filename=' . html_encode($subtab); ?>&XSRFToken=<?php echo getXSRFToken('delete_log'); ?>">
<img src="images/edit-delete.png" /><?php echo gettext('Delete'); ?></a>
</span>
<?php
if (!empty($logtext)) {
?>
<span class="button buttons">
<a href="<?php echo WEBPATH . '/' . ZENFOLDER . '/admin-logs.php?action=clear_log&page=logs&tab=' . html_encode($subtab) . '&filename=' . html_encode($subtab); ?>&XSRFToken=<?php echo getXSRFToken('clear_log'); ?>">
<img src="images/refresh.png" /><?php echo gettext('Reset'); ?></a>
</span>
<span class="button buttons">
<a href="<?php echo WEBPATH . '/' . ZENFOLDER . '/admin-logs.php?action=download_log&page=logs&tab=' . html_encode($subtab) . '&filename=' . html_encode($subtab); ?>&XSRFToken=<?php echo getXSRFToken('download_log'); ?>">
<img src="images/arrow_down.png" /><?php echo gettext('Download'); ?></a>
</span>
<?php
}
?>
</form>
<br class="clearall" />
<br />
<blockquote class="logtext">
<?php
if (!empty($logtext)) {
$header = array_shift($logtext);
$fields = explode("\t", $header);
if (count($fields) > 1) { // there is a header row, display in a table
?>
<table id="log_table">
<?php
if (!empty($header)) {
?>
<tr>
<?php
foreach ($fields as $field) {
?>
<th>
<span class="nowrap"><?php echo $field; ?></span>
</th>
<?php
}
?>
</tr>
<?php
}
foreach ($logtext as $line) {
?>
<tr>
<?php
$fields = explode("\t", trim($line));
foreach ($fields as $key => $field) {
?>
<td>
<?php
if ($field) {
?>
<span class="nowrap"><?php echo html_encode($field); ?></span>
<?php
}
?>
</td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
<?php
} else {
array_unshift($logtext, $header);
foreach ($logtext as $line) {
if ($line) {
?>
<p>
<span class="nowrap">
<?php
echo str_replace(' ', ' ', html_encode(getBare(trim($line))));
?>
</span>
</p>
<?php
}
}
}
}
?>
</blockquote>
</div>
<?php
} else {
?>
<h2><?php echo gettext("There are no logs to view."); ?></h2>
<?php
}
?>
</div>
</div>
<?php printAdminFooter(); ?>
<?php
// to fool the validator
echo "\n</body>";
echo "\n</html>";
?>
<file_sep><?php
include 'header.php';
include 'dbConnect.php';
if($_GET['region'])
$region = stripslashes($_GET['region']);
?>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<td class="lg_mid">
<h1 align="center">Upcoming Events</h1>
<h2 align="center"> <?php if(isset($region)) echo $region. " Region"; ?> </h2>
<div style="margin-left:30px; margin-right:30px;">
<br/>
<hr/>
<br/>
</div>
<div style="margin-left:20px; margin-right:20px;">
<?php
$listStartDate = '2014-03-01';
// find out how many rows are in the table
if(isset($region)){
$sql = "SELECT COUNT(*) FROM $table
WHERE eventDateTimeStart >= '$listStartDate'
AND eventRegion = $region
AND isApproved = 1";
}else{
$sql = "SELECT COUNT(*) FROM $table
WHERE eventDateTimeStart >= '$listStartDate'
AND isApproved = 1";
$result = mysql_query($sql, $link);
$r = mysql_fetch_row($result);
$numrows = $r[0];
}
// number of rows to show per page
$rowsperpage = 6;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get events after startDate
if(isset($region)){
$sql = "SELECT * FROM $table
WHERE eventDateTimeStart >= '$listStartDate'
AND eventRegion = '$region'
AND isApproved = 1
ORDER BY eventDateTimeStart ASC";
}else{
$sql = "SELECT * FROM $table
WHERE eventDateTimeStart >= '$listStartDate'
AND isApproved = 1
ORDER BY eventDateTimeStart ASC
LIMIT $offset, $rowsperpage";
}
$upcomingEvents = mysql_query($sql, $link);
$approvedEvents = false; //default to false until approved events are found
// If the query returned more than 0 events
if(mysql_num_rows($upcomingEvents) != 0 ){
while($event = mysql_fetch_array($upcomingEvents))
{
$timestampStart = strtotime($event['eventDateTimeStart']);
$timestampEnd = strtotime($event['eventDateTimeEnd']);
//Convert and format dates and times
$eventDate = date('l, F j, Y', $timestampStart);
$eventTimeStart = date('g:i a', $timestampStart);
$eventTimeEnd = date('g:i a', $timestampEnd);
?>
<table style="width:100%">
<tr>
<td style="min-width:380px;">
<p><h2>
<?php echo stripslashes($event['eventTitle']);?>
</h2></p>
<p>
<strong><? echo $eventDate; ?> @ <?php echo $eventTimeStart; ?></strong><br/>
<strong>Location:</strong><em> <?php echo $event['eventLocation']; ?></em><br />
<?php echo $event['eventCity']; ?> -
<a href="regions.php" target="_blank"> <?php echo $event['eventRegion'];?> Florida</a>
</p>
</td>
<td style="width:260px;">
<p>
<h3>
<a href="eventDetail.php?eventID=<?php echo $event['eventID']; ?>&eventDate=<?php echo $eventDate; ?>"> View Details </a>
</h3>
</p>
</td>
</table>
<?php
}// end while
}else
echo '<br/><p align="center">No events currently scheduled. Check back soon!</p>';
echo "<h4 align=\"center\">";
/****** build the pagination links ******/
// range of num links to show
$range = 1;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a>";
} // end if
// only if there is more than one page
if ($totalpages > 1){
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo "[<b>$x</b>]";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
}// end if
// if not on last page, show forward and last page links
if (($currentpage != $totalpages) && ($totalpages > 1)) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
echo "</h4>";
?>
</div>
<div style="margin-left:30px; margin-right:30px;">
<br/>
<hr/>
<br/>
<br/>
</div>
</td>
</tr>
</table>
<?php include 'calendar.php'; ?> <br/>
<table class="sm_table" cellpadding="0" cellspacing="0">
<tr>
<th class="sm_header"> <h2 align="center"> Filter Events </h2></th>
</tr>
<tr>
<td class="sm_mid">
<p> By Region:
<ul>
<li><a href="eventList.php?®ion=Northwest">Northwest</a></li>
<li><a href="eventList.php?®ion=North Central">North Central</a></li>
<li><a href="eventList.php?®ion=Northeast">Northeast</a></li>
<li><a href="eventList.php?®ion=West Central"> West Central</a></li>
<li><a href="eventList.php?®ion=Central">Central</a></li>
<li><a href="eventList.php?®ion=East Central">East Central</a></li>
<li><a href="eventList.php?®ion=Southwest">Southwest</a></li>
<li><a href="eventList.php?®ion=Southeast">Southeast</a></li>
<li><a href="eventList.php"> Show All </a></li>
</ul>
</p>
</td>
</tr>
</table>
<div class="clearFloat"></div>
</div>
<?php include 'footer.php'; ?><file_sep><?php
include 'header.php';
$employeeSql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($employeeSql);
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true){
$formVars = $_SESSION['formVars'];
$date = $formVars['year'] ."-". $formVars['month'] ."-". $formVars['day'];
$comments = $formVars['comments'];
//Insert new Activity ID
$sql = "INSERT INTO Activity VALUES (NULL);";
if(!mysql_query($sql)){
$err = true;
$msg .= ' Error: ' . mysql_error();
}
//Insert activity info with new Activity ID
$sql = "INSERT INTO ServiceToCommunity (id, submit_id, date, comments)
VALUES (LAST_INSERT_ID(), '$_SESSION[staffID]', '$date', '$comments');";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error();
}
//For logged in staff member, insert entry into EmployeeActivity to associate that employee with this activity
$sql = "INSERT INTO EmployeeActivity VALUES ('$_SESSION[staffID]', LAST_INSERT_ID());";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error();
}
//If there were no erorrs while inserting: Clear temporary event array, display success message
if($err != true){
$_SESSION['formVars'] = "";
$msg = "Activity was successfully logged!";
}
?>
<div class="summary">
<br/><br/>
<?php echo "<h3>".$msg."</h3>"; ?>
<br/><br/><br/><br/>
<a href="<?php echo $_SERVER['PHP_SELF']; ?>">Enter another Service to Community</a> or
<a href="main.php">return to main menu</a>.
<br/><br/>
</div>
<?php } //End confirmed submission IF ?>
<?php //Form has been submitted. Process form submission.
if(isset($_POST['submit']) && !isset($_POST['confirmSubmission'])){
// Sanitize Data
$formVars['month'] = mysql_real_escape_string(addslashes($_POST['month']));
$formVars['day'] = mysql_real_escape_string(addslashes($_POST['day']));
$formVars['year'] = mysql_real_escape_string(addslashes($_POST['year']));
$formVars['comments'] = mysql_real_escape_string(addslashes($_POST['comments']));
$date = $formVars['year'] ."-". $formVars['month'] ."-". $formVars['day'];
$_SESSION['formVars'] = $formVars;
?>
<br/><br/>
<div class="summary">
<br/>
<br/>
<div style="text-align:left; margin-left:100px;">
<?php
echo "<strong>Date:</strong> " .$date."<br/>";
echo "<strong>Staff member:</strong> ". $_SESSION['user']."<br/>";
echo "<strong>Comments:</strong> ".$formVars['comments']."<br/>";
?>
</div>
<br/><br/>
If any of this is incorrect, please
<a href="<?php echo $_SERVER['PHP_SELF']; ?>"> go back and correct it</a>.
<br/><br/>
Otherwise, please confirm your submission:
<br/><br/>
<form id="submissionForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<input type="hidden" name="confirmSubmission" value="true" />
<input type="submit" name="submit" value="Confirm" />
</form>
<br/>
<br/>
</div>
<?php }elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="serviceHostInstitution" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Service to Community</h2>
<p></p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text">
/
<label for="element_1_1">MM</label>
</span> <span>
<input id="element_1_2" name="day" class="element text" size="2" maxlength="2" value="<?php echo $formVars['day']; ?>" type="text">
/
<label for="element_1_2">DD</label>
</span> <span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text">
<label for="element_1_3">YYYY</label>
</span> <span id="calendar_1"> <img id="cal_img_1" class="datepicker" src="images/calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</li>
<input type="hidden" name="staffID" value="<?php echo $_SESSION['staffID']; ?>" />
<li id="li_2" >
<label class="description" for="element_2">Comments </label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium" onKeyDown="limitText(this.form.comments,this.form.countdown,2080);"
onKeyUp="limitText(this.form.comments,this.form.countdown,2080);"><?php echo $formVars['comments']; ?></textarea>
<br/>
<font size="1">(Maximum characters: 2080)<br>
You have
<input readonly type="text" name="countdown" size="3" value="2080">
characters left.</font> </div>
</li>
<li class="buttons">
<input type="hidden" name="form_id" value="384428" />
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close else ?>
</div>
<img id="bottom" src="images/bottom.png" alt="">
</body>
</html><file_sep><?php
$pageTitle = "Explore";
$county = isset($_GET['county']) ? $_GET['county'] : null;
include('_header.php');
?>
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-push-3">
<!-- ********* ****************** ********** -->
<!-- ********* Explore Bay County ********** -->
<!-- ********* ****************** ********** -->
<?php if($county == 'bay'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Bay County</small></h1>
</div>
<div class="row">
<div class="box-dash row col-sm-8 col-sm-push-2">
Home to some of the world's most beautiful and famous beaches, Bay County hosts an abundance of archaeological, historic, and natural resources both on land and in the water.
</div>
</div>
<div class="col-md-6">
<h2>National Registor of Historic Places</h2>
<div class="box-tab">
<p class="text-center"><a target="_blank" href="http://www.co.walton.fl.us"></a>The following historical sites can be found on the:<br />
<a target="_blank" href="http://www.nationalregisterofhistoricplaces.com/fl/Bay/state.html">National Register of Historic Places</a></p>
<ul>
<li><a target="_blank" href="http://www.nationalregisterofhistoricplaces.com/fl/Bay/state.html">Latimer Cabin</a></li>
<li><a target="_blank" href="http://www.flheritage.com/facts/reports/places/index.cfm?fuseaction=ListAreas&county=Bay" target="_blank"> <NAME> House</a></li>
<li><a target="_blank" href="http://www.nationalregisterofhistoricplaces.com/fl/Bay/state.html">Sapp House</a></li>
<li><a target="_blank" href="http://www.nationalregisterofhistoricplaces.com/fl/Bay/state.html">Schmidt—Godert Farm</a></li>
<li><a target="_blank" href="http://www.nationalregisterofhistoricplaces.com/fl/Bay/state.html">Sherman Arcade</a></li>
</ul>
</div>
<h2>Shipwrecks</h2>
<div class="box-tab row">
<p class="col-sm-6 text-center">
<a target="_blank" href="http://www.flheritage.com/archaeology/underwater/seamuseum/tarpon/index.htm"><span class="h3"> SS <em>Tarpon</em></span>
</a>
<img src="images/Tarpon2.gif" alt="SS Tarpon" width="200" height="139" class="padded-center img-responsive" />
</p>
<p class="col-sm-6 text-center">
<em><a target="_blank" href="http://www.flheritage.com/archaeology/underwater/seamuseum/vamar/index.htm"> <span class="h3">Vamar</span></a></em>
<img src="images/vamar_trotter.jpg" alt="Vamar" width="200" height="150" class="padded-center img-responsive" />
</p>
</div>
</div><!-- /.col -->
<div class="col-md-6">
<h2>Government offices</h2>
<div class="box-tab">
<p>
<a target="_blank" href="http://www.co.bay.fl.us/">Bay County Government</a>
</p>
<p>
<a target="_blank" href="http://www.panamacity.org/">Bay County Chamber of Commerce</a>
</p>
</div>
<h2>Parks</h2>
<div class="box-tab ">
<p align="center">
<a target="_blank" href="http://www.floridastateparks.org/camphelen/default.cfm">
<img src="images/camphelen.jpg" alt="Welcome to Camp Helen State Park!" width="300" height="117" class="padded-center img-responsive" /></a>
</p>
<p align="center">
<a target="_blank" href="http://www.floridastateparks.org/standrews/">
<img src="images/standrews.jpg" alt="Welcome to St. Andrews State Park!" width="300" height="117" class="padded-center img-responsive" /></a>
</p>
</div>
</div><!-- /.col -->
<!-- ********* ********************** ********** -->
<!-- ********* Explore Calhoun County ********** -->
<!-- ********* ********************** ********** -->
<?php }elseif($county == 'calhoun'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Calhoun County</small></h1>
</div>
<div class="row">
<div class="box-dash col-sm-8 col-sm-push-2">
<p>Named for twice Vice President and U.S. Senator <NAME>, Calhoun County lies in the heart of the Florida Panhandle. Within the county borders are a wide variety of natural, historic, and archaeological sites including the Panhandle Pioneer Settlement, Clay Mary Historical Park, M & B Railroad Memorial, and the Old Courthouse. Calhoun County's diverse past is highlighted in the first bi-lingual historical marker in Florida for Cochranetown, home of the Apalachicola Creek Indians.</p>
</div>
</div><!-- /.row -->
<div class="col-sm-6">
<h2>Government Offices</h2>
<div class="box-tab">
<a target="_blank" href="http://www.calhounco.org/">Calhoun County Chamber of Commerce</a>
</div>
<h2>National Registor of Historic Places</h2>
<div class="box-tab">
<p class="text-center"><a target="_blank" href="http://www.co.walton.fl.us"></a>The following historical sites can be found on the:<br />
<a target="_blank" href="http://www.nationalregisterofhistoricplaces.com/fl/Bay/state.html">National Register of Historic Places</a></p>
<ul>
<li>
<p>Old Calhoun County Courthouse</p>
</li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h2>Historical Sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://ppmuseum.org/">Panhandle Pioneer Settlement</a></li>
<li><a target="_blank" href="http://www.flheritage.com/preservation/markers/markers.cfm?ID=calhoun">Florida Historical Markers</a></li>
<li>Blunt Reservation and Fields</li>
<li>Cochranetown- corakko talofv</li>
<li>Abe Springs Bluff Courthouse</li>
<li>“Old Blountstown” Courthouse</li>
<li>Altha Methodist Church</li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* *********************** ********** -->
<!-- ********* Explore Escambia County ********** -->
<!-- ********* *********************** ********** -->
<?php }elseif($county == 'escambia'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Escambia County</small></h1>
</div>
<div class="row">
<div class="box-dash col-sm-8 col-sm-push-2">
<img src="images/escambia.jpg" class="img-responsive padded-center" />
<p>
Located at the extreme western end of the Florida Panhandle, Escambia is the home county for the Northwest Region of the <strong>Florida Public Archaeology Network</strong>.
Escambia also is home to the <a target="_blank" href="http://uwf.edu">University of West Florida</a> and the <a target="_blank" href="http://pasfl.org/">Pensacola Archaeological Society</a>. Pensacola, Escambia County's seat, is the nation's oldest European settlement, first colonized by the Spanish in 1559.
</p>
</div>
</div><!-- /.row -->
<div class="col-sm-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.co.escambia.fl.us/">Escambia County Government</a> </li>
<li><a target="_blank" href="http://www.visitpensacola.com/">Visit Pensacola</a> </li>
<li><a target="_blank" href="http://www.pensacolachamber.com/">Pensacola Bay Area Chamber of Commerce</a> </li>
<li><a target="_blank" href="http://www.perdidochamber.com/">Perdido Key Area Chamber of Commerce</a></li>
<li><a target="_blank" href="http://visitpensacolabeach.com/">Pensacola Beach Visitors Information Center</a></li>
</ul>
</div>
<h2>Museums</h2>
<div class="box-tab">
<ul>
<li>
<a target="_blank" href="http://www.historicpensacola.org/">T. T. Wentworth Museum & Historic Pensacola Village</a>
</li>
<li>
<a target="_blank" href="http://uwf.edu/archaeology/">University of West Florida Archaeology Institute</a>
</li>
<li>
<a target="_blank" href="http://www.navalaviationmuseum.org/">National Museum of Naval Aviation</a>
</li>
<li>
<a target="_blank" href="http://www.historicpensacola.org/events.cfm">Pensacola Children's Museum</a>
</li>
</ul>
</div>
<h2>Underwater Sites</h2>
<div class="box-tab row">
<div class="col-sm-12">
<img src="images/mardigras.jpg" class="img-responsive center-block" width="144" height="97" />
<p><a target="_blank" href="http://uwf.edu/fpan/mardigras">The "Mardi Gras Shipwreck"</a> sank some 200 years ago about 35 miles off the coast of Louisiana in the Gulf of Mexico in 4,000 feet (1220 meters) of water. Research continues into the identity and history of the vessel.</p>
</div>
<div class="col-sm-12">
<img src="images/ussMass.jpg" class="img-responsive center-block" width="108" height="80" />
<p><a target="_blank" href="http://museumsinthesea.com/massachusetts/index.htm">USS Massachusetts</a><br/>
First used for battle in the Spanish-American war and later refitted for use as a training ship midshipmen and for experimental artillery training. She was finally decommissioned and scuttled just outside the entrance to Pensacola Bay.</p>
</div>
<div class="col-sm-12">
<img src="images/emanuelpt.gif" class="img-responsive center-block" width="84" height="60" />
<p><a target="_blank" href="http://dhr.dos.state.fl.us/archaeology/projects/shipwrecks/emanuelpoint/">The Emanuel Pt. Shipwreck</a><br/>
Florida's earliest shipwreck site is believed to be part of the 1559 expedition of Tristán de Luna. Most of his fleet was destroyed by a hurricane only a month after arriving in Pensacola.</p>
</div>
<div class="col-sm-12">
<img src="images/deadmans.gif" class="img-responsive center-block" width="126" height="60" />
<p><a target="_blank" href="http://uwf.edu/anthropology/research/maritime/deadmans/">Deadman's Island Shipwreck</a><br/>
In 1994, the remains of three barrel wells on the present shore of Deadman's Island appeared after the eroding effects of a storm.</p>
</div>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h2>State Parks</h2>
<div class="box-tab">
<a target="_blank" href="http://www.floridastateparks.org/biglagoon/">
<img src="images/biglagoon.jpg" class="img-responsive padded-center" width="390" height="152" /></a>
<p><a target="_blank" href="http://www.floridastateparks.org/biglagoon/">Big Lagoon State Park</a> is a coastal park which separates the mainland from Perdido Key and the Gulf of Mexico. It contains saltwater marshes, beaches, shallow bays, nature trails, and open woodlands attracting a wide variety of birds. Visitors enjoy camping, swimming, fishing, boating, canoeing, and hiking. Located on County Road 292A, 10 miles southwest of Pensacola.</p>
<a target="_blank" href="http://www.floridastateparks.org/perdidokey/">
<img src="images/perdidokey.jpg" class="img-responsive padded-center" width="390" height="152" /></a>
<p>Perdido Key is a 247-acre barrier island near Pensacola on the Gulf of Mexico. White sand beaches and rolling dunes covered with sea oats make this park a favorite destination for swimmers and sunbathers. Surf fishing is another popular activity. <a target="_blank" href="http://www.floridastateparks.org/perdidokey/">Perdido Key State Park</a> provides boardwalks from the parking lot allow visitors to access the beach without causing damage to the fragile dunes and beach vegetation. Covered picnic tables overlooking the beach provide a great place for family outings. Located 15 miles southwest of Pensacola, off State Road 292.</p>
<a target="_blank" href="http://www.floridastateparks.org/tarkilnbayou/default.cfm">
<img src="images/tarklinbayou.jpg" class="img-responsive padded-center" width="390" height="152" /></a>
<p><a target="_blank" href="http://www.floridastateparks.org/tarkilnbayou/default.cfm">The Tarklin Bayou Preserve</a> is home to rare and endangered plant species as well as the rare, carnivorous white-top pitcher plant which is unique to the Gulf Coast. Almost 100 other rare plants and animals depend on the wet prairie habitat, including the alligator snapping turtle, sweet pitcher plant, and Chapman's butterwort. A boardwalk offers visitors a view of the wild and beautiful Tarklin Bayou. Located about 1.5 miles south of the intersection of U.S. 98 and State Road 293.</p>
</div>
</div><!-- /.col -->
<!-- ********* ********************** ********** -->
<!-- ********* Explore Gulf County ********** -->
<!-- ********* ********************** ********** -->
<?php }elseif($county == 'gulf'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Gulf County</small></h1>
</div>
<div class="row">
<div class="box-dash col-sm-8 col-sm-push-2">
<p>
Named for the Gulf of Mexico, Gulf County boasts pristine beaches and a variety of historic and archaeological resources.
</p>
</div>
</div><!-- /.row -->
<div class="col-sm-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li>
<a target="_blank" href="http://www.gulfcountygovernment.com/">Gulf County Government</a>
</li>
<li>
<a target="_blank" href="http://www.gulfchamber.org/">Gulf County Chamber of Commerce</a>
</li>
<li>
<a target="_blank" href="http://www.visitgulf.com/">Tourism Development</a>
</li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li>
<a target="_blank" href="http://www.floridastateparks.org/constitutionconvention/default.cfm">Constitution Convention Museum State Park</a>
</li>
<li>
<a target="_blank" href="http://www.floridastateparks.org/stjoseph/">T.H. Stone Memorial St. Joseph Peninsula State Park</a>
</li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ********************** ********** -->
<!-- ********* Explore Holmes County ********** -->
<!-- ********* ********************** ********** -->
<?php }elseif($county == 'holmes'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Holmes County</small></h1>
</div>
<div class="row">
<div class="box-dash col-sm-8 col-sm-push-2">
<p>
Holmes County's motto, "There's No Place Like Holmes" speaks to the unique balance of natural beauty and an archaeologically and historically rich community.
</p>
</div>
</div><!-- /.row -->
<div class="col-sm-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.holmescountyonline.com/">Chamber of Commerce</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/poncedeleonsprings/default.cfm">Ponce de Leon Springs State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ********************** ********** -->
<!-- ********* Explore Jackson County ********** -->
<!-- ********* ********************** ********** -->
<?php }elseif($county == 'jackson'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Jackson County</small></h1>
</div>
<div class="row">
<div class="box-dash col-sm-8 col-sm-push-2">
<p>
Truly unique in its archaeology and environment, Jackson County is a combination of traditional southern history and hospitality mixed with a relaxed Florida attitude.
</p>
</div>
</div><!-- /.row -->
<div class="col-sm-6">
<h2>Government Offices</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.jacksoncountyfl.net/">County Government</a></li>
<li><a target="_blank" href="http://www.jacksoncounty.com/">Chamber of Commerce</a></li>
</ul>
</div>
<h2>Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/floridacaverns/default.cfm">Florida Caverns State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/threerivers/default.cfm">Three Rivers State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h2>National Register of Historic Places</h2>
<div class="box-tab">
<p class="text-center">The following historical sites can be found on the:
<a target="_blank" href="http://nrhp.focus.nps.gov/natreghome.do?searchtype=natreghome">National Register of Historic Places</a></p>
<ul>
<li><a target="_blank" href="http://www.jacksoncounty.com/Marianna-History/ely-criglar-house.html">Ely-Criglar House</a></li>
<li><a target="_blank" href="http://www.jacksoncounty.com/History/erwin-house.html">Erwin House</a></li>
<li><a target="_blank" href="http://www.jacksoncountytdc.com/great-oaks-bryan-mansion-greenwood.html">Great Oaks</a></li>
<li><a target="_blank" href="http://www.fnai.org/arrow/almanac/history/history_oralhistory_Pender.cfm">Pender's Store</a></li>
<li><a target="_blank" href="http://www.jacksoncountytdc.com/waddells-mill-pond-site.html">Waddells Mill Pond Site</a></li>
<li><a target="_blank" href="http://www.fnai.org/arrow/almanac/history/history_oralhistory_Pender.cfm">Theophilus West House</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* *********************** ********** -->
<!-- ********* Explore Okaloosa County ********** -->
<!-- ********* *********************** ********** -->
<?php }elseif($county == 'okaloosa'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Okaloosa County</small></h1>
</div>
<div class="row">
<div class="box-dash col-sm-8 col-sm-push-2">
<p>
Once a small pioneer town, Okaloosa County has grown into a modern community composed of beautiful beach vacation spots and a thriving military population. Despite its growth evidence of Okaloosa's rich past is evident everywhere, from the Native American mound at the Fort Walton Beach Heritage Park and Cultural Center to the warplanes at the Air Force Armament Museum.
</p>
</div>
</div><!-- /.row -->
<div class="col-sm-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li>
<a target="_blank" href="http://www.co.okaloosa.fl.us/">Okaloosa County Government</a>
</li>
</ul>
</div>
<h2>Museums & Cultural Centers</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.heritage-museum.org/">Heritage Museum of Northwest Florida</a></li>
<li><a target="_blank" href="http://fwb.org/index.php/museums">Fort Walton Beach Heritage Park and Cultural Center</a></li>
<li><a target="_blank" href="http://bakerblockmuseum.org/clouds/intheclouds/index-a.html">Baker Block Museum</a></li>
<li><a target="_blank" href="http://www.destinhistoryandfishingmuseum.org/">Destin History and Fishing Museum</a></li>
<li><a target="_blank" href="http://www.destin-ation.com/airforcearmamentmuseum/">Air Force Armament Museum</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/blackwaterriver/default.cfm">Blackwater River State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/yellowriver/default.cfm">Yellow River Marsh Preserve State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/rockybayou/default.cfm"><NAME> Rocky Bayou State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/hendersonbeach/default.cfm">Henderson Beach State Park</a></li>
</ul>
</div>
<h2>Historical Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.fasweb.org/chapters/emeraldcoast.htm">Emerald Coast Archaeological Society</a></li>
<li><a target="_blank" href="http://www.bakerblockmuseum.org/bod.htm">North Okaloosa Historical Association</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ************************* ********** -->
<!-- ********* Explore Santa Rosa County ********** -->
<!-- ********* ************************* ********** -->
<?php }elseif($county == 'santarosa'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Santa Rosa County</small></h1>
</div>
<div class="row">
<div class="box-dash col-sm-8 col-sm-push-2">
<img src="images/santarosa.jpg" class="img-responsive padded-center" width="168" height="120" />
<p>
Santa Rosa County's white sandy beaches and dense forests are just a short drive from the City of Pensacola. Rich in both history and archaeology, Santa Rosa County provides a wealth of opportunities for visitors interested in Northwest Florida's past. Places of interest include the Arcadia Mill Site, Gulf Islands National Seashore, and several historic districts.</p>
<p>Many of the sites listed below are on the <a target="_blank" href="http://www.nationalhistoricalregister.com/">National Register of Historic Places</a>. See the complete list for <a target="_blank" href="http://www.nationalhistoricalregister.com/fl/Santa+Rosa/state.html">Santa Rosa County</a></p>
</div>
</div><!-- /.row -->
<div class="col-sm-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.santarosa.fl.gov/">Santa Rosa County Government</a></li>
<li><a target="_blank" href="http://www.srcchamber.com/">Santa Rosa Chamber of Commerce</a></li>
</ul>
</div>
<h2>Historical sites</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.uwf.edu/anthropology/research/industrial/arcadia">Arcadia Sawmill & Arcadia Cotton Mill</a></li>
<li><a target="_blank" href="http://www.historicpensacola.org/arcadia.cfm">Arcadia @ Historica Pensacola Village Website</a></li>
</ul>
</div>
<h2>Historic Districts</h2>
<div class="box-tab">
<p class="text-center"><a target="_blank" href="http://bagdadvillage.org/">Bagdad Village Historic District</a></p>
<img src="images/bagdadvillage.jpg" class="img-responsive center-block" alt="Bagdad Village Historic District" width="168" height="108">
<p class="text-center"><a target="_blank" href="http://www.flheritage.com/facts/reports/places/index.cfm?fuseaction=ListAreas&county=Santa%20Rosa#569">Milton Historic District</a></p>
<img src="images/milton.jpg" class="img-responsive center-block" alt="Milton Historic District" width="132" height="122">
<p class="text-center"><a target="_blank" href="http://www.flheritage.com/facts/reports/places/index.cfm?fuseaction=ListAreas&county=Santa%20Rosa#570">Thomas Creek Archaeological District</a></p>
<img src="images/thomascreek.jpg" class="img-responsive center-block" alt="Thomas Crrek Archaeological District" width="180" height="125">
</div>
<h2>Museums</h2>
<div class="box-tab">
<img src="images/ln.gif" class="img-responsive center-block" alt="L&N Railroad Museum" width="120" height="68">
<p class="text-center"><a target="_blank" href="http://www.wfrm.org/">Louisville & Nashville Depot/West Florida Railroad Museum</a></p>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h2>Parks</h2>
<div class="box-tab">
<strong>National Parks</strong>
<p>
<ul>
<li><a target="_blank" href="http://www.nps.gov/guis/planyourvisit/naval-live-oaks.htm">Gulf Islands National Seashore</a></li>
</ul>
</p>
<strong>State Parks</strong>
<a target="_blank" href="http://www.santarosa.fl.gov/parks/navarrebeach.html"><img src="images/navarrebeach.jpg" class="center-block img-responsive" alt="Navarre Beach State Park" width="264" height="103"/></a>
<p><a target="_blank" href="http://www.santarosa.fl.gov/parks/navarrebeach.html">Navarre Beach State Park </a>is home to one of the most popular fishing destinations along the Emerald Coast. Anglers catch cobia, redfish, mackerel, flounder, bonita, Gulf kingfish, and Florida pompano from the park's 800-foot pier. Walkers visit the pier to see coastal and aquatic wildlife such as bottlenose dolphins, sea turtles, manta rays, and a variety of shorebirds. A multi-use trail provides access for bicycling, jogging, in-line skating, and wildlife viewing. Beach visitors can sunbathe, swim in the blue-green waters, or watch a stunning sunset over the Gulf of Mexico. A concession at the base of the fishing pier offers drinks, snacks, ice cream, and fishing amenities.</p>
</div>
<h2>Other Historic Places & Organizations</h2>
<div class="box-tab">
<strong>Trails</strong>
<p><a target="_blank" href="http://www.floridastateparks.org/blackwater/">The Blackwater Heritage State Trail</a>, a 7.0 miles, non-motorized paved trail is mostly a rural trail with only a few dwellings at some of the cross roads. There are some nice creek crossings on wooden bridges with few hills or grades. This is a pleasant trip for the whole family with lots of access and safe riding.</p>
<strong>Underwater Sites</strong>
<ul>
<li>Bethune Blackwater Schooner Shipwreck</li>
</ul>
<strong>Historical Places & Organizations</strong>
<ul>
<li><a target="_blank" href="http://www.kilnwalk.org/">Gulf Coast Kiln Walk Society</a></li>
<li><a target="_blank" href="http://www.santarosa.fl.gov/vetplaza/index.html">Santa Rosa Veterans Memorial Plaza</a></li>
<li><a target="_blank" href="http://www.nationalregisterofhistoricplaces.com/fl/Santa+Rosa/state.html">Big Heart West</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/tarkilnbayou/default.cfm">Butcherpen Mound</a></li>
<li><a target="_blank" href="http://www.flheritage.com/preservation/markers/markers.cfm?ID=santa%20rosa">First American Road in Florida</a></li>
<li><a target="_blank" href="http://www.flheritage.com/facts/reports/places/index.cfm?fuseaction=ListAreas&county=Santa%20Rosa#572">Florida State Road No. 1</a></li>
<li><a target="_blank" href="http://historical-places.findthedata.org/l/56170/Exchange-Hotel">Exchange Hotel Building</a></li>
<li><a target="_blank" href="http://www.flheritage.com/facts/reports/places/index.cfm?fuseaction=ListAreas&county=Santa%20Rosa#575">Mt. Pilgrim African Baptist Church</a></li>
<li><a target="_blank" href="http://www.nps.gov/guis/planyourvisit/naval-live-oaks.htm">Naval Live Oaks Reservation</a></li>
<li><a target="_blank" href="http://www.flheritage.com/facts/reports/places/index.cfm?fuseaction=ListAreas&county=Santa%20Rosa#576">Ollinger-Cobb House</a></li>
<li><a target="_blank" href="http://www.flheritage.com/facts/reports/places/index.cfm?fuseaction=ListAreas&county=Santa%20Rosa#577">St. Mary's Episcopal Church & Rectory</a></li>
<li><a target="_blank" href="http://historical-places.findthedata.org/l/73626/Third-Gulf-Breeze">Third Gulf Breeze</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ********************* ********** -->
<!-- ********* Explore Walton County ********** -->
<!-- ********* ********************* ********** -->
<?php }elseif($county == 'walton'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Walton County</small></h1>
</div>
<div class="row">
<div class="box-dash col-sm-8 col-sm-push-2">
<p>
One of the fastest-growing counties in Florida, Walton County has incorporated archaeological, historical, and environmental preservation into modern living. Home to the rare Coastal Dune Lakes as well as several state parks, Walton County includes beautiful beaches, rich woodlands, and prosperous agricultural lands. In addition, the county boasts a variety of archaeological and historical sites such as the Walton County Heritage Museum and the DeFuniak Springs Historic District.
</p>
</div>
</div><!-- /.row -->
<div class="col-sm-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.co.walton.fl.us/">Walton County Government</a></li>
</ul>
</div>
<h2>National Register of Historic Places</h2>
<div class="box-tab">
<p class="text-center">The following historical sites can be found on the:
<a target="_blank" href="http://nrhp.focus.nps.gov/natreghome.do?searchtype=natreghome">National Register of Historic Places</a></p>
<ul>
<li><a target="_blank" href="http://www.flheritage.com/facts/reports/places/index.cfm?fuseaction=ListAreas&county=walton">Perry L. Biddle House</a></li>
<li><a target="_blank" href="http://www.defuniakspringsflorida.net/chautauqua_hall_of_brotherhood.htm">Chautauqua Hall of Brotherhood</a></li>
<li><a target="_blank" href="http://www.co.walton.fl.us/index.aspx?NID=611">DeFuniak Springs Historic District</a></li>
<li><a target="_blank" href="http://www.cr.nps.gov/maritime/nhl/stone.htm">GovernorStone (historic sailing schooner)</a></li>
<li><a target="_blank" href="http://www.visitflorida.com/articles/early-rocket-testing-in-florida">Operation Crossbow Site</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h2>Museums & Cultural Centers</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.waltoncountyheritage.org/">Walton County Heritage Museum</a></li>
</ul>
</div>
<h2>State Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/deerlake/default.cfm">Deer Lake State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/edengardens/default.cfm">Eden Gardens State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/graytonbeach/default.cfm">Grayton Beach State Park</a></li>
<li><a target="_blank" href="http://www.floridastateparks.org/topsailhill/">Topsail Hill Preserve State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<!-- ********* ************************* ********** -->
<!-- ********* Explore Washington County ********** -->
<!-- ********* ************************* ********** -->
<?php }elseif($county == 'washington'){ ?>
<div class="page-header">
<h1><?=$pageTitle?> <small>Washington County</small></h1>
</div>
<div class="row">
<div class="box-dash col-sm-8 col-sm-push-2">
<p>
Just as today, early settlers were drawn to the vast forests and winding rivers of Washington County. These natural resources enticed a variety of people to the area, all of whom left behind the unique archaeological and historical record of Washington County.
</p>
</div>
</div><!-- /.row -->
<div class="col-sm-6">
<h2>National Register of Historic Places</h2>
<div class="box-tab">
<p class="text-center">The following historical sites can be found on the:
<a target="_blank" href="http://nrhp.focus.nps.gov/natreghome.do?searchtype=natreghome">National Register of Historic Places</a></p>
<ul>
<li><a target="_blank" href="http://www.exploresouthernhistory.com/mosshill1.html">Moss Hill Church</a></li>
<li><a target="_blank" href="http://paulgouldingproductions.com/womansclubofchipley/">Woman's Club of Chipley</a></li>
</ul>
</div>
<h2>Stae Parks</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.floridastateparks.org/fallingwaters/default.cfm">Falling Waters State Park</a></li>
</ul>
</div>
</div><!-- /.col -->
<div class="col-sm-6">
<h2>County Offices and Organizations</h2>
<div class="box-tab">
<ul>
<li><a target="_blank" href="http://www.washingtonfl.com/">County Government</a></li>
<li><a target="_blank" href="http://www.washcomall.com/">Chamber of Commerce</a></li>
</ul>
</div>
</div><!-- /.col -->
<?php }else{ ?>
<div class="page-header">
<h1><?=$pageTitle?></h1>
</div>
<div class="row">
<div class="box-dash col-sm-12 col-md-8 col-md-push-2">
<p>
The Northwest Region offers many amazing historical and archaeological sites that you can visit. Click on any county below to discover sites in your area.
<hr/>
<!-- Interactive SVG Map -->
<div id="nwmap" class="center-block"></div>
</p>
<hr/>
<div class="col-sm-12 text-center">
<div class="image"><img src="images/explore_page.jpg" alt="Explore Northwest Florida" class="img-responsive" width="400" height="464"></div>
</div>
</div>
</div><!-- /.row -->
<?php } ?>
</div><!-- /.col -->
<div class="col-sm-3 col-sm-pull-9">
<?php include('_sidebar.php'); ?>
</div><!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /.container -->
<script type="text/javascript" src="../_js/jquery.js"></script>
<script type="text/javascript" src="../_js/raphael.js"></script>
<script type="text/javascript" src="../_js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../_js/mapsvg.min.js"></script>
<script type="text/javascript">
$('#nwmap').mapSvg({
source: 'images/nw_counties_map.svg',
zoom: false,
pan:false,
responsive:true,
colors:{
background:"transparent",
hover:10,
selected:20,
stroke:"#000"
},
disableAll:true,
tooltipsMode:'names',
popover:{width:250, height:145},
marks:[
{ //Northwest Region Marker
xy:[58,165],
tooltip:'Northwest Regional Center & Coordinating Center',
attrs: {src:'../images/pin_yellow.png'}}
],
regions:{
'Escambia' :{popover:'<h3>Escambia</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=escambia">Explore Escambia County</a></p>'},
'Santa_Rosa' :{popover:'<h3>Santa Rosa</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=santarosa">Explore Santa Rosa County</a></p>'},
'Okaloosa' :{popover:'<h3>Okaloosa</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=okaloosa">Explore Okaloosa County</a></p>'},
'Walton' :{popover:'<h3>Walton</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=walton">Explore Walton County</a></p>'},
'Holmes' :{popover:'<h3>Holmes</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=holmes">Explore Holmes County</a></p>'},
'Washington' :{popover:'<h3>Washington</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=washington">Explore Washington County</a></p>'},
'Bay' :{popover:'<h3>Bay</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=bay">Explore Bay County</a></p>'},
'Gulf' :{popover:'<h3>Gulf</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=gulf">Explore Gulf County</a></p>'},
'Jackson' :{popover:'<h3>Jackson</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=jackson"> Explore Jackson County</a></p>'},
'Calhoun' :{popover:'<h3>Calhoun</h3><p class="text-center"><a class="btn btn-primary" href="/nwrc/explore.php?county=calhoun"> Explore Calhoun County</a></p>'}
}});
</script>
<?php include('_footer.php'); ?><file_sep><?php
$pageTitle = "Then and Now: Life Along the New River";
include '../header.php';
?>
<!-- Main Middle -->
<div id="middle">
<div id="lg_tables">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1>Then and Now: Life Along the New River</h1></th>
</tr>
<tr>
<td class="table_mid">
<div id="exhibit">
<?php include 'nav.php'?>
<h2 align="center">Hunting & Fishing </h2>
<p align="center"><img src="images/exhibit16.jpg" alt=""Everglades Hunt", Painting by Theodore Morris" /></p>
<p><strong>Artifacts from the Tequesta culture in the area date to about 2000 years ago.</strong> These first residents of the New River left remains of their camps, villages, and monuments as evidence of their existence in Broward County. Descendants of these people were encountered a century and half later by the early Spanish explorers in south Florida. Their complex society relied on canoes to access natural resources while maintaining trade and political networks. The New River Tequesta traveled from the Everglades, past hardwood hammocks, through the mangrove swamps, along fresh water lakes, and into the Atlantic Ocean in dugout canoes. Archaeological sites dot the banks of the river throughout each of these environments.</p>
<p> Evidence of Tequesta hunting and fishing expeditions are found in the archaeological record. Fresh water fish like largemouth bass and gar are found in the same deposits as salt water species such as sharks and snappers. Softshell turtles rest beside the remains of deer and alligators. Oysters and mullet were important resources and were harvested at the eastern extent of the New River. Examples of their hunting and fishing technology can be seen in the form of weights for fishing nets, bone projectile points, and shark teeth that were used as knives. </p>
<p> <strong>Hunting and fishing also drew early tourists to Fort Lauderdale. </strong> These tourists describe the New River as a fishing wonderland with schools of fish being chased up the river by porpoises and sharks. <NAME> recounted a dramatic moment when a bull shark killed a large tarpon right in front of his house.</p>
<p><img src="images/exhibit19.jpg" style="float:left; margin-right:10px" alt="A woman and her prized catch in front of the New River.<br/>
Courtesy of the International Game Fishing Association" /></p>
<p><img src="images/exhibit24.jpg" style="float:right; margin-left:10px" alt=" " /></p>
</div>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include '../footer.php'; ?>
<file_sep><?php
include 'appHeader.php';
/******** Delete a file *******/
if(isset($_GET['delete'])){
$delete = mysqli_real_escape_string($dblink, $_GET['delete']);
if(unlink($uploadDirectory.$delete))
$msg = $delete . " was deleted successfully.";
else{
$msg = "Unable to delete " . $delete;
$err = true;
}
}
/******** Show list of files in directory *******/
if ($handle = opendir($uploadDirectory)) {
$dirArray = scandir($uploadDirectory,2);
$thelist = "";
foreach($dirArray as $file){
if ($file != "." && $file != ".."){
$thelist .= '<div class="row upload-item">
<div class="col-sm-10"> <a href="'.$rootUploadDirectory.$region."/".$file.'" target="_blank">'.$file.'</a></div>
<div class="col-sm-2"> <a class="btn btn-sm btn-primary" href="?delete='.$file.'"
onclick="return confirm(\'Are you sure you want to delete this file?\');"><i class="fa fa-trash-o fa-lg"></i></a></div></div>';
}
}
closedir($handle);
}
$pageTitle = "File Upload";
include $header;
?>
<div class="container-fluid">
<div class="page-header">
<h1><?php echo $pageTitle ?></h1>
</div>
<div class="row">
<div class="col-sm-6 col-sm-push-3">
<form enctype="multipart/form-data" action="processUpload.php" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<!-- Name of input element determines name in $_FILES array -->
<div class="text-center row">
<div class="form-group">
<label for="file" class="control-label">Upload New File</label>
<input name="userfile" type="file" id="file" class="form-control" />
</div>
<input type="submit" value="Upload" class="btn btn-primary" />
</div><!-- /.row -->
</form>
<?php
$class = ($err==true) ? "alert-danger" : "alert-success";
if(isset($msg))
echo "<div class=\"text-center alert $class\"> $msg </div>";
?>
<h3 class="text-center">Contents of /uploads/<?php echo $region ?></h3>
<div class="box box-dash">
<?php echo $thelist ?>
</div>
</div>
</div> <!-- /.row -->
<?php include $footer; ?><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Destination Archaeology Resource Center<?php if($pageTitle){echo " - ".$pageTitle;} ?></title>
<meta name="DESCRIPTION" content="">
<meta name="KEYWORDS" content="">
<link rel="stylesheet" type="text/css" href="/style.css" media="all" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script type="text/javascript" src="http://www.flpublicarchaeology.org/js/fpan.js"></script>
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-7301672-16']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body id="radial-center">
<div id="main">
<div id="header">
<img src="http://www.destinationarchaeology.org/images/header.jpg" alt="Destination: Archaeology Resource Center" />
</div>
<div id="navbar">
<ul class="menu">
<li><a href="/news">News</a> </li>
<li><a href="/exhibits">Exhibits</a> </li>
<li><a href="/education">Education</a> </li>
<li>
<a href="#">Virtual Tours</a>
<ul>
<li><a href="/tours/arcadia.php">Arcadia Mill</a></li>
<li><a href="/tours/templemound.php">Ft. Walton Temple Mound</a></li>
</ul>
</li>
<li><a href="/programs">Programs</a> </li>
<li><a href="/geotrail">GeoTrail</a> </li>
<li><a href="http://fpan.us/nwrc/volunteer.php">Lab</a> </li>
<ul>
</div>
<div class="clearFloat"></div>
<file_sep><?php
if (!defined('WEBPATH')) die();
$firstPageImages = setThemeColumns('2', '6');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s').' GMT');
$pageTitle = "";
include 'header.php';
zp_apply_filter("theme_head");
?>
<!-- Main Left Side -->
<div id="left_side">
<div id="navbar">
<div id="navbar_top"> </div>
<div id="album_container">
<ul class="album_ul">
<li><a href="http://flpublicarchaeology.org/civilwar">Home</a></li>
<li><a href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=http:%2F%2Fwww.flpublicarchaeology.org%2Fcivilwar%2Fsites.kmz&sll=37.0625,-95.677068&sspn=58.72842,135.263672&ie=UTF8&t=h&ll=28.960089,-83.748779&spn=5.689017,9.371338&z=7" target="_blank">Map of Sites</a></li>
<li><a href="http://flpublicarchaeology.org/links.php#civilwar">Sesquicentennial Links</a></li>
</ul>
<img src="http://www.flpublicarchaeology.org/images/nav_div.png" width="180" height="4" alt="divider"/>
<?php printAlbumMenuList("list-top","","","","album_ul","","");?>
</div>
<div id="navbar_bottom"> </div>
</div>
<div style="margin-left:29px">
<a href="https://secure.uwf.edu/give/index.cfm?action=viewFund&fund=6&search=fpan" target="_blank">
<img src="http://flpublicarchaeology.org/images/donate_button_green.png" /></a></div>
<br/>
<div style="margin-left:5px;">
<p align="center">
<a href="http://www.flheritage.com/preservation/trails/civilwar/index.cfm" target="_blank">
<img src="http://flpublicarchaeology.org/civilwar/images/heritageTrail.jpg" />
</a>
</p>
</div>
<!-- <table class="newsletter_table" cellpadding="0" cellspacing="0">
<tr>
<th class="newsletter_header"></th>
</tr>
<tr>
<td class="newsletter_table_mid">
</td>
</tr>
<tr>
<td class="newsletter_bottom"></td>
</tr>
</table>-->
</div>
<!-- Main Middle -->
<div id="middle">
<table class="lg_table" cellpadding="0" cellspacing="0">
<tr>
<th class="lg_header"><h1><?php echo getGalleryTitle(); ?></h1></th>
</tr>
<tr>
<td class="table_mid"><h2 align="center"><a href="http://flpublicarchaeology.org/DCWApp" target="_blank" style="color:#000">Destination: Civil War iPhone app now available!</a><br />
</h2>
<p align="center"><img src="http://flpublicarchaeology.org/iphone/images/DCW_screens.png" /> </p>
<hr/>
<p><strong>DESTINATION: CIVIL WAR is a listing of Civil War heritage sites that are open for the public to visit. View a map of all of these sites with <a href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=http:%2F%2Fwww.flpublicarchaeology.org%2Fcivilwar%2Fsites.kmz&sll=37.0625,-95.677068&sspn=58.72842,135.263672&ie=UTF8&t=h&ll=28.960089,-83.748779&spn=8.511294,16.907959&z=7" class="dark">Google Maps</a> or download the <a href="http://www.flpublicarchaeology.org/civilwar/sites.kmz" class="dark">Google Earth</a> file. </strong></p>
<p>On January 10, 1861 Florida seceded from the Union and was soon involved in a Civil War that changed forever our nation and its people. Though far from the main theaters of war, Florida saw conflict, suffering, and loss within its borders and on distant battlefields where native sons were sent to fight. Florida’s economy was at first crippled by an effective naval blockade, and soon transformed to support the Confederate war effort by supplying critical staples such as salt and beef. </p>
<div align="center"> <img src="images/home-logo2.jpg" class="padded" /></div>
<p>
In commemoration of the 150th anniversary of the Civil War in Florida, we have developed this Web site as a guide to public places in Florida that tell the story of the Civil War and the movement to preserve its lessons. Many are significant archaeological sites. All are worthy of a visit and respectful reflection. Included are battlefields, fortifications, plantations, arsenals, the state capitol, cemetery plots, monuments, shipwrecks, and museum exhibits. We invite you to include these places into your travels whether you live in Florida or are planning a vacation or business trip to the state.</p><?php printAdminToolbox(); ?> </p>
<p>
Content for this web resource has been developed by FPAN Executive Director Dr. <NAME>, with the collaboration of <NAME> of Tallahassee and the assistance of FPAN staff throughout the state. We would also like to thank Dr. <NAME> of Dunedin, Florida, for sharing with us information on monuments that he has collected through the years.
</p>
</td>
</tr>
<tr>
<td class="lg_bottom"></td>
</tr>
</table>
</div>
<div class="clearFloat"></div>
<?php include 'footer.php'; ?>
<file_sep><?php
include '../header.php';
$employeeSql = "SELECT * FROM Employees;";
$listEmployees = mysql_query($employeeSql);
//Submission has been confirmed, add to database
if($_POST['confirmSubmission'] == true){
$formVars = $_SESSION['formVars'];
$activityDate = $formVars['year'] ."-". $formVars['month'] ."-". $formVars['day'];
$typeMedia = $formVars['typeMedia'];
$typeContact = $formVars['typeContact'];
$comments = $formVars['comments'];
//Insert new Activity ID
$sql = "INSERT INTO Activity VALUES (NULL);";
if(!mysql_query($sql)){
$err = true;
$msg .= ' Error: ' . mysql_error();
}
//Insert activity info with new Activity ID
$sql = "INSERT INTO PressContact (id, submit_id, activityDate, typeMedia, typeContact, comments)
VALUES (LAST_INSERT_ID(), '$_SESSION[my_id]', '$activityDate', '$typeMedia', '$typeContact', '$comments');";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error();
}
//For each staff member checked, insert entry into EmployeeActivity to associate that employee with this activity
foreach($formVars['staffInvolved'] as $staff){
$sql = "INSERT INTO EmployeeActivity VALUES ($staff, LAST_INSERT_ID());";
if(!mysql_query($sql)){
$err = true;
$msg .= 'Error: ' . mysql_error();
}
}
//If there were no erorrs while inserting: Clear temporary event array, display success message
if($err != true){
$_SESSION['formVars'] = "";
$msg = "Activity was successfully logged!";
}
?>
<div class="summary">
<br/><br/>
<?php echo "<h3>".$msg."</h3>"; ?>
<br/><br/><br/><br/>
<a href="<?php echo $_SERVER['../PHP_SELF']; ?>">Enter another Press Contact activity</a> or
<a href="../main.php">return to main menu</a>.
<br/><br/>
</div>
<?php } //End confirmed submission IF ?>
<?php //Form has been submitted. Process form submission.
if(isset($_POST['submit']) && !isset($_POST['confirmSubmission'])){
// Sanitize Data
$formVars['month'] = mysql_real_escape_string(addslashes($_POST['month']));
$formVars['day'] = mysql_real_escape_string(addslashes($_POST['day']));
$formVars['year'] = mysql_real_escape_string(addslashes($_POST['year']));
$formVars['typeMedia'] = mysql_real_escape_string(addslashes($_POST['typeMedia']));
$formVars['typeContact'] = mysql_real_escape_string(addslashes($_POST['typeContact']));
$formVars['staffInvolved'] = $_POST['staffInvolved'];
$formVars['comments'] = mysql_real_escape_string(addslashes($_POST['comments']));
$activityDate = $formVars['year'] ."-". $formVars['month'] ."-". $formVars['day'];
$_SESSION['formVars'] = $formVars;
?>
<br/><br/>
<div class="summary">
<br/>
<br/>
<div style="text-align:left; margin-left:100px;">
<?php
echo "<strong>Date:</strong> " .$activityDate."<br/>";
echo "<strong>Media Type:</strong> ".$formVars['typeMedia']."<br/>";
echo "<strong>Contact Type:</strong> ".$formVars['typeContact']."<br/>";
echo "<strong>The staff involved:</strong> <br/>";
while($employee = mysql_fetch_array($listEmployees)){
$employeeName = $employee['firstName']." ".$employee['lastName'];
if(in_array($employee['id'], $formVars['staffInvolved']))
echo "<span style=\"margin-left:10px;\">". $employeeName."</span><br/>";
}
echo "<strong>Comments:</strong> ".$formVars['comments']."<br/>";
?>
</div>
<br/><br/>
If any of this is incorrect, please
<a href="<?php echo $_SERVER['../PHP_SELF']; ?>"> go back and correct it</a>.
<br/><br/>
Otherwise, please confirm your submission:
<br/><br/>
<form id="submissionForm" method="post" action="<?php echo $_SERVER['../PHP_SELF']; ?>" >
<input type="hidden" name="confirmSubmission" value="true" />
<input type="submit" name="submit" value="Confirm" />
</form>
<br/>
<br/>
</div>
<?php }elseif(!isset($_POST['confirmSubmission'])){ //Form hasn't been submitted yet. Display form. ?>
<form id="pressContact" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Press Contact</h2>
<p>Please fill out the information below to log this activity.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Date </label>
<span>
<input id="element_1_1" name="month" class="element text" size="2" maxlength="2" value="<?php echo $formVars['month']; ?>" type="text"> /
<label for="element_1_1">MM</label>
</span>
<span>
<input id="element_1_2" name="day" class="element text" size="2" maxlength="2" value="<?php echo $formVars['day']; ?>" type="text"> /
<label for="element_1_2">DD</label>
</span>
<span>
<input id="element_1_3" name="year" class="element text" size="4" maxlength="4" value="<?php echo $formVars['year']; ?>" type="text">
<a class="red"> *</a>
<label for="element_1_3">YYYY</label>
</span>
<span id="calendar_1">
<img id="cal_img_1" class="datepicker" src="../images/calendar.gif" alt="Pick a date.">
</span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</li>
<li id="li_3" >
<label class="description" for="element_3">Type of Media </label>
<div>
<select class="element select medium" id="element_3" name="typeMedia" required="required">
<option value="" selected="selected"></option>
<option value="Television" <?php if($formVars['typeMedia'] == "Television") echo 'selected="selected"';?> >Television</option>
<option value="Radio" <?php if($formVars['typeMedia'] == "Radio") echo 'selected="selected"';?>>Radio</option>
<option value="Magazine" <?php if($formVars['typeMedia'] == "Magazine") echo 'selected="selected"';?>>Magazine</option>
<option value="Newspaper" <?php if($formVars['typeMedia'] == "Newspaper") echo 'selected="selected"';?>>Newspaper</option>
<option value="Web" <?php if($formVars['typeMedia'] == "Web") echo 'selected="selected"';?>>Web</option>
<option value="Multiple Media Types" <?php if($formVars['typeMedia'] == "Multiple Media Types") echo 'selected="selected"';?>>Multiple Media Types</option>
<option value="Other"<?php if($formVars['typeMedia'] == "Other") echo 'selected="selected"';?> >Other</option>
</select>
<a class="red">*</a></div>
<p class="guidelines" id="guide_3"><small>Choose the most appropriate media type. If this contact involves more than one media type, please select "Multiple Media Types".</small></p>
</li>
<li id="li_4" >
<label class="description" for="element_4">Type of Contact </label>
<div>
<select class="element select medium" id="element_4" name="typeContact" required="required">
<option value="" selected="selected"></option>
<option value="Press Release" <?php if($formVars['typeContact'] == "Press Release") echo 'selected="selected"';?>>Press Release</option>
<option value="Interview" <?php if($formVars['typeContact'] == "Interview") echo 'selected="selected"';?> >Interview</option>
<option value="Announcement" <?php if($formVars['typeContact'] == "Announcement") echo 'selected="selected"';?> >Announcement</option>
<option value="Other" <?php if($formVars['typeContact'] == "Other") echo 'selected="selected"';?> >Other</option>
</select>
<a class="red">*</a></div>
</li>
<li id="li_5" >
<?php include("../staffInvolved.php"); ?>
</li>
<li id="li_2" >
<label class="description" for="element_2">Comments </label>
<div>
<textarea id="element_2" name="comments" class="element textarea medium"><?php echo $formVars['comments']; ?></textarea>
</div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
<?php } //Close else ?>
<div id="footer"> </div>
</div>
<img id="bottom" src="../images/bottom.png" alt="">
</body>
</html> | 73c060907bf13e85ae5070349709e7aa9014b776 | [
"JavaScript",
"PHP"
]
| 229 | PHP | jasontk19/fpan_web | 5c7089f319a69bf812caa501124d0a2113d517ad | a7e46d86fe27a67579c56448d428b3e7d5e25d77 |
refs/heads/master | <file_sep>/**
*Name: <NAME>
*Designation: Software Engineer
*Date: 02-Dec-20 2:28 PM
*/
/*var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
const cors = require('cors');
app.use(cors());
server.listen(8890);
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
// app.set('view engine', 'ejs');
io.on('connection', function (socket) {
console.log("client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, data) {
console.log("mew message add in queue "+ data['message'] + " channel");
socket.emit(channel, data);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});*/
/*const express = require('express')
const path = require('path')
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
console.log("outside io");
io.on('connection', function(socket){
console.log('User Conncetion');
socket.on('connect user', function(user){
console.log("Connected user ");
io.emit('connect user', user);
});
socket.on('on typing', function(typing){
console.log("Typing.... ");
io.emit('on typing', typing);
});
socket.on('chat message', function(msg){
console.log("Message " + msg['message']);
io.emit('chat message', msg);
});
});
http.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});*/
var baseURL = getBaseURL(); // Call function to determine it
var socketIOPort = 8080;
var socketIOLocation = baseURL + socketIOPort; // Build Socket.IO location
var socket = io.connect(socketIOLocation);
// Build the user-specific path to the socket.io server, so it works both on 'localhost' and a 'real domain'
function getBaseURL()
{
baseURL = location.protocol + "//" + location.hostname + ":" + location.port;
return baseURL;
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function index()
{
if (is_null($this->alal)) {
return view('welcome');
}
return $this->alal['name'];
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Chat;
use App\Events\ChatEvent;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
class ChatController extends Controller
{
public function index(){
$chat = [
'message'=>'hello world',
'id'=>3
];
broadcast(new ChatEvent((object)$chat))->toOthers();
return $chat;
//return view('chat');
}
public function sendMessage(Request $request){
$redis = Redis::connection();
$data = ['message' => $request->message, 'user' => $request->user];
$redis->publish('message', json_encode($data));
return response()->json([$data]);
}
}
| 31de7fa3a461837b0213a06110bc9740ab9349a1 | [
"JavaScript",
"PHP"
]
| 3 | JavaScript | alauddin020/html | 2665d28ee5744945ab18c4d2f9bf09aec6403d89 | 0a82e8a5c7e36fe8cc5feee0345d6a8883bd2053 |
refs/heads/master | <file_sep>package com.itcast.whw.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.itcast.whw.tool.ActivityCollector;
/**
* 所有活动的基类
*/
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
}
<file_sep>package com.itcast.whw;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.Toast;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.TextBadgeItem;
import com.itcast.whw.activity.BaseActivity;
import com.itcast.whw.activity.CollectionActivity;
import com.itcast.whw.activity.SearchActivity;
import com.itcast.whw.activity.ShortCutActivity;
import com.itcast.whw.adapter.SectionPageAdapter;
import com.itcast.whw.fragment.HomeFragment;
import com.itcast.whw.fragment.MineFragment;
import com.itcast.whw.fragment.ToolFragment;
import com.itcast.whw.tool.PermissionPageUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* APP主界面
*/
public class MainActivity extends BaseActivity {
private Toolbar toolBar;
private ViewPager viewPager;
private BottomNavigationBar bottom_navigation_bar;
private boolean isEmptyCollect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
HashSet<Map<String,Integer>> collect_info = (HashSet<Map<String,Integer>>)intent.getSerializableExtra("collect_info");
if(collect_info!=null){
isEmptyCollect = collect_info.isEmpty();
}
initView();
setSupportActionBar(toolBar);
//去除ToolBar的标题
getSupportActionBar().setDisplayShowTitleEnabled(false);
List<Fragment> fragmentList = new ArrayList<>();
HomeFragment homeFragment = new HomeFragment();
ToolFragment toolFragment = new ToolFragment();
MineFragment mineFragment = new MineFragment();
fragmentList.add(homeFragment);
fragmentList.add(toolFragment);
fragmentList.add(mineFragment);
viewPager.setAdapter(new SectionPageAdapter(getSupportFragmentManager(), fragmentList));
//监听ViewPager页面变化
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
/**
* 在屏幕滚动过程中不断调用
* @param position 页面翻动成功后,i表示其当前页面
* @param positionOffset 当前页面滑动比例
* @param positionOffsetPixels 当前页面滑动像素
*/
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
/**
* 翻动页面调用此方法
* @param position 代表哪个页面被选中
*/
@Override
public void onPageSelected(int position) {
bottom_navigation_bar.selectTab(position);
}
/**
* 这个方法在手指操作屏幕的时候发生变化。有三个值:0(END),1(PRESS) , 2(UP) 。
* 当用手指滑动翻页时,手指按下去的时候会触发这个方法,state值为1,手指抬起时,
* 如果发生了滑动(即使很小),这个值会变为2,然后最后变为0 。总共执行这个方法三次。
* 一种特殊情况是手指按下去以后一点滑动也没有发生,这个时候只会调用这个方法两次,state值分别是1,0 。
* @param state
*/
@Override
public void onPageScrollStateChanged(int state) {
}
});
if(ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull final String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 1:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示")
.setMessage("存储权限请求被拒绝,这将会导致应用可能无法正常使用,是否前往设置页面手动赋予权限?")
.setPositiveButton("手动授权", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
PermissionPageUtils permissionPageUtils = new PermissionPageUtils(MainActivity.this);
permissionPageUtils.jumpPermissionPage();
}
})
.show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar, menu);
MenuItem menuItem = menu.findItem(R.id.searchView);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
//搜索图标是否显示在搜索框内
searchView.setIconifiedByDefault(true);
//设置搜索框展开时是否显示提交按钮,可不显示
searchView.setSubmitButtonEnabled(true);
//让键盘的回车键设置成搜索
searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
//搜索框是否展开,false表示展开
searchView.setIconified(false);
searchView.onActionViewExpanded();
searchView.clearFocus();
//设置提示词
searchView.setQueryHint("搜索功能...");
EditText editText = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
editText.setFocusable(false);
editText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SearchActivity.class));
}
});
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.shortcut://快捷方式
startActivity(new Intent(this,ShortCutActivity.class));
break;
case R.id.all_functions://快捷方式
startActivity(new Intent(this,CollectionActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
private void initView() {
toolBar = (Toolbar) findViewById(R.id.toolBar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
bottom_navigation_bar = findViewById(R.id.bottom_navigation_bar);
/**
* 导航基础设置 包括按钮选中效果 导航栏背景色等
*/
bottom_navigation_bar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
@Override
public void onTabSelected(int position) {
viewPager.setCurrentItem(position);
}
@Override
public void onTabUnselected(int position) {
}
@Override
public void onTabReselected(int position) {
}
})
.setMode(BottomNavigationBar.MODE_FIXED)
.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
//.setActiveColor("#ffffff")//选中颜色
//.setInActiveColor("#2B2B2B")//未选中颜色
//.setBarBackgroundColor("#ffffff");//导航栏背景色
TextBadgeItem badgeItem = new TextBadgeItem()
.setBorderWidth(2)
.setTextColor(Color.BLACK)
.setBackgroundColor(Color.RED)
.setText("99");
/**
*添加导航按钮
*/
bottom_navigation_bar
.addItem(new BottomNavigationItem(R.mipmap.ic_launcher, "首页"))
.addItem(new BottomNavigationItem(R.mipmap.ic_launcher, "分类"))
.addItem(new BottomNavigationItem(R.mipmap.ic_launcher, "测试"))
.initialise();//initialise 一定要放在 所有设置的最后一项
}
}
<file_sep>package com.itcast.whw.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.baidu.mapapi.search.core.PoiInfo;
import com.itcast.whw.R;
import java.util.ArrayList;
import java.util.List;
/**
* 附近信息的适配器
*/
public class MapListAdapter extends BaseAdapter {
private List<PoiInfo> poiInfoList = new ArrayList<>();
private Context mContext;
public MapListAdapter(List<PoiInfo> poiInfoList, Context context) {
this.poiInfoList = poiInfoList;
this.mContext = context;
}
@Override
public int getCount() {
return poiInfoList.size();
}
@Override
public Object getItem(int position) {
return poiInfoList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
ViewHolder viewHolder = null;
if (convertView == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.map_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv_name = view.findViewById(R.id.tv_name);
viewHolder.tv_address = view.findViewById(R.id.tv_address);
view.setTag(viewHolder);
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
//设置数据
PoiInfo poiInfo = poiInfoList.get(position);
viewHolder.tv_name.setText(poiInfo.name);
viewHolder.tv_address.setText(poiInfo.address);
return view;
}
class ViewHolder {
private TextView tv_name;
private TextView tv_address;
}
}
<file_sep>package com.itcast.whw.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.itcast.whw.R;
import com.itcast.whw.adapter.ShortCutAdapter;
import java.util.ArrayList;
import java.util.List;
public class ShortCutActivity extends AppCompatActivity {
private Toolbar toolBar;
private RecyclerView recyclerView;
private List<String> strList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_short_cut);
initView();
setSupportActionBar(toolBar);
//初始化数据
getInitData();
//设置适配器
ShortCutAdapter adapter = new ShortCutAdapter(strList);
recyclerView.setAdapter(adapter);
//设置布局管理器
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
}
private void initView() {
toolBar = (Toolbar) findViewById(R.id.toolBar);
recyclerView = findViewById(R.id.recyclerView);
}
/**
* 初始化数据
*/
public void getInitData() {
strList = new ArrayList<>();
for(int i = 0;i < 10;i++){
strList.add("校园外卖");
strList.add("表情制作");
strList.add("付费音乐下载");
strList.add("红包");
strList.add("汇率");
}
}
}
<file_sep>package com.itcast.whw.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import com.itcast.whw.MainActivity;
import com.itcast.whw.R;
import com.itcast.whw.adapter.CollectRecycleAdapter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 工具收藏界面
*/
public class CollectionActivity extends AppCompatActivity implements View.OnClickListener {
private Toolbar tool_bar;
private CollapsingToolbarLayout ctl_title;
private AppBarLayout abl_title;
private RecyclerView rv_collection;
private List<String> strList;
private FloatingActionButton collect_fab;
private CollectRecycleAdapter collect_adapter;
private SharedPreferences collect_info_sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection);
initView();
//初始化数据
getInitData();
setSupportActionBar(tool_bar);
ActionBar actionBar = getSupportActionBar();
//开启返回键
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
rv_collection.setLayoutManager(gridLayoutManager);
collect_adapter = new CollectRecycleAdapter(strList, this);
collect_adapter.setType(0);
rv_collection.setAdapter(collect_adapter);
collect_info_sp = getSharedPreferences("collect_info",MODE_PRIVATE);
HashSet<String> collect = (HashSet<String>)collect_info_sp.getStringSet("collect", null);
if(collect!=null){
for(String str: collect){
Log.d("CollectionActivity", str);
}
collect_adapter.setCollect_set(collect);
collect_adapter.setFunctionAble(true);
collect_adapter.setType(0);
collect_adapter.notifyDataSetChanged();
}
}
private void initView() {
tool_bar = (Toolbar) findViewById(R.id.tool_bar);
ctl_title = (CollapsingToolbarLayout) findViewById(R.id.ctl_title);
abl_title = (AppBarLayout) findViewById(R.id.abl_title);
rv_collection = (RecyclerView) findViewById(R.id.rv_collection);
collect_fab = (FloatingActionButton) findViewById(R.id.collect_fab);
collect_fab.setOnClickListener(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//后退键的点击事件
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
/**
* 初始化数据
*/
public void getInitData() {
strList = new ArrayList<>();
strList.add("查看附近");
strList.add("表情制作");
strList.add("付费音乐下载");
strList.add("红包");
strList.add("汇率转换");
strList.add("画图");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.collect_fab:
//实现收藏功能
HashSet<String> collect_set = collect_adapter.getCollect_set();
if(collect_set!=null){
for(String str: collect_set){
Log.d("CollectionActivity", str);
}
collect_adapter.setFunctionAble(true);
collect_adapter.notifyDataSetChanged();
}
Intent intent = new Intent(CollectionActivity.this,MainActivity.class);
collect_info_sp = getSharedPreferences("collect_info",MODE_PRIVATE);
SharedPreferences.Editor editor = collect_info_sp.edit().putStringSet("collect", collect_set);
editor.apply();
startActivity(intent);
finish();
overridePendingTransition(R.anim.fade_in_all,R.anim.fade_out_all);
break;
}
}
}
<file_sep>package com.itcast.whw.activity.currency_conversion;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.itcast.whw.R;
/**
* 汇率转换工具
*/
public class CurrencyConversionActivity extends AppCompatActivity implements View.OnClickListener {
private Toolbar currency_toolbar;
private Spinner spinner_left;
private Spinner spinner_right;
private EditText et_money_j;
private Button btn_conversion_j;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_conversion);
initView();
setSupportActionBar(currency_toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
private void initView() {
currency_toolbar = (Toolbar) findViewById(R.id.currency_toolbar);
spinner_left = (Spinner) findViewById(R.id.spinner_left);
spinner_right = (Spinner) findViewById(R.id.spinner_right);
et_money_j = (EditText) findViewById(R.id.et_money_j);
btn_conversion_j = (Button) findViewById(R.id.btn_conversion_j);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.money_spinner,android.R.layout.simple_list_item_1);
spinner_left.setAdapter(adapter);
spinner_right.setAdapter(adapter);
//注册监听
//TODO 未完工,待续。。。。
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_conversion_j:
break;
}
}
}
<file_sep>package com.itcast.whw.adapter;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.itcast.whw.R;
import com.itcast.whw.tool.LogUtil;
import java.util.List;
/**
* 快捷方式界面的适配器
*/
public class ShortCutAdapter extends RecyclerView.Adapter<ShortCutAdapter.ViewHolder> {
private List<String> strList;
public ShortCutAdapter(List<String> strList){
this.strList = strList;
}
static class ViewHolder extends RecyclerView.ViewHolder{
TextView tv_function_head;
TextView tv_function;
RelativeLayout rl_layout;
RelativeLayout rl;
public ViewHolder(View itemView) {
super(itemView);
tv_function_head = itemView.findViewById(R.id.tv_function_head);
tv_function = itemView.findViewById(R.id.tv_function);
rl_layout = itemView.findViewById(R.id.rl_layout);
rl = itemView.findViewById(R.id.rl);
}
}
@Override
public ShortCutAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shortcut_item,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ShortCutAdapter.ViewHolder holder, int position) {
String str = strList.get(position);
//截取第一个汉字
String substring = str.substring(0, 1);
holder.tv_function_head.setText(substring);
holder.tv_function.setText(str);
if(position % 2 == 0){
//偶数item
holder.rl_layout.setBackgroundColor(Color.parseColor("#ffffff"));
}else{
//奇数item
holder.rl_layout.setBackgroundColor(Color.parseColor("#e0e8e8"));
holder.rl.setBackgroundResource(R.drawable.background_pink_light);
holder.tv_function_head.setBackgroundResource(R.drawable.background_pink);
}
}
@Override
public int getItemCount() {
return strList.size();
}
}
<file_sep>package com.itcast.whw.tool;
import android.net.Uri;
/**
* 数据接口类
*/
public class API {
/**
* 协议
*/
private static final String AGGREMENT = "http";
/**
* ip地址
*/
private static final String LOCALHOST = "172.16.17.32";
/**
* 端口号
*/
private static final String PORT = "8080";
/**
* url地址
*/
private static String URL = AGGREMENT + "://" + LOCALHOST + ":" + PORT + "/";
/**
* 用户注册接口
*/
public static final String API_REGISTER = URL + "register/";
/**
* 用户登录接口
*/
public static final String API_LOGIN = URL + "login/";
}
| 03174c66faa5ac366b68c66fc05952e2aeb2d2e3 | [
"Java"
]
| 8 | Java | notaorganizationname/DoraemonsPocket | 1f23b077490abbe20f275803eddfa49e3b3d1a3a | 5fccaee6cdc276e6ca294ec83886eb942e65cae6 |
refs/heads/master | <file_sep>package com.example.agavacovid;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import java.io.IOException;
import java.net.DatagramPacket;
/**
* @author <NAME>
* @author <NAME>
*/
public class MulticastListenerThread extends MulticastThread {
public MulticastListenerThread(MainActivity activity, String multicastIP, int multicastPort) {
super("MulticastListenerThread", activity, multicastIP, multicastPort, new Handler());
}
@SuppressLint("NewApi")
@Override
public void run() {
super.run();
DatagramPacket packet = new DatagramPacket(new byte[512], 512);
while (this.getRunning()) {
packet.setData(new byte[1024]);
try {
if (multicastSocket != null)
multicastSocket.receive(packet);
else
break;
} catch (IOException ignored) {
continue;
}
String data = new String(packet.getData()).trim();
//Desencriptar datos
//
final String consoleMessage = data;
//this.getHandler().post(() -> getActivity().comprobarIDsContagiados(data));
this.getHandler().post(() -> getActivity().comprobarHash(consoleMessage));
}
if (multicastSocket != null)
this.multicastSocket.close();
}
}
<file_sep>package com.example.agavacovid;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.widget.Toast;
import com.example.agavacovid.persistence.AgavaContract;
import com.example.agavacovid.persistence.DbHelper;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* @author <NAME>
* @author <NAME>
*/
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
int REQUEST_ENABLE_BLUETOOTH=1;
private MulticastListenerThread multicastListenerThread;
private boolean isListening = false;
private WifiManager.MulticastLock wifiLock;
private List<String> listaHashes;
private static int estado = 0;
private DbHelper dbHelper;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setItemBackgroundResource(R.drawable.background_selector);
this.getSupportActionBar().hide();
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
dbHelper= new DbHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(AgavaContract.IdsPropios.ID_EF, "910a5497fa536069da1e00aecb93e45af7943b93789933d9b61cf814b35533eb");
values.put(AgavaContract.IdsPropios.CLAVE_GEN, "MC4CAQAwBQYDK2VwBCIEIPtCxE+YheK+57B6xfjrGhjeYzc2MUkOGlaynnVEO/L8");
values.put(AgavaContract.IdsPropios.FECHA_GEN, "2021-05-26 17:00:00"); //yyyy-MM-dd HH:mm:ss
db.insert(AgavaContract.IDS_PROPIOS_TABLA, null, values);
values.clear();
values.put(AgavaContract.IdsPropios.ID_EF, "0ab330eb9fae7fcca4ed7f0f65f018235693969d5cdd4720f437ea43004df0fe");
values.put(AgavaContract.IdsPropios.CLAVE_GEN, "910a5497fa536069da1e00aecb93e45af7943b93789933d9b61cf814b35533eb");
values.put(AgavaContract.IdsPropios.FECHA_GEN, "2021-05-26 17:15:00");
db.insert(AgavaContract.IDS_PROPIOS_TABLA, null, values);
values.clear();
values.put(AgavaContract.IdsPropios.ID_EF, "f64757888e6330d08dbfb0d2f48eca29df715adc8fa9d86fd97d48003a1cfe12");
values.put(AgavaContract.IdsPropios.CLAVE_GEN, "0ab330eb9fae7fcca4ed7f0f65f018235693969d5cdd4720f437ea43004df0fe");
values.put(AgavaContract.IdsPropios.FECHA_GEN, "2021-05-26 17:30:00");
db.insert(AgavaContract.IDS_PROPIOS_TABLA, null, values);
values.clear();
values.put(AgavaContract.IdsAjenos.ID_EF, "8a19a2c9bd2408ab43862183bea9e3b1601b4f87a1d81162d2bd6618a4104db7");
values.put(AgavaContract.IdsAjenos.FECHA_REC, "2021-06-16 17:30:00");
db.insert(AgavaContract.IDS_AJENOS_TABLA, null, values);
dbHelper.close();
listaHashes = new ArrayList<>();
if (this.isListening) {
stopListening();
} else {
startListening();
}
bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
if(!bluetoothAdapter.isEnabled()){
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
}
@Override
protected void onStop() {
super.onStop();
stopListening();
}
@Override
protected void onRestart() {
super.onRestart();
recreate();
}
private void startListening() {
if (!isListening) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
setWifiLockAcquired(true);
this.multicastListenerThread = new MulticastListenerThread(this, "172.16.58.3"/*La IP del multicast*/, 4446 /*Puerto de recepcion*/);
multicastListenerThread.start();
isListening = true;
} else {
outputErrorToConsole(getString(R.string.error_wifi));
}
}
}
void stopListening() {
if (isListening) {
isListening = false;
stopThreads();
setWifiLockAcquired(false);
}
}
private void setWifiLockAcquired(boolean acquired) {
if (acquired) {
if (wifiLock != null && wifiLock.isHeld())
wifiLock.release();
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi != null) {
this.wifiLock = wifi.createMulticastLock("MulticastTester");
wifiLock.acquire();
}
} else {
if (wifiLock != null && wifiLock.isHeld())
wifiLock.release();
}
}
private void stopThreads() {
if (this.multicastListenerThread != null)
this.multicastListenerThread.stopRunning();
}
public void outputErrorToConsole(String errorMessage) {
Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show();
}
@SuppressLint("NewApi")
public void comprobarHash(String message) {
String[] arrSplit = message.split(",");
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
StringBuffer result = new StringBuffer();
byte[] hash = digest.digest(arrSplit[0].getBytes());
for (byte byt : hash) result.append(Integer.toString((byt & 0xff) + 0x100, 16).substring(1));
String hashString = result.toString();
listaHashes.add(hashString);
if(comprobarIDsContagiados()){
if(estado == 0){
estado = 1;
recreate();
}
}
}
public boolean comprobarIDsContagiados(){
db= dbHelper.getReadableDatabase();
String[] projection = {
BaseColumns._ID,
AgavaContract.IdsAjenos.ID_EF,
AgavaContract.IdsAjenos.FECHA_REC,
};
Cursor cursor = db.query(AgavaContract.IDS_AJENOS_TABLA, projection,
null, null, null, null, null);
List<String> listaIdsAjenosBD = new ArrayList<>();
while(cursor.moveToNext()) {
String idEf = cursor.getString(
cursor.getColumnIndexOrThrow(AgavaContract.IdsAjenos.ID_EF));
listaIdsAjenosBD.add(idEf);
}
cursor.close();
return !Collections.disjoint(listaHashes, listaIdsAjenosBD); //true si hay interseccion, false sino
}
public static int getEstado(){
return estado;
}
public static void setEstado(int estado){
MainActivity.estado = estado;
}
}<file_sep>package com.example.agavacovid.bluetooth;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.provider.BaseColumns;
import com.example.agavacovid.persistence.AgavaContract;
import com.example.agavacovid.persistence.DbHelper;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* @author <NAME>
* @author <NAME>
*/
public class ClientBTClass extends Thread {
private BluetoothDevice device;
private BluetoothSocket socket;
private static final String APP_NAME = "AgavaCOVID";
private static final UUID MY_UUID=UUID.fromString("b485f10d-9b3d-4682-b779-9d69ec2a2db5");
private SendReceive sendReceive;
private Context context;
private Handler handler;
static final int STATE_LISTENING = 1;
static final int STATE_CONNECTING=2;
static final int STATE_CONNECTED=3;
static final int STATE_CONNECTION_FAILED=4;
static final int STATE_MESSAGE_RECEIVED=5;
public ClientBTClass(BluetoothDevice device1, Context context, Handler handler) {
device = device1;
this.context = context;
this.handler = handler;
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run()
{
super.run();
try {
socket.connect();
Message message=Message.obtain();
message.what=STATE_CONNECTED;
handler.sendMessage(message);
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] projection = {
BaseColumns._ID,
AgavaContract.IdsPropios.ID_EF,
AgavaContract.IdsPropios.CLAVE_GEN,
AgavaContract.IdsPropios.FECHA_GEN,
};
Cursor cursor = db.query(
AgavaContract.IDS_PROPIOS_TABLA, // The table to query
projection, // The array of columns to return (pass null to get all)
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
Map<Date, String> idsfecha = new HashMap<>();
while(cursor.moveToNext()) {
String idEf = cursor.getString(
cursor.getColumnIndexOrThrow(AgavaContract.IdsPropios.ID_EF));
String fechagen = cursor.getString(
cursor.getColumnIndexOrThrow(AgavaContract.IdsPropios.FECHA_GEN));
Calendar c= Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //2021-05-26 17:00:00
try {
c.setTime(sdf.parse(fechagen));
} catch (ParseException e) {
e.printStackTrace();
}
idsfecha.put(c.getTime(), idEf);
}
List<Date> listafechas = new ArrayList<>();
for(Date d: idsfecha.keySet()){
listafechas.add(d);
}
Collections.sort(listafechas, new Comparator<Date>() {
public int compare(Date o1, Date o2) {
return o1.compareTo(o2);
}
});
OutputStream os = socket.getOutputStream();
os.write((idsfecha.get(listafechas.get(listafechas.size()-1)).getBytes()));
cursor.close();
dbHelper.close();
message = Message.obtain();
message.what=STATE_MESSAGE_RECEIVED;
handler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
Message message=Message.obtain();
message.what=STATE_CONNECTION_FAILED;
handler.sendMessage(message);
}
}
}<file_sep>package com.example.agavacovid;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
/**
* @author <NAME>
* @author <NAME>
*/
public class MulticastThread extends Thread {
private Boolean running = new Boolean(true);
private MainActivity activity;
private String multicastIP;
private int multicastPort;
private Handler handler;
MulticastSocket multicastSocket;
private InetAddress inetAddress;
MulticastThread(String threadName, MainActivity activity, String multicastIP, int multicastPort, Handler handler) {
super(threadName);
this.activity = activity;
this.multicastIP = multicastIP;
this.multicastPort = multicastPort;
this.handler = handler;
}
@Override
public void run() {
try {
WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int wifiIPInt = wifiInfo.getIpAddress();
byte[] wifiIPByte = new byte[]{
(byte) (wifiIPInt & 0xff),
(byte) (wifiIPInt >> 8 & 0xff),
(byte) (wifiIPInt >> 16 & 0xff),
(byte) (wifiIPInt >> 24 & 0xff)};
this.inetAddress = InetAddress.getByAddress(wifiIPByte);
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress);
this.multicastSocket = new MulticastSocket(multicastPort);
multicastSocket.setNetworkInterface(networkInterface);
multicastSocket.joinGroup(InetAddress.getByName(multicastIP));
} catch (BindException e) {
handler.post(new Runnable() {
@Override
public void run() {
activity.stopListening();
}
});
String error = "Error: Cannot bind Address or Port.";
if (multicastPort < 1024)
error += "\nTry binding to a port larger than 1024.";
outputErrorToConsole(error);
} catch (IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
activity.stopListening();
}
});
String error = "Error: Cannot bind Address or Port.\n"
+ "An error occurred: " + e.getMessage();
outputErrorToConsole(error);
e.printStackTrace();
}
}
String getLocalIP() {
return this.inetAddress.getHostAddress();
}
private void outputErrorToConsole(final String errorMessage) {
handler.post(new Runnable() {
@Override
public void run() {
activity.outputErrorToConsole(errorMessage);
}
});
}
void stopRunning() {
this.running = false;
}
public Boolean getRunning(){
return running;
}
public void setRunning(Boolean b){
running = b;
}
public MainActivity getActivity(){
return activity;
}
public void setActivity(MainActivity a){
activity = a;
}
public Handler getHandler(){
return handler;
}
public void setHandler(Handler h){
handler = h;
}
}<file_sep>package com.example.agavacovid.persistence;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* @author <NAME>
* @author <NAME>
*/
public class DbHelper extends SQLiteOpenHelper {
private static final String TAG = DbHelper.class.getSimpleName();
// Constructor
public DbHelper(Context context) {
super(context, AgavaContract.DB_NAME, null, AgavaContract.DB_VERSION);
}
@Override
public void onConfigure(SQLiteDatabase db){
db.setForeignKeyConstraintsEnabled(true);
}
// Llamado para crear la tabla
@Override
public void onCreate(SQLiteDatabase db) {
String dropTable = "DROP TABLE IF EXISTS ";
db.execSQL(dropTable + AgavaContract.IDS_PROPIOS_TABLA);
Log.d(TAG, "onCreate con SQL.");
String sql = String.format("CREATE TABLE %s" + //LOS MIOS
" (" +
" %s INTEGER PRIMARY KEY AUTOINCREMENT" + //El ID de la tabla
", %s TEXT" + // Id efimero
", %s TEXT" + // clave key
", %s TEXT" + // keydate
//ID lo metemos?
" )",
AgavaContract.IDS_PROPIOS_TABLA,
AgavaContract.IdsPropios._ID,
AgavaContract.IdsPropios.ID_EF,
AgavaContract.IdsPropios.CLAVE_GEN,
AgavaContract.IdsPropios.FECHA_GEN);
db.execSQL(sql);
sql = String.format("CREATE TABLE %s" + //LOS DE OTROS
" (" +
" %s INTEGER PRIMARY KEY AUTOINCREMENT" + //El ID de la tabla
", %s TEXT" + //id efimero recibido
", %s TEXT" + //fecha de recepcion del id externo
" )",
AgavaContract.IDS_AJENOS_TABLA,
AgavaContract.IdsAjenos._ID,
AgavaContract.IdsAjenos.ID_EF,
AgavaContract.IdsAjenos.FECHA_REC);
db.execSQL(sql);
}
// Llamado siempre que tengamos una nueva version
//Hecho solo para pruebas. De otro modo, se borrarian los IDs entre cada actualizacion
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Borramos la base de datos antigua
String dropTable = "DROP TABLE IF EXISTS ";
db.execSQL(dropTable + AgavaContract.IDS_PROPIOS_TABLA);
db.execSQL(dropTable + AgavaContract.IDS_AJENOS_TABLA);
// Creamos una base de datos nueva
onCreate(db);
Log.d(TAG, "onUpgrade");
}
}<file_sep># AgavaCOVID
Aplicación de rastreo de contactos desarrollada para el Trabajo de Fin de Grado de Ingeniería Informática de la Universidad de Valladolid.
<file_sep>package com.example.agavacovid.ui.information;
import android.graphics.text.LineBreaker;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.example.agavacovid.R;
/**
* @author <NAME>
* @author <NAME>
*/
public class InfoFragment extends Fragment {
private InfoViewModel infoViewModel;
private TextView descripcion;
private TextView tituloPolitica;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
infoViewModel =
new ViewModelProvider(this).get(InfoViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
descripcion = (TextView) root.findViewById(R.id.textView4);
tituloPolitica = (TextView) root.findViewById(R.id.textView5);
infoViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
descripcion.getText().toString().replace('\n', System.lineSeparator().toCharArray()[0]);
tituloPolitica.getText().toString().replace('\n', System.lineSeparator().toCharArray()[0]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
descripcion.setJustificationMode(LineBreaker.JUSTIFICATION_MODE_INTER_WORD);
}
}
});
return root;
}
}<file_sep>package com.example.agavacovid;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActionBar;
import android.app.DatePickerDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author <NAME>
* @author <NAME>
*/
public class SendActivity extends AppCompatActivity {
private View vistaEnvio;
private EditText code;
private EditText fecha;
private Button buttonConfirmacion;
private DatePickerDialog picker;
private static final long CATORCE_DIAS = 1209600000; //El numero del demonio son 14 dias en milisegundos T-T
BluetoothAdapter bluetoothAdapter;
int REQUEST_ENABLE_BLUETOOTH=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
if(!bluetoothAdapter.isEnabled()){
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
vistaEnvio = (View) findViewById(R.id.vistaEnvio);
code = (EditText) vistaEnvio.findViewById(R.id.outlinedTextField);
fecha = (EditText) vistaEnvio.findViewById(R.id.etPlannedDate);
buttonConfirmacion = (Button) vistaEnvio.findViewById(R.id.buttonConfirmacion);
fecha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(SendActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
fecha.setText(year + "-" + String.format("%02d", monthOfYear + 1) + "-" + String.format("%02d", dayOfMonth));
}
}, year, month, day);
picker.getDatePicker().setMaxDate(System.currentTimeMillis());
picker.getDatePicker().setMinDate(System.currentTimeMillis() - CATORCE_DIAS);
picker.show();
}
});
buttonConfirmacion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String fecharec;
if(code.getText().equals("")){
Toast.makeText(getApplicationContext(),
getString(R.string.mensaje_vacio), Toast.LENGTH_LONG).show();
}else {
if (code.getText().length() < 12) {
Toast.makeText(getApplicationContext(),
getString(R.string.mensaje_incompleto), Toast.LENGTH_LONG).show();
} else {
if(fecha.getText() ==null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fecharecdate = new Date();
sdf.format(fecharecdate);
fecharec = fecharecdate.toString();
}else{
fecharec = String.valueOf(fecha.getText()) + " " + "00" + ":" + "00" + ":" + "00";
}
Intent intent = new Intent(SendActivity.this, PopUp.class);
Bundle b = new Bundle();
b.putLong("code", Long.parseLong(String.valueOf(code.getText())));
b.putString("fecha", fecharec);
intent.putExtras(b);
startActivity(intent);
}
}
}
});
}
} | 21dc9e7c155fba5a0b3e776f32d974232da64618 | [
"Markdown",
"Java"
]
| 8 | Java | Aga-Gava/AgavaCOVID | 69dc36806e8f8a8c471cd086e04de7f30de08bf9 | 30a175c42de2380cf01868ae29bcfd4b00911232 |
refs/heads/master | <repo_name>PrithviKambhampati/cola-blimp<file_sep>/jschulz/README.md
name: <NAME>
email: <EMAIL>
quote:
This visage, no mere veneer of vanity, is a vestige of the vox populi,
now vacant, vanished. However, this valorous visitation of a by-gone vexation,
stands vivified and has vowed to vanquish these venal and virulent vermin
vanguarding vice and vouchsafing the violently vicious and voracious violation of volition.
-V
<file_sep>/lab_one_ws/src/weather_pkg/scripts/weather_sub.py
#!/usr/bin/env python
import sys
import rospy
import pyowm
from random import randint
from std_msgs.msg import Int64
from weather_pkg.msg import weather
hot = ["Boy that is hot!","Better wear a tee-shirt.","I'm melting."]
warm = ["Looks like a nice day", "Good day for a walk.", "Great weather to be outside."]
cool = ["Better wear a sweeter.", "Getting colder...", "Don't catch a cold..."]
cold = ["Better wear a jacket!", "Good Day to stay indoors..", "Don't freeze!"]
def callback(data):
x = randint(0,2)
if data.temp < 32:
rospy.loginfo("It is " + str(data.temp) + " degrees outside! " + cold[x])
elif data.temp < 50:
rospy.loginfo("It is " + str(data.temp) + " degrees outside! " + cool[x])
elif data.temp < 80:
rospy.loginfo("It is " + str(data.temp) + " degrees outside! " + warm[x])
else:
rospy.loginfo("It is " + str(data.temp) + " degrees outside! " + hot[x])
rospy.loginfo("Temperature is: " + str(data.temp))
rospy.loginfo("Cloud Cover is: " + data.cloud_cover)
rospy.loginfo("Pressure is: " + str(data.pressure))
rospy.loginfo("Zipcode is: " + str(data.zipcode))
def weather_sub():
rospy.init_node('listener', anonymous=True)
rospy.Subscriber("chatter", weather, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
weather_sub()
<file_sep>/lab_one_ws/src/weather_pkg/scripts/weather_pub.py
#!/usr/bin/env python
import sys
import rospy
import pyowm
from std_msgs.msg import Int64
from weather_pkg.msg import weather
def weather_pub(x):
pub = rospy.Publisher('chatter', weather, queue_size=10)
rospy.init_node('weather_pub', anonymous=True)
rate = rospy.Rate(0.1) # 10hz
owm = pyowm.OWM('211a0e00ae519d723c94311c4ec86126')
while not rospy.is_shutdown():
city = owm.weather_at_zip_code(x,"us")
w=city.get_weather()
temp=w.get_temperature('fahrenheit')
pressure=w.get_pressure()
msg=weather()
msg.zipcode=x
msg.temp=float(temp['temp'])
msg.cloud_cover=str(w.get_clouds())
msg.pressure=float(pressure['press'])
rospy.loginfo(msg)
pub.publish(msg)
rate.sleep()
if __name__ == '__main__':
if len(sys.argv) > 1:
x = sys.argv[1]
else:
x = "49931" #default to Houghton if no zip code given
try:
weather_pub(x)
except rospy.ROSInterruptException:
pass
<file_sep>/lab_one_ws/bash_scripts/bash_roscore.sh
#! /bin/bash
cd ~/catkin_ws/
catkin_make
. ./devel/setup.bash
cd ~
roscore
<file_sep>/pkambham/bash_scripts/bash_publisher.sh
#! /bin/bash/
cd catkin_ws
catkin_make
. ./devel/setup.bash
cd ~
rosrun weather_pkg weather_pub.py
<file_sep>/pkambham/bash_scripts/bash_turtle.sh
#! /bin/bash/
cd catkin_ws
catkin_make
. ./devel/setup.bash
temp=$(tail ~/catkin_ws/temp.txt -c 14)
cd ~
rosrun turtlesim turtlesim_node
<file_sep>/lab_one_ws/bash_scripts/bash_subscriber.sh
#! /bin/bash/
cd catkin_ws
catkin_make
. ./devel/setup.bash
rosrun weather_pkg weather_sub.py
<file_sep>/pkambham/catkin_ws/devel/share/weather_tutorials/cmake/weather_tutorials-msg-paths.cmake
# generated from genmsg/cmake/pkg-msg-paths.cmake.develspace.in
set(weather_tutorials_MSG_INCLUDE_DIRS "")
set(weather_tutorials_MSG_DEPENDENCIES std_msgs)
<file_sep>/pkambham/catkin_ws/src/weather_tutorials/scripts/weather_pub.py
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int64
import pyowm
def weather_pub():
pub = rospy.Publisher('chatter', Int64, queue_size=10)
rospy.init_node('weather_pub', anonymous=True)
rate = rospy.Rate(0.1) # 10hz
owm = pyowm.OWM('211a0e00ae519d723c94311c4ec86126')
while not rospy.is_shutdown():
city = owm.weather_at_zip_code("49931","us")
w=city.get_weather()
temp=w.get_temperature('fahrenheit')
temp =temp['temp']
rospy.loginfo(temp)
pub.publish(temp)
rate.sleep()
if __name__ == '__main__':
try:
weather_pub()
except rospy.ROSInterruptException:
pass
<file_sep>/pkambham/catkin_ws/build/weather_tutorials/catkin_generated/installspace/weather_tutorials-msg-paths.cmake
# generated from genmsg/cmake/pkg-msg-paths.cmake.installspace.in
_prepend_path("${weather_tutorials_DIR}/.." "" weather_tutorials_MSG_INCLUDE_DIRS UNIQUE)
set(weather_tutorials_MSG_DEPENDENCIES std_msgs)
<file_sep>/lab_one_ws/build/weather_pkg/CMakeFiles/weather_pkg_generate_messages_cpp.dir/cmake_clean.cmake
FILE(REMOVE_RECURSE
"CMakeFiles/weather_pkg_generate_messages_cpp"
"/home/robotics/git_work/cola-blimp/lab_one_ws/devel/include/weather_pkg/weather.h"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang)
INCLUDE(CMakeFiles/weather_pkg_generate_messages_cpp.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
<file_sep>/lab_one_ws/build/weather_pkg/catkin_generated/weather_pkg-msg-extras.cmake.installspace.in
set(weather_pkg_MESSAGE_FILES "msg/weather.msg")
set(weather_pkg_SERVICE_FILES "")
<file_sep>/pkambham/README.md
Name: <NAME>
Email: <EMAIL>
Quote: The function of education is to teach one to think intensively and to think critically.
<file_sep>/lab_one_ws/build/weather_pkg/catkin_generated/installspace/weather_pkg-msg-paths.cmake
# generated from genmsg/cmake/pkg-msg-paths.cmake.installspace.in
_prepend_path("${weather_pkg_DIR}/.." "msg" weather_pkg_MSG_INCLUDE_DIRS UNIQUE)
set(weather_pkg_MSG_DEPENDENCIES std_msgs)
<file_sep>/lab_one_ws/build/weather_pkg/Makefile
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.8
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/robotics/git_work/cola-blimp/lab_one_ws/src
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/robotics/git_work/cola-blimp/lab_one_ws/build
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..."
/usr/bin/cmake -i .
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target install
install: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/bin/cmake -P cmake_install.cmake
.PHONY : install
# Special rule for the target install
install/fast: preinstall/fast
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/bin/cmake -P cmake_install.cmake
.PHONY : install/fast
# Special rule for the target install/local
install/local: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..."
/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake
.PHONY : install/local
# Special rule for the target install/local
install/local/fast: install/local
.PHONY : install/local/fast
# Special rule for the target install/strip
install/strip: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..."
/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake
.PHONY : install/strip
# Special rule for the target install/strip
install/strip/fast: install/strip
.PHONY : install/strip/fast
# Special rule for the target list_install_components
list_install_components:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\""
.PHONY : list_install_components
# Special rule for the target list_install_components
list_install_components/fast: list_install_components
.PHONY : list_install_components/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target test
test:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..."
/usr/bin/ctest --force-new-ctest-process $(ARGS)
.PHONY : test
# Special rule for the target test
test/fast: test
.PHONY : test/fast
# The main all target
all: cmake_check_build_system
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/robotics/git_work/cola-blimp/lab_one_ws/build/CMakeFiles /home/robotics/git_work/cola-blimp/lab_one_ws/build/weather_pkg/CMakeFiles/progress.marks
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/all
$(CMAKE_COMMAND) -E cmake_progress_start /home/robotics/git_work/cola-blimp/lab_one_ws/build/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/preinstall
.PHONY : preinstall/fast
# clear depends
depend:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
# Convenience name for target.
weather_pkg/CMakeFiles/_weather_pkg_generate_messages_check_deps_weather.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/_weather_pkg_generate_messages_check_deps_weather.dir/rule
.PHONY : weather_pkg/CMakeFiles/_weather_pkg_generate_messages_check_deps_weather.dir/rule
# Convenience name for target.
_weather_pkg_generate_messages_check_deps_weather: weather_pkg/CMakeFiles/_weather_pkg_generate_messages_check_deps_weather.dir/rule
.PHONY : _weather_pkg_generate_messages_check_deps_weather
# fast build rule for target.
_weather_pkg_generate_messages_check_deps_weather/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/_weather_pkg_generate_messages_check_deps_weather.dir/build.make weather_pkg/CMakeFiles/_weather_pkg_generate_messages_check_deps_weather.dir/build
.PHONY : _weather_pkg_generate_messages_check_deps_weather/fast
# Convenience name for target.
weather_pkg/CMakeFiles/roscpp_generate_messages_cpp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/roscpp_generate_messages_cpp.dir/rule
.PHONY : weather_pkg/CMakeFiles/roscpp_generate_messages_cpp.dir/rule
# Convenience name for target.
roscpp_generate_messages_cpp: weather_pkg/CMakeFiles/roscpp_generate_messages_cpp.dir/rule
.PHONY : roscpp_generate_messages_cpp
# fast build rule for target.
roscpp_generate_messages_cpp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/roscpp_generate_messages_cpp.dir/build.make weather_pkg/CMakeFiles/roscpp_generate_messages_cpp.dir/build
.PHONY : roscpp_generate_messages_cpp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/roscpp_generate_messages_lisp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/roscpp_generate_messages_lisp.dir/rule
.PHONY : weather_pkg/CMakeFiles/roscpp_generate_messages_lisp.dir/rule
# Convenience name for target.
roscpp_generate_messages_lisp: weather_pkg/CMakeFiles/roscpp_generate_messages_lisp.dir/rule
.PHONY : roscpp_generate_messages_lisp
# fast build rule for target.
roscpp_generate_messages_lisp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/roscpp_generate_messages_lisp.dir/build.make weather_pkg/CMakeFiles/roscpp_generate_messages_lisp.dir/build
.PHONY : roscpp_generate_messages_lisp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/roscpp_generate_messages_py.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/roscpp_generate_messages_py.dir/rule
.PHONY : weather_pkg/CMakeFiles/roscpp_generate_messages_py.dir/rule
# Convenience name for target.
roscpp_generate_messages_py: weather_pkg/CMakeFiles/roscpp_generate_messages_py.dir/rule
.PHONY : roscpp_generate_messages_py
# fast build rule for target.
roscpp_generate_messages_py/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/roscpp_generate_messages_py.dir/build.make weather_pkg/CMakeFiles/roscpp_generate_messages_py.dir/build
.PHONY : roscpp_generate_messages_py/fast
# Convenience name for target.
weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule
.PHONY : weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule
# Convenience name for target.
rosgraph_msgs_generate_messages_cpp: weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule
.PHONY : rosgraph_msgs_generate_messages_cpp
# fast build rule for target.
rosgraph_msgs_generate_messages_cpp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/build.make weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/build
.PHONY : rosgraph_msgs_generate_messages_cpp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule
.PHONY : weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule
# Convenience name for target.
rosgraph_msgs_generate_messages_lisp: weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule
.PHONY : rosgraph_msgs_generate_messages_lisp
# fast build rule for target.
rosgraph_msgs_generate_messages_lisp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/build.make weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/build
.PHONY : rosgraph_msgs_generate_messages_lisp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule
.PHONY : weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule
# Convenience name for target.
rosgraph_msgs_generate_messages_py: weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule
.PHONY : rosgraph_msgs_generate_messages_py
# fast build rule for target.
rosgraph_msgs_generate_messages_py/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/build.make weather_pkg/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/build
.PHONY : rosgraph_msgs_generate_messages_py/fast
# Convenience name for target.
weather_pkg/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule
.PHONY : weather_pkg/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule
# Convenience name for target.
std_msgs_generate_messages_cpp: weather_pkg/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule
.PHONY : std_msgs_generate_messages_cpp
# fast build rule for target.
std_msgs_generate_messages_cpp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/std_msgs_generate_messages_cpp.dir/build.make weather_pkg/CMakeFiles/std_msgs_generate_messages_cpp.dir/build
.PHONY : std_msgs_generate_messages_cpp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule
.PHONY : weather_pkg/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule
# Convenience name for target.
std_msgs_generate_messages_lisp: weather_pkg/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule
.PHONY : std_msgs_generate_messages_lisp
# fast build rule for target.
std_msgs_generate_messages_lisp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/std_msgs_generate_messages_lisp.dir/build.make weather_pkg/CMakeFiles/std_msgs_generate_messages_lisp.dir/build
.PHONY : std_msgs_generate_messages_lisp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/std_msgs_generate_messages_py.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/std_msgs_generate_messages_py.dir/rule
.PHONY : weather_pkg/CMakeFiles/std_msgs_generate_messages_py.dir/rule
# Convenience name for target.
std_msgs_generate_messages_py: weather_pkg/CMakeFiles/std_msgs_generate_messages_py.dir/rule
.PHONY : std_msgs_generate_messages_py
# fast build rule for target.
std_msgs_generate_messages_py/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/std_msgs_generate_messages_py.dir/build.make weather_pkg/CMakeFiles/std_msgs_generate_messages_py.dir/build
.PHONY : std_msgs_generate_messages_py/fast
# Convenience name for target.
weather_pkg/CMakeFiles/weather_pkg_gencpp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/weather_pkg_gencpp.dir/rule
.PHONY : weather_pkg/CMakeFiles/weather_pkg_gencpp.dir/rule
# Convenience name for target.
weather_pkg_gencpp: weather_pkg/CMakeFiles/weather_pkg_gencpp.dir/rule
.PHONY : weather_pkg_gencpp
# fast build rule for target.
weather_pkg_gencpp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/weather_pkg_gencpp.dir/build.make weather_pkg/CMakeFiles/weather_pkg_gencpp.dir/build
.PHONY : weather_pkg_gencpp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/weather_pkg_generate_messages.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/weather_pkg_generate_messages.dir/rule
.PHONY : weather_pkg/CMakeFiles/weather_pkg_generate_messages.dir/rule
# Convenience name for target.
weather_pkg_generate_messages: weather_pkg/CMakeFiles/weather_pkg_generate_messages.dir/rule
.PHONY : weather_pkg_generate_messages
# fast build rule for target.
weather_pkg_generate_messages/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/weather_pkg_generate_messages.dir/build.make weather_pkg/CMakeFiles/weather_pkg_generate_messages.dir/build
.PHONY : weather_pkg_generate_messages/fast
# Convenience name for target.
weather_pkg/CMakeFiles/weather_pkg_generate_messages_cpp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/weather_pkg_generate_messages_cpp.dir/rule
.PHONY : weather_pkg/CMakeFiles/weather_pkg_generate_messages_cpp.dir/rule
# Convenience name for target.
weather_pkg_generate_messages_cpp: weather_pkg/CMakeFiles/weather_pkg_generate_messages_cpp.dir/rule
.PHONY : weather_pkg_generate_messages_cpp
# fast build rule for target.
weather_pkg_generate_messages_cpp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/weather_pkg_generate_messages_cpp.dir/build.make weather_pkg/CMakeFiles/weather_pkg_generate_messages_cpp.dir/build
.PHONY : weather_pkg_generate_messages_cpp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/weather_pkg_generate_messages_lisp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/weather_pkg_generate_messages_lisp.dir/rule
.PHONY : weather_pkg/CMakeFiles/weather_pkg_generate_messages_lisp.dir/rule
# Convenience name for target.
weather_pkg_generate_messages_lisp: weather_pkg/CMakeFiles/weather_pkg_generate_messages_lisp.dir/rule
.PHONY : weather_pkg_generate_messages_lisp
# fast build rule for target.
weather_pkg_generate_messages_lisp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/weather_pkg_generate_messages_lisp.dir/build.make weather_pkg/CMakeFiles/weather_pkg_generate_messages_lisp.dir/build
.PHONY : weather_pkg_generate_messages_lisp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/weather_pkg_generate_messages_py.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/weather_pkg_generate_messages_py.dir/rule
.PHONY : weather_pkg/CMakeFiles/weather_pkg_generate_messages_py.dir/rule
# Convenience name for target.
weather_pkg_generate_messages_py: weather_pkg/CMakeFiles/weather_pkg_generate_messages_py.dir/rule
.PHONY : weather_pkg_generate_messages_py
# fast build rule for target.
weather_pkg_generate_messages_py/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/weather_pkg_generate_messages_py.dir/build.make weather_pkg/CMakeFiles/weather_pkg_generate_messages_py.dir/build
.PHONY : weather_pkg_generate_messages_py/fast
# Convenience name for target.
weather_pkg/CMakeFiles/weather_pkg_genlisp.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/weather_pkg_genlisp.dir/rule
.PHONY : weather_pkg/CMakeFiles/weather_pkg_genlisp.dir/rule
# Convenience name for target.
weather_pkg_genlisp: weather_pkg/CMakeFiles/weather_pkg_genlisp.dir/rule
.PHONY : weather_pkg_genlisp
# fast build rule for target.
weather_pkg_genlisp/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/weather_pkg_genlisp.dir/build.make weather_pkg/CMakeFiles/weather_pkg_genlisp.dir/build
.PHONY : weather_pkg_genlisp/fast
# Convenience name for target.
weather_pkg/CMakeFiles/weather_pkg_genpy.dir/rule:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f CMakeFiles/Makefile2 weather_pkg/CMakeFiles/weather_pkg_genpy.dir/rule
.PHONY : weather_pkg/CMakeFiles/weather_pkg_genpy.dir/rule
# Convenience name for target.
weather_pkg_genpy: weather_pkg/CMakeFiles/weather_pkg_genpy.dir/rule
.PHONY : weather_pkg_genpy
# fast build rule for target.
weather_pkg_genpy/fast:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(MAKE) -f weather_pkg/CMakeFiles/weather_pkg_genpy.dir/build.make weather_pkg/CMakeFiles/weather_pkg_genpy.dir/build
.PHONY : weather_pkg_genpy/fast
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... _weather_pkg_generate_messages_check_deps_weather"
@echo "... edit_cache"
@echo "... install"
@echo "... install/local"
@echo "... install/strip"
@echo "... list_install_components"
@echo "... rebuild_cache"
@echo "... roscpp_generate_messages_cpp"
@echo "... roscpp_generate_messages_lisp"
@echo "... roscpp_generate_messages_py"
@echo "... rosgraph_msgs_generate_messages_cpp"
@echo "... rosgraph_msgs_generate_messages_lisp"
@echo "... rosgraph_msgs_generate_messages_py"
@echo "... std_msgs_generate_messages_cpp"
@echo "... std_msgs_generate_messages_lisp"
@echo "... std_msgs_generate_messages_py"
@echo "... test"
@echo "... weather_pkg_gencpp"
@echo "... weather_pkg_generate_messages"
@echo "... weather_pkg_generate_messages_cpp"
@echo "... weather_pkg_generate_messages_lisp"
@echo "... weather_pkg_generate_messages_py"
@echo "... weather_pkg_genlisp"
@echo "... weather_pkg_genpy"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
cd /home/robotics/git_work/cola-blimp/lab_one_ws/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>/lab_one_ws/build/weather_pkg/CMakeFiles/weather_pkg_generate_messages_lisp.dir/cmake_clean.cmake
FILE(REMOVE_RECURSE
"CMakeFiles/weather_pkg_generate_messages_lisp"
"/home/robotics/git_work/cola-blimp/lab_one_ws/devel/share/common-lisp/ros/weather_pkg/msg/weather.lisp"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang)
INCLUDE(CMakeFiles/weather_pkg_generate_messages_lisp.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
<file_sep>/pkambham/catkin_ws/build/weather_tutorial/catkin_generated/package.cmake
set(_CATKIN_CURRENT_PACKAGE "weather_tutorial")
set(weather_tutorial_VERSION "0.0.0")
set(weather_tutorial_MAINTAINER "prithvi <<EMAIL>>")
set(weather_tutorial_PACKAGE_FORMAT "1")
set(weather_tutorial_BUILD_DEPENDS "roscpp" "rospy" "std_msgs")
set(weather_tutorial_BUILD_EXPORT_DEPENDS "roscpp" "rospy" "std_msgs")
set(weather_tutorial_BUILDTOOL_DEPENDS "catkin")
set(weather_tutorial_BUILDTOOL_EXPORT_DEPENDS )
set(weather_tutorial_EXEC_DEPENDS "roscpp" "rospy" "std_msgs")
set(weather_tutorial_RUN_DEPENDS "roscpp" "rospy" "std_msgs")
set(weather_tutorial_TEST_DEPENDS )
set(weather_tutorial_DOC_DEPENDS )
set(weather_tutorial_DEPRECATED "")<file_sep>/lab_one_ws/build/CTestTestfile.cmake
# CMake generated Testfile for
# Source directory: /home/robotics/git_work/cola-blimp/lab_one_ws/src
# Build directory: /home/robotics/git_work/cola-blimp/lab_one_ws/build
#
# This file includes the relevant testing commands required for
# testing this directory and lists subdirectories to be tested as well.
SUBDIRS(gtest)
SUBDIRS(weather_pkg)
<file_sep>/pkambham/catkin_ws/build/weather_tutorials/catkin_generated/package.cmake
set(_CATKIN_CURRENT_PACKAGE "weather_tutorials")
set(weather_tutorials_VERSION "0.0.0")
set(weather_tutorials_MAINTAINER "prithvi <<EMAIL>>")
set(weather_tutorials_PACKAGE_FORMAT "1")
set(weather_tutorials_BUILD_DEPENDS "message_generation" "roscpp" "rospy" "std_msgs")
set(weather_tutorials_BUILD_EXPORT_DEPENDS "message_runtime" "roscpp" "rospy" "std_msgs")
set(weather_tutorials_BUILDTOOL_DEPENDS "catkin" "catkin")
set(weather_tutorials_BUILDTOOL_EXPORT_DEPENDS )
set(weather_tutorials_EXEC_DEPENDS "message_runtime" "roscpp" "rospy" "std_msgs")
set(weather_tutorials_RUN_DEPENDS "message_runtime" "roscpp" "rospy" "std_msgs")
set(weather_tutorials_TEST_DEPENDS )
set(weather_tutorials_DOC_DEPENDS )
set(weather_tutorials_DEPRECATED "")<file_sep>/README.md
# cola-blimp
EE5900-Introduction to Robotics #3
<file_sep>/lab_one_ws/src/weather_pkg/scripts/weather_sub_turtle.py
#!/usr/bin/env python
import sys
import rospy
import pyowm
from random import randint
from std_msgs.msg import Int64
from weather_pkg.msg import weather
def callback(data):
rospy.loginfo(str(data.temp))
def weather_sub():
rospy.init_node('listener', anonymous=True)
rospy.Subscriber("chatter", weather, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
weather_sub()
<file_sep>/lab_one_ws/bash_scripts/bash_subscriber_turtle.sh
#! /bin/bash/
cd catkin_ws
catkin_make
. ./devel/setup.bash
timeout 15 rosrun weather_pkg weather_sub_turtle.py > temp.txt
temp=$(tail ~/catkin_ws/temp.txt -c 14)
cd ~
<file_sep>/pkambham/catkin_ws/src/weather_tutorials/scripts/weather_sub.py
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int64
def callback(data):
rospy.loginfo(data.data)
def weather_sub():
rospy.init_node('listener', anonymous=True)
rospy.Subscriber("chatter", Int64, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
weather_sub()
<file_sep>/lab_one_ws/build/weather_pkg/cmake/weather_pkg-genmsg.cmake
# generated from genmsg/cmake/pkg-genmsg.cmake.em
message(STATUS "weather_pkg: 1 messages, 0 services")
set(MSG_I_FLAGS "-Iweather_pkg:/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg;-Istd_msgs:/opt/ros/indigo/share/std_msgs/cmake/../msg")
# Find all generators
find_package(gencpp REQUIRED)
find_package(genlisp REQUIRED)
find_package(genpy REQUIRED)
add_custom_target(weather_pkg_generate_messages ALL)
# verify that message/service dependencies have not changed since configure
get_filename_component(_filename "/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg/weather.msg" NAME_WE)
add_custom_target(_weather_pkg_generate_messages_check_deps_${_filename}
COMMAND ${CATKIN_ENV} ${PYTHON_EXECUTABLE} ${GENMSG_CHECK_DEPS_SCRIPT} "weather_pkg" "/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg/weather.msg" ""
)
#
# langs = gencpp;genlisp;genpy
#
### Section generating for lang: gencpp
### Generating Messages
_generate_msg_cpp(weather_pkg
"/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg/weather.msg"
"${MSG_I_FLAGS}"
""
${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/weather_pkg
)
### Generating Services
### Generating Module File
_generate_module_cpp(weather_pkg
${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/weather_pkg
"${ALL_GEN_OUTPUT_FILES_cpp}"
)
add_custom_target(weather_pkg_generate_messages_cpp
DEPENDS ${ALL_GEN_OUTPUT_FILES_cpp}
)
add_dependencies(weather_pkg_generate_messages weather_pkg_generate_messages_cpp)
# add dependencies to all check dependencies targets
get_filename_component(_filename "/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg/weather.msg" NAME_WE)
add_dependencies(weather_pkg_generate_messages_cpp _weather_pkg_generate_messages_check_deps_${_filename})
# target for backward compatibility
add_custom_target(weather_pkg_gencpp)
add_dependencies(weather_pkg_gencpp weather_pkg_generate_messages_cpp)
# register target for catkin_package(EXPORTED_TARGETS)
list(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS weather_pkg_generate_messages_cpp)
### Section generating for lang: genlisp
### Generating Messages
_generate_msg_lisp(weather_pkg
"/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg/weather.msg"
"${MSG_I_FLAGS}"
""
${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/weather_pkg
)
### Generating Services
### Generating Module File
_generate_module_lisp(weather_pkg
${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/weather_pkg
"${ALL_GEN_OUTPUT_FILES_lisp}"
)
add_custom_target(weather_pkg_generate_messages_lisp
DEPENDS ${ALL_GEN_OUTPUT_FILES_lisp}
)
add_dependencies(weather_pkg_generate_messages weather_pkg_generate_messages_lisp)
# add dependencies to all check dependencies targets
get_filename_component(_filename "/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg/weather.msg" NAME_WE)
add_dependencies(weather_pkg_generate_messages_lisp _weather_pkg_generate_messages_check_deps_${_filename})
# target for backward compatibility
add_custom_target(weather_pkg_genlisp)
add_dependencies(weather_pkg_genlisp weather_pkg_generate_messages_lisp)
# register target for catkin_package(EXPORTED_TARGETS)
list(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS weather_pkg_generate_messages_lisp)
### Section generating for lang: genpy
### Generating Messages
_generate_msg_py(weather_pkg
"/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg/weather.msg"
"${MSG_I_FLAGS}"
""
${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/weather_pkg
)
### Generating Services
### Generating Module File
_generate_module_py(weather_pkg
${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/weather_pkg
"${ALL_GEN_OUTPUT_FILES_py}"
)
add_custom_target(weather_pkg_generate_messages_py
DEPENDS ${ALL_GEN_OUTPUT_FILES_py}
)
add_dependencies(weather_pkg_generate_messages weather_pkg_generate_messages_py)
# add dependencies to all check dependencies targets
get_filename_component(_filename "/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg/weather.msg" NAME_WE)
add_dependencies(weather_pkg_generate_messages_py _weather_pkg_generate_messages_check_deps_${_filename})
# target for backward compatibility
add_custom_target(weather_pkg_genpy)
add_dependencies(weather_pkg_genpy weather_pkg_generate_messages_py)
# register target for catkin_package(EXPORTED_TARGETS)
list(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS weather_pkg_generate_messages_py)
if(gencpp_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/weather_pkg)
# install generated code
install(
DIRECTORY ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/weather_pkg
DESTINATION ${gencpp_INSTALL_DIR}
)
endif()
add_dependencies(weather_pkg_generate_messages_cpp std_msgs_generate_messages_cpp)
if(genlisp_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/weather_pkg)
# install generated code
install(
DIRECTORY ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/weather_pkg
DESTINATION ${genlisp_INSTALL_DIR}
)
endif()
add_dependencies(weather_pkg_generate_messages_lisp std_msgs_generate_messages_lisp)
if(genpy_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/weather_pkg)
install(CODE "execute_process(COMMAND \"/usr/bin/python\" -m compileall \"${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/weather_pkg\")")
# install generated code
install(
DIRECTORY ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/weather_pkg
DESTINATION ${genpy_INSTALL_DIR}
)
endif()
add_dependencies(weather_pkg_generate_messages_py std_msgs_generate_messages_py)
<file_sep>/lab_one_ws/build/weather_pkg/cmake/weather_pkg-genmsg-context.py
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg/weather.msg"
services_str = ""
pkg_name = "weather_pkg"
dependencies_str = "std_msgs"
langs = "gencpp;genlisp;genpy"
dep_include_paths_str = "weather_pkg;/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg;std_msgs;/opt/ros/indigo/share/std_msgs/cmake/../msg"
PYTHON_EXECUTABLE = "/usr/bin/python"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/indigo/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
<file_sep>/lab_one_ws/devel/share/weather_pkg/cmake/weather_pkg-msg-paths.cmake
# generated from genmsg/cmake/pkg-msg-paths.cmake.develspace.in
set(weather_pkg_MSG_INCLUDE_DIRS "/home/robotics/git_work/cola-blimp/lab_one_ws/src/weather_pkg/msg")
set(weather_pkg_MSG_DEPENDENCIES std_msgs)
<file_sep>/pkambham/bash_scripts/bash_turtle_rostopic.sh
#! /bin/bash/
cd catkin_ws
catkin_make
. ./devel/setup.bash
temp=$(tail ~/catkin_ws/temp.txt -c 14)
cd ~
ang_vel=$(echo "scale=3;100/${temp}" | bc)
temp_int=${temp%.*}
if [ "$temp_int" -lt "32" ]
then
rostopic pub /turtle1/cmd_vel geometry_msgs/Twist -r 1 -- '[2.0, 0.0, 0.0]' '[0.0, 0.0, 4.0]'
elif [ "$temp_int" -lt "50" ]
then
rostopic pub /turtle1/cmd_vel geometry_msgs/Twist -r 1 -- '[2.0, 0.0, 0.0]' '[0.0, 0.0, 3.0]'
elif [ "$temp_int" -lt "80" ]
then
rostopic pub /turtle1/cmd_vel geometry_msgs/Twist -r 1 -- '[2.0, 0.0, 0.0]' '[0.0, 0.0, 2.0]'
else
rostopic pub -1 /turtle1/cmd_vel geometry_msgs/Twist -- '[2.0, 0.0, 0.0]' '[0.0, 0.0, 1.0]'
fi
<file_sep>/pkambham/catkin_ws/build/weather_tutorials/CTestTestfile.cmake
# CMake generated Testfile for
# Source directory: /home/prithvi/catkin_ws/src/weather_tutorials
# Build directory: /home/prithvi/catkin_ws/build/weather_tutorials
#
# This file includes the relevant testing commands required for
# testing this directory and lists subdirectories to be tested as well.
<file_sep>/pdscraml/README.md
My Name is **<NAME>**
My email is **<EMAIL>**
My favorite quote is **"Whatever you are, be a good one." - <NAME>**
<file_sep>/lab_one_ws/build/weather_pkg/catkin_generated/package.cmake
set(_CATKIN_CURRENT_PACKAGE "weather_pkg")
set(weather_pkg_VERSION "0.0.0")
set(weather_pkg_MAINTAINER "<NAME> <<EMAIL>>")
set(weather_pkg_PACKAGE_FORMAT "1")
set(weather_pkg_BUILD_DEPENDS "message_generation" "roscpp" "rospy" "std_msgs")
set(weather_pkg_BUILD_EXPORT_DEPENDS "message_runtime" "roscpp" "rospy" "std_msgs")
set(weather_pkg_BUILDTOOL_DEPENDS "catkin")
set(weather_pkg_BUILDTOOL_EXPORT_DEPENDS )
set(weather_pkg_EXEC_DEPENDS "message_runtime" "roscpp" "rospy" "std_msgs")
set(weather_pkg_RUN_DEPENDS "message_runtime" "roscpp" "rospy" "std_msgs")
set(weather_pkg_TEST_DEPENDS )
set(weather_pkg_DOC_DEPENDS )
set(weather_pkg_DEPRECATED "")<file_sep>/jtradwil/README.md
Name: <NAME>
Email: <EMAIL>
Favorite Quote: "Do or do not, there is no try."
| 461a34fcb30b21aec4406c34f7f4f8f67c4e6933 | [
"CMake",
"Markdown",
"Makefile",
"Python",
"Shell"
]
| 31 | Markdown | PrithviKambhampati/cola-blimp | dbac1497901a46fdb0c077873b0c2d0bc3a06e0d | 4aa9186da2a99f87653075f79e50a90155eef5bc |
refs/heads/master | <file_sep>#pragma comment(lib, "RaspberryPI.lib")
#include <stdio.h>
#include <stdlib.h>
#include <RaspberryDLL.h>
#include <conio.h>
#include <iostream>
#pragma once
void alarm(int i);
void unlocked(int i);
void keyChange(int i, int* keyPtr);
void locked(int i);
void breakIn(int i);
<file_sep>#pragma once
#include "Header.h"
void alarm(int i)
{
ledOn(i);
Wait(10);
ledOff(i);
Wait(10);
}
void unlocked(int i)
{
ledOn(i);
Wait(10);
ledOff(i);
}
void locked(int i)
{
ledOn(i);
Wait(10);
ledOff(i);
}
void breakIn(int i)
{
ledOn(i);
}
<file_sep>#include "Header.h"
/*
Exercise 9
Bilalarm
I denne opgave skal du udvikle koden til en bilalarm.
Du skal anvende disse komponenter på din Raspberry Pi:
• En key. Den skal fungere som ”fjernbetjening”. Når der trykkes på knappen
skal ”bilen låses” og alarmen skal aktiveres. Når der trykkes på knappen igen
skal ”bilen låses op” og alarmen skal deaktiveres. Der skiftes tilstand hver
gang der trykkes på knappen.
• Den røde LED. Dette er dioden der sidder inde i ”bilen”. Den skal blinke, når
alarmen er aktiveret og være slukket når alarmen er deaktiveret. Når der er
registreret indbrud skla den lyse konstant.
• Grønne LED’er. Disse skal simulere ”bilens” blinklys. Blinklyset skal med en
blinksekvens markere at alarmen aktiveres og med en anden blinksekvens
markere at alarmen deaktiveres. En tredje blinksekvens skal fungere som
alarmsignal (i stadet for et lydsignal). Du vælger selv dine blinksekvenser.
Alternativt kan du vælge nogle af de grønne LED’er til blinklys (on/off-signaler) og nogle andre grønne LED’er til alarmsignal.
• Switchen. Denne skal fungerer som bilens dørkontakt. Når switchen er ON
er ”døren låst”, når switchen er OFF er ”døren åben”. Hvis ”døren” brydes op
(åbnes) mens alarmen er aktiveret, skal alarmsignalet sættes i gang.
• Fotoresistoren. Denne skal fungerer som ”bevægelsesføler” inde i bilen.
Hvis der detekteres bevægelse inde i bilen (lyset på fotoresistoren brydes)
mens alarmen er aktiveret, skal alarmsignalet sættes i gang.
*/
int main(void)
{
using namespace std;
if (!Open())
{
printf("Error with connection\n");
exit(1);
}
printf("Connected to Raspberry Pi\n");
// To do your code
int key = 1; //STARTER BILEN TIL AT VÆRE OPLÅST
do //lave uendeligt while loop
{
do
{
unlocked(5); //viser at bilen er oplåst
cout << "Car is unlocked" << endl; //udskriver bilen er oplåst
while (key == 1) //er inde i dette loop indtil der trykkes på P1
{
if (keyPressed(1)) //hvis der trykkes på P1
{
key = 0; //hvis der trykkes på P1 ændres key til 0 og
}
Wait(70);
}
} while (key == 1); //gentag det hvis key er lig 1
do
{
locked(4); //låse bilen 2 blink på grøn led 4
cout << "Car is locked" << endl;
while (key == 0)
{
alarm(6); //rød led blinker
if (getIntensity() <= 50 || keyPressed(2)) // indbrud hvis der er bevægelse eller dør
{
key = 3; //går over på key 3 tilstand
}
if (keyPressed(1)) //bilen oplåses
{
key = 1; //går i oplåst tilstand
}
Wait(70);
}
} while (key == 0);
while (key == 3) //går kun og kun igang hvis der er indbrud
{
breakIn(6); //rød led lyser konstant
cout << "<NAME> BEEN HIJACKED!!!" << endl; //fortæller indbrud
while (key == 3)
{
if (keyPressed(1))
{
ledOff(6);
key = 1;
}
Wait(70);
}
}
} while (1); // ud af loop når der trykkes på tastatur
return 0;
} | 873943bcf367a7cfb3e2e2f0bde4137e41574490 | [
"C++"
]
| 3 | C++ | pilo309/Exercise9.1 | eea5e8c043b8be6b4f91c885e06b07aee9909ecc | 96351001f19ffb03167fe5d4deff825ef8636aa4 |
refs/heads/master | <file_sep>
let filterOn = false
document.addEventListener("DOMContentLoaded", () => {
getDogs()
makeDogPage()
let filter = document.getElementById('good-dog-filter')
filter.addEventListener('click', toggleGoodDogs)
})
function toggleGoodDogs(event) {
let dogBar = document.getElementById('dog-bar')
if(filterOn) {
filterOn = false
event.target.innerText = 'Filter good dogs: OFF'
Array.from(document.getElementsByClassName("false")).forEach(dog => dog.style.display = 'flex')
} else {
event.target.innerText = 'Filter good dogs: ON'
filterOn = true
Array.from(document.getElementsByClassName("false")).forEach(dog => dog.style.display = 'none')
}
}
function getDogs() {
fetch('http://localhost:3000/pups')
.then(resp => resp.json())
.then(data => data.forEach(dog => createDogBar(dog)))
}
function createDogBar(dog) {
let dogBar = document.getElementById("dog-bar")
let dogSpan = document.createElement('span')
dogSpan.innerText = dog.name
dogSpan.id = dog.id
dogSpan.classList.add(`${dog.isGoodDog}`)
dogBar.append(dogSpan)
dogSpan.addEventListener("click", getDog)
}
function getDog(event) {
let dogId = event.target.id
fetch(`http://localhost:3000/pups/${dogId}`)
.then(resp => resp.json())
.then(data => replaceDogPage(data))
// dogImage.src =
}
function replaceDogPage(dog) {
let dogInfo = document.getElementById("dog-info")
let image = document.getElementById("image-box")
image.style.display ='block'
image.src = dog.image
let title = document.getElementById('dog-title')
title.innerText = dog.name
let dogButton = document.getElementById("dog-button")
dogButton.dataset.id = dog.id
dogButton.style.display = 'block'
if (dog.isGoodDog) {
dogButton.innerText = "Good Dog!"
} else {
dogButton.innerText = "Bad Dog!"
}
dogButton.addEventListener('click', changeStatus)
}
function changeStatus(event) {
console.log(event)
let dogId = event.target.attributes[2].value
let formData
let dogSpan = document.getElementById(`${dogId}`)
if (event.target.innerText === "Good Dog!") {
formData = {
isGoodDog: false
}
dogSpan.className = 'false'
}else {
formData = {
isGoodDog: true
}
dogSpan.className = 'true'
}
let configObj = {
method: "PATCH",
headers: {
"content-type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(formData)
}
fetch(`http://localhost:3000/pups/${dogId}`, configObj)
.then(resp => resp.json())
.then(dog => replaceDogPage(dog))
}
function makeDogPage() {
let dogInfo = document.getElementById("dog-info")
let image = document.createElement("img")
image.id = "image-box"
image.src = null
dogInfo.append(image)
image.style.display = 'none'
let title = document.createElement("h2")
title.id = "dog-title"
dogInfo.append(title)
let dogButton = document.createElement("button")
dogButton.innerText = "Good Dog"
dogButton.id = "dog-button"
dogInfo.append(dogButton)
dogButton.style.display = 'none'
}
| e12ad9eccec42a9dc4b15d8f144e44918f034e89 | [
"JavaScript"
]
| 1 | JavaScript | stvik/woof-woof-js-practice-dc-web-102819 | e6b0572475cb9f808570b6d2bcc704aeaa61743f | 168a5e306a7be5048ff27e5231cab6e5439297c4 |
refs/heads/master | <repo_name>animeshrisal/reactnativetodolist<file_sep>/App.js
import React from 'react';
import { AsyncStorage, TextInput, StyleSheet, Text, View, Button, TouchableHighlight } from 'react-native';
import { createStackNavigator } from 'react-navigation';
class Details extends React.Component{
constructor(props){
super(props);
this.state = {
name: '',
description: ''
}
}
componentDidMount(){
const { navigation } = this.props;
const itemId = navigation.getParam("name", "Not Found");
this._getFromStorage(itemId)
}
_getFromStorage = (key) => {
AsyncStorage.getItem(key).then(value => {this.setState({name: key, description: value}) })
}
_deleteTask = (key) => {
AsyncStorage.removeItem(key);
this.props.navigation.state.params.onGoBack();
this.props.navigation.goBack();
}
render(){
return(
<View>
<Text>{this.state.name}</Text>
<Text>{this.state.description}</Text>
<Button title = "delete" onPress={()=> this._deleteTask(this.state.name)}/>
</View>
)
}
}
class AsyncStorageExample extends React.Component{
constructor(props){
super(props);
this.state = {
'tasks': [],
'name': '',
'description': ''
}
}
_getAllItems = () => {
console.log("AAAA")
AsyncStorage.getAllKeys((err, keys) => {
this.setState({tasks: keys});
});
}
componentDidMount = () => {
this._getAllItems();
}
setName = (name) => {
this.setState({'name': name});
}
setDescription = (description) => {
this.setState({'description': description});
}
_saveToStorage = () =>{
AsyncStorage.setItem(this.state.name, this.state.description);
AsyncStorage.getAllKeys((err, keys) => {
this.setState({tasks: keys});
});
}
render(){
return(
<View>
<TextInput onChangeText = {this.setName}></TextInput>
<TextInput onChangeText = {this.setDescription}></TextInput>
{
this.state.tasks.map(
item => <TouchableHighlight
key={item}
title = {item}
onPress = {() => {this.props.navigation.navigate('Details', {name: item,
onGoBack: () => this._getAllItems()
});
}}
><Text>{item}</Text></TouchableHighlight>)}
<Button title = "Save" onPress = {() => this._saveToStorage()} />
</View>
)
}
}
const RootStack = createStackNavigator({
Home:{
screen: AsyncStorageExample,
},
Details: Details
})
export default class App extends React.Component{
render(){
return <RootStack />
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
<file_sep>/README.md
To do list using react native | 49a4fade3be36028fc7a6b23223452cd86dbde9e | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | animeshrisal/reactnativetodolist | e509130dd9829e1c50671e8d9a3cb0d3260eae25 | d67acdef0c0db8617177a5bce44f97f4d153c813 |
refs/heads/master | <file_sep>import re
from random import choice
import colorful
prefixes = [
("Adal", "edle {}"),
("Adel", "edle {}"),
("Al", "edle {}"),
("Ans", "kühne {}"),
("Bald", "kühne {}"),
("Bern", "{} wie ein Bär"),
("Bert", "glänzende {}"),
("Burk", "schützende {}"),
("Burg", "schützende {}"),
("Chlod", "berühmte {}"),
("Klod", "berühmte {}"),
("Dago", "tägliche {}"),
("Dag", "tägliche {}"),
("Dank", "denkende {}"),
("Degen", "Degen-{}"),
("Eg", "Schwert-{}"),
("Ef", "Elfen-{}"),
("Eck", "Schwert-{}"),
("Det", "Volks-{}"),
("Diet", "Volks-{}"),
("Eber", "{} wie ein Eber"),
("Ed", "besitzende {}"),
("Ehren", "{} der Ehre"),
("Ehr", "ehrwürdige {}"),
("Er", "ehrwürdige {}"),
("E", "{} nach Recht und Gesetz"),
("Engel", "{} durch Engel"),
("Fol", "{} im Kriegsvolk"),
("Fried", "beschützende {}"),
("Friede", "beschützende {}"),
("Frith", "Friedens-{}"),
("Gang", "Kampf-{}"),
("Gari", "speerkämpfende {}"),
("Geb", "gebende {}"),
("Ger", "Speer-{}"),
("Gisel", "vornehme {}"),
("Gis", "geiselschützende {}"),
("Gode", "Gottes-{}"),
("God", "Gottes-{}"),
("Gott", "Gottes-{}"),
("Gund", "Kampf-{}"),
("Gun", "Kampf-{}"),
("Gust", "Kampf-{}"),
("Har", "Heeres-{}"),
("Hed", "starke {}"),
("Her", "Heeres-{}"),
("Hart", "starke {}"),
("Hel", "Schützen-{}"),
("Hil", "Schützen-{}"),
("Hild", "Schwert-{}"),
("Hilde", "Schwert-{}"),
("Hin", "Heim-{}"),
("Hein", "Heim-{}"),
("Hol", "{}"),
("Hu", "schlaue {}"),
("Hum", "riesige {}"),
("Kon", "kühne {}"),
("Kuni", "{}"),
("Ladis", "ruhmvolle {}"),
("Lam", "{}"),
("Lebe", "Volks-{}"),
("Leon", "{} im Kriegsvolk"),
("Lud", "ruhmvolle {}"),
("Mal", "gemeinsame {}"), # in der Versammlung o_O
("Man", "männliche {}"),
("Mark", "Grenz-{}"),
("Mat", "mächtige {}"),
("Mar", "Kriegs-{}"),
("Mein", "mächtige {}"),
("Neid", "grimmige {}"),
("Neit", "grimmige {}"),
("Nik", "Volks-{}"),
("Niko", "Volks-{}"),
("Nor", "{} aus dem Norden"),
("Not", "{} in der Not"),
("Os", "Gottes-{}"),
("Ot", "{} der Heimat"),
("Or", "Schwert-{}"),
("Odil", "{} der Heimat"),
("Otto", "besitzende {}"),
("Rag", "kluge {}"),
("Ragn", "Kampf-{}"),
("Ram", "Raben-{}"),
("Rat", "beratende {}"),
("Rein", "beratende {}"),
("Ro", "ruhmvolle {}"),
("Rud", "ruhmreiche {}"),
("Ru", "ruhmreiche {}"),
("Rut", "ruhmreiche {}"),
("Sieg", "siegreiche {}"),
("Sig", "siegreiche {}"),
("Stanis", "beständige {}"),
("Ul", "gute {}"),
("Volk", "Volks-{}"),
("Wald", "herrschende {}"),
("Wal", "herrschende {}"),
("Wern", "warnende {}"),
("Widu", "{} des Waldes"),
("Wil", "willensstarke {}"),
("Wi", "kühne {}"),
("Win", "freundliche {}"),
("Wolde", "waltende {}"),
("Wolf", "Wolfs-{}"),
("Kriem", "{} im Helm"),
("Kuni", "{} für die Sippe"),
]
suffixes = {
"Der": [
("bert", "Glänzende"),
("brecht", "Glänzende"),
("precht", "Glänzende"),
("fons", "Hilfsbereite"),
("fred", "Beschützer"),
("fried", "Beschützer"),
("win", "Freund"),
("uin", "Freund"),
("gand", "Kämpfer"),
("gar", "Speerkämpfer"),
("ger", "Speerkämpfer"),
("hard", "Starke"),
("hold", "Waltende"),
("ram", "Rabe"),
("wig", "Kämpfer"),
("mar", "Berühmte"),
("wart", "Wächter"),
("lef", "Lebende"),
("lev", "Lebende"),
("wald", "Herrscher"),
("ald", "Waltende"),
("rich", "König"),
("mont", "Schützer"),
("mund", "Gewaltige"),
("bald", "Mächtige"),
("mann", "Mann"),
("jof", "Fürst"),
("olf", "Wolf"),
("not", "Kampf"),
("lieb", "Sohn"),
("her", "Mann"),
("av", "Ordner"),
("ald", "Führer"),
("mut", "Kühne"),
("brand", "Kämpfer"),
("mar", "Berühmte"),
("rad", "Berater"),
("ard", "Berater"),
("laus", "Herrscher"),
("las", "Herrscher"),
("recht", "Glänzende"),
("pold", "Kühne"),
("kar", "Speer"),
("nar", "Held"),
("bod", "Gebietende"),
("urd", "Hüter"),
("bot", "Bote"),
],
"Die": [
("gard", "Schützerin"),
("gund", "Kämpferin"),
("heid", "Geartete"),
("berta", "Glänzende"),
("mut", "Mutige"),
("ma", "Gebende"),
("rune", "Zauberin"),
("wine", "Freundin"),
("hild", "Kämpfende"),
("burga", "Schützerin"),
("mar", "Berühmte"),
("ke", "Herrin"),
("lind", "Schildträgerin"),
("linde", "Schildträgerin"),
("gunde", "Kämpferin"),
("traut", "Vertraute"),
("bett", "Geweihte"),
("erike", "Reiche"),
("rike", "Reiche"),
("nelda", "Bekämpferin"),
("run", "Verkündende"),
("trud", "Kämpferin"),
("sine", "Wissende"),
("wig", "Kämpferin"),
("burg", "Schützerin"),
("borg", "Geborgene"),
("rid", "Reiterin"),
("rina", "Reine"),
("trun", "Raunende"),
("hilde", "Kämpferin"),
("milla", "Volksnahe"),
("wiga", "Kämpferin"),
("munde", "Schützerin"),
]
}
colors = {"Der": colorful.red, "Die": colorful.green}
print("Wie wäre es mit einem dieser Namen?")
for _ in range(20):
art = choice(["Der", "Die"])
pre, fmt = choice(prefixes)
post, fill = choice(suffixes[art])
desc = re.sub("-(.)", lambda x: x.group(1).lower(), fmt.format(fill))
print(colors[art]("{:<20}{:<27}".format(f"{pre}{post}", f"({art} {desc})")))
<file_sep>For reasons™, I was "recently" looking at old German names. This is a generator
for them, including their meaning, for example:
Eckhold (Der Schwertwaltende)
Ludolf (Der ruhmvolle Wolf)
Kunigund (Die Kämpferin für die Sippe)
Meinlieb (Der mächtige Sohn)
Adelborg (Die edle Geborgene)
Widuerike (Die Reiche des Waldes)
Meinrid (Die mächtige Reiterin)
Ganggard (Die Kampfschützerin)
Kunimont (Der Schützer)
Erwiga (Die ehrwürdige Kämpferin)
Ratbrand (Der beratende Kämpfer)
Neidav (Der grimmige Ordner)
Chlodard (Der berühmte Berater)
Hildebett (Die Schwertgeweihte)
Ludhilde (Die ruhmvolle Kämpferin)
Friedberta (Die beschützende Glänzende)
Godsine (Die Gotteswissende)
Kuniburg (Die Schützerin für die Sippe)
Godhild (Die Gotteskämpfende)
Hinrid (Die Heimreiterin)
| ba598b0e47ecc1f07091d9342590de38cccd5d93 | [
"Markdown",
"Python"
]
| 2 | Python | L3viathan/siegwald | b74868501d44ff7d3865930c8a220d3e52e53ca4 | 5380fb71d705c0c8fa3f8988b4b50322ac3e7f69 |
refs/heads/master | <repo_name>spicyChick3ns/spicychick3ns.github.io<file_sep>/src/App.js
import React, { Component } from 'react';
import ContactItem from './components/ContactItem';
import './App.css';
import config from './config';
const TITLES = ['wood worker', '<NAME>', 'software engineer'];
class App extends Component {
constructor(props) {
super(props);
this.state = {
word: 'software engineer',
}
}
things = (cb) =>{
let i = 0;
setInterval(() => {
if (i === TITLES.length) {
i=0;
clearInterval();
}
this.setState({
word: TITLES[i],
});
console.log(TITLES[i])
i++;
}, 1000)
}
componentDidMount() {
this.things();
}
render() {
return (
<div className="App">
<header className="App-header">
<h1><NAME></h1>
<h3>{`I am a ${this.state.word}`}</h3>
</header>
<main>
<div className="contact-container">
<ContactItem type='github' url={config.github}/>
<ContactItem type='instagram' url={config.instagram}/>
<ContactItem type='file' url={config.resume}/>
<ContactItem type='envelope' url={config.email}/>
</div>
</main>
</div>
);
}
}
export default App;
<file_sep>/src/components/ContactItem.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class ContactItem extends Component {
render() {
let style;
(this.props.type === 'github' || this.props.type === 'instagram')
? style = `fab fa-${this.props.type}`
: style = `far fa-${this.props.type}`
return (
<div className='contact-item'>
<a target='_blank' href={this.props.url}>
<i className={style}></i>
</a>
</div>
);
}
};
ContactItem.propTypes = {
type: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
}
export default ContactItem;
<file_sep>/precache-manifest.9829f71ff63738bc3f7a7e165d712961.js
self.__precacheManifest = [
{
"revision": "229c360febb4351a89df",
"url": "/static/js/runtime~main.229c360f.js"
},
{
"revision": "8ffb6e1eb199bffefd26",
"url": "/static/js/main.8ffb6e1e.chunk.js"
},
{
"revision": "b05f58ae460c5f47cea3",
"url": "/static/js/1.b05f58ae.chunk.js"
},
{
"revision": "8ffb6e1eb199bffefd26",
"url": "/static/css/main.41e454b5.chunk.css"
},
{
"revision": "cf<PASSWORD>",
"url": "/index.html"
}
]; | 2ceb5cfdf4fe59ebea6e008da360eba290812851 | [
"JavaScript"
]
| 3 | JavaScript | spicyChick3ns/spicychick3ns.github.io | 5751896663ee0cd8e67724464a9a4c67c321ed7b | 6e22f1035ef3d20accd0fdb226ebacfc75257a12 |
refs/heads/master | <repo_name>composi/merge-objects<file_sep>/src/index.js
/**
* Combine two objects, merging the second into the first. Any properties already existing in the first will be replaced by those of the second. Any properties in the second not in the first will be added to it.
* This does a deep clone. Sub arrays will be cloned. If arrays consist of objects, those will be cloned. Functions will also be cloned. This also support Maps and Sets.
* Passing in just one object will return a deep clone of it.
*
* @param {Object.<string, any>[]} objects One or more objects to use for merging.
* @return {Object.<string, any>} Object.<string, any>
*/
export function mergeObjects(...objects) {
const FIRST_ARGUMENT = 0
const ZERO = 0
const SECOND_ARGUMENT = 1
// Add empty array or object to arguments to ensure unique clone:
Array.isArray(objects[FIRST_ARGUMENT])
&& objects.unshift([])
|| typeof objects[FIRST_ARGUMENT] === 'string'
&& objects.unshift(/** @type {*} */(''))
|| typeof objects[FIRST_ARGUMENT] === 'number'
&& objects.unshift(/** @type {*} */(ZERO))
|| objects[FIRST_ARGUMENT] instanceof Set
&& objects.unshift(new Set())
|| objects[FIRST_ARGUMENT] instanceof Map
&& objects.unshift(new Map())
|| objects[FIRST_ARGUMENT] instanceof WeakSet
&& objects.unshift(objects[FIRST_ARGUMENT])
|| objects[FIRST_ARGUMENT] instanceof WeakMap
&& objects.unshift(objects[FIRST_ARGUMENT])
|| objects.unshift({})
/**
* Create a clone of an object or array.
* @param {*} object The object to clone.
* @return {Object<string, any>} Object<string, any>
*/
const createClone = (object, hash = new WeakMap()) =>
Object(object) !== object
// Deal with primitive types:
&& object
|| hash.has(object)
// Deal with cyclic references:
&& hash.get(object)
// Test for other objects:
|| (() => {
const result = object instanceof Date
&& new Date(object)
|| object instanceof RegExp
&& new RegExp(object.source, object.flags)
|| object instanceof Set
&& new Set([...object])
|| object instanceof Map
&& new Map([...object])
|| object.constructor
&& new object.constructor()
|| Object.create(null)
hash.set(object, result)
return object instanceof Set
&& new Set([...object])
|| object instanceof Map
&& new Map([...object])
|| object instanceof WeakSet
&& object
|| object instanceof WeakMap
&& object
|| Object.assign(
result,
...Object.keys(object).map(key => ({
[key]: createClone(object[key], hash)
})
)
)
}
)()
// Return cloned copy of merged objects:
return Array.isArray(objects[FIRST_ARGUMENT])
&& objects.reduce((a, b) => Array.prototype.concat(a, createClone(b)))
|| objects[FIRST_ARGUMENT] instanceof Set
&& objects.reduce((a, b) => new Set([
.../** @type {Set} */(a),
.../** @type {Set} */(createClone(b))
]))
|| objects[FIRST_ARGUMENT] instanceof Map
&& objects.reduce((a, b) => new Map([
.../** @type {Map} */(a),
.../** @type {Map} */(createClone(b))
]))
|| objects[FIRST_ARGUMENT] instanceof WeakSet
&& objects.reduce(a => a)
|| objects[FIRST_ARGUMENT] instanceof WeakMap
&& objects.reduce(a => a)
|| typeof objects[FIRST_ARGUMENT] === 'object'
&& objects.reduce((a, b) => Object.assign(a, createClone(b)))
|| typeof objects[FIRST_ARGUMENT] === 'string'
&& objects[SECOND_ARGUMENT]
|| typeof objects[FIRST_ARGUMENT] === 'number'
&& objects[SECOND_ARGUMENT]
}
export const cloneObject = object => mergeObjects(object)
export const clone = object => mergeObjects(object)
<file_sep>/types/index.d.ts
/**
* Combine two objects, merging the second into the first. Any properties already existing in the first will be replaced by those of the second. Any properties in the second not in the first will be added to it.
* This does a deep clone. Sub arrays will be cloned. If arrays consist of objects, those will be cloned. Functions will also be cloned. This also support Maps and Sets.
* Passing in just one object will return a deep clone of it.
*
* @param {Object.<string, any>[]} objects One or more objects to use for merging.
* @return {Object.<string, any>} Object.<string, any>
*/
export function mergeObjects(...objects: {
[x: string]: any;
}[]): {
[x: string]: any;
};
export function cloneObject(object: any): {
[x: string]: any;
};
export function clone(object: any): {
[x: string]: any;
};
<file_sep>/README.md
# @composi/merge-objects
This function takes objects and returns a new object with all of their properties. The last object's properties will replace those of the earlier when these have the same name. Since arrays are also objects, this will merge a series of arrays together.
Merge does a deep copy of objects, but ignores non-iterable properties.
### Note:
Passing in non-object values, such as string or numbers, will result in unpredictable results. Merge must be used only for combining objects or arrays. Although this handles objects or arrays, you cannot merge objects and arrays together, this will create an unexecpte result.
## Install
```
npm install --save-dev @composi/merge-objects
```
## Using
Merge two objects:
```javascript
import { mergeObjects } from '@composi/merge-objects'
const obj1 = {name: 'Mary'}
const obj2 = {job: 'project manager'}
const person = mergeObjects(obj1, obj2)
// returns {name: 'Mary', job: 'project manager'}
```
## Clone an Object
You can clone an object with merge. Just pass in the object. The return object will be a clone:
```javascript
import { mergeObjects } from '@composi/merge-objects'
const obj1 = {name: 'Joe', job: 'mechanic'}
const obj2 = mergeObjects(obj1)
obj1 === obj2 // returns false
```
## Merge Arrays Together
You can use mergeObjects to merge any number of arrays together. This is a deep clone, which means you can use it safely with arrays of objects.
```javascript
const arr1 = [{name: 'Joe'}, {name: 'Jane'}]
const arr2 = [{name: 'Mary'}, {name: 'Sam'}]
const arr3 = mergeObjects(arr1, arr2)
// arr3 equals [{name: 'Joe'}, {name: 'Jane'}, {name: 'Mary'}, {name: 'Sam'}])
arr1[0].name = 'Joseph' // [{name: 'Joseph'}, {name: 'Jane'}]
arr2[1].name = 'Samuel' // [{name: 'Mary'}, {name: 'Samuel'}]
// The above changes do not affect arr3:
// [{name: 'Joe'}, {name: 'Jane'}, {name: 'Mary'}, {name: 'Sam'}])
```
## Clone an Array
If you want to clone an array, just pass it as the argument:
```javascript
const arr1 = [{name: 'Joe'}, {name: 'Jane'}]
// Create clone of arr1:
const clonedArr1 = mergeObjects(arr1)
arr1[0].name = 'Joseph'
arr2[0].name // 'Joe'
```
| ef64a3bc5fcb3a66785f8a40ccf7d0f568db66c4 | [
"JavaScript",
"TypeScript",
"Markdown"
]
| 3 | JavaScript | composi/merge-objects | 869e87c7eeae46fa61b1d1df578e24a91f5872ce | 7cff2751207f350e8e584eecdc10ef6f5f3e952b |
refs/heads/master | <file_sep>import {assert, assertEquals} from 'https://deno.land/[email protected]/testing/asserts.ts';
import {readText, writeText} from './mod.ts';
type Test = [string, () => void | Promise<void>];
let originalClipboard = '';
const tests: Test[] = [
['reads without throwing', async () => {
originalClipboard = await readText({unixNewlines: false});
}],
['single line data', async () => {
const input = 'single line data';
await writeText(input);
const output = await readText();
assertEquals(output.replace(/\n+$/u, ''), input.replace(/\n+$/u, ''));
}],
['multi line data', async () => {
const input = 'multi\nline\ndata';
await writeText(input);
const output = await readText();
assertEquals(output.replace(/\n+$/u, ''), input.replace(/\n+$/u, ''));
}],
['multi line data dangling newlines', async () => {
const input = '\n\n\nmulti\n\n\n\n\n\nline\ndata\n\n\n\n\n';
await writeText(input);
const output = await readText({trimFinalNewlines: false});
assertEquals(output.replace(/\n+$/u, ''), input.replace(/\n+$/u, ''));
}],
['data with special characters', async () => {
const input = '`~!@#$%^&*()_+-=[]{};\':",./<>?\t\n';
await writeText(input);
const output = await readText({trimFinalNewlines: false});
assertEquals(output.replace(/\n+$/u, ''), input.replace(/\n+$/u, ''));
}],
['data with unicode characters', async () => {
const input = 'Rafał';
await writeText(input);
const output = await readText();
assertEquals(output.replace(/\n+$/u, ''), input.replace(/\n+$/u, ''));
}],
['option: trimFinalNewlines', async () => {
const input = 'hello world\n\n';
const inputTrimmed = 'hello world';
await writeText(input);
const output = await readText({trimFinalNewlines: false});
const outputTrimmed = await readText({trimFinalNewlines: true});
const outputDefault = await readText();
assert(output !== inputTrimmed && output.trim() === inputTrimmed);
assertEquals(inputTrimmed, outputTrimmed);
assertEquals(inputTrimmed, outputDefault);
}],
['option: unixNewlines', async () => {
const inputCRLF = 'hello\r\nworld';
const inputLF = 'hello\nworld';
await writeText(inputCRLF);
const output = await readText({unixNewlines: false});
const outputUnix = await readText({unixNewlines: true});
const outputDefault = await readText();
assertEquals(inputCRLF, output);
assertEquals(inputLF, outputUnix);
assertEquals(inputLF, outputDefault);
}],
['writes without throwing', async () => {
await writeText(originalClipboard);
}],
];
for (const [name, fn] of tests) Deno.test({fn, name});
<file_sep>import * as clipboard from './mod.ts';
console.log(await clipboard.readText());
<file_sep>import * as clipboard from './mod.ts';
await clipboard.writeText('some text');
const text = await clipboard.readText();
console.log(text === 'some text'); // true
<file_sep>import * as clipboard from './mod.ts';
const text = 'abcaaa';
await clipboard.writeText(text);
console.log(await clipboard.readText());
<file_sep>Deno clipboard library
=
[![Build Status][actions-img]][actions-url]<br>(CI tests on Linux, Mac, Windows)
> On Linux, `xsel` or `xclip` must be installed and in your `PATH`.
Usage
-
```ts
import * as clipboard from 'https://deno.land/x/clipboard/mod.ts';
await clipboard.writeText('some text');
const text = await clipboard.readText();
console.log(text === 'some text'); // true
```
Goals
-
- use Web [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard)
- use readText and writeText (no read and write, see the spec)
- work on Linux, macOS, Windows
- don't bundle any binaries
It will spawn external processes so unfortunately
it will require the all-powerful `--allow-run` flag.
If Deno exposes a Clipboard API
(with new permissions like `--allow-copy` and `--allow-paste`)
then hopefully this will be obsolete. See the relevant issue:
- [denoland/deno#3450 Support of Clipboard API without `--deno-run`](https://github.com/denoland/deno/issues/3450)
Options
-
The clipboard on Windows always adds a trailing newline if there was none,
which makes single line strings end with a newline. Newlines in the clipboard are sometimes
problematic (like automatically starting commands when pasted into the terminal), so this module trims trailing newlines by default. It also converts CRLF (Windows) newlines to LF (Unix) newlines by default when reading the clipboard.
Both of these options can be disabled independently:
```ts
import * as clipboard from 'https://deno.land/x/clipboard/mod.ts';
const options: clipboard.ReadTextOptions = {
trimFinalNewlines: false, // don't trim trailing newlines
unixNewlines: false, // don't convert CRLF to LF
};
const clipboardText = await clipboard.readText(options);
```
Issues
-
For any bug reports or feature requests please
[post an issue on GitHub][issues-url].
Author
-
[**<NAME>**](https://pocztarski.com/)
<br/>
[![Follow on GitHub][github-follow-img]][github-follow-url]
[![Follow on Twitter][twitter-follow-img]][twitter-follow-url]
<br/>
[![Follow on Stack Exchange][stackexchange-img]][stackoverflow-url]
Contributors
-
- [**<NAME>**](https://github.com/jsejcksn)
License
-
MIT License (Expat). See [LICENSE.md](LICENSE.md) for details.
[github-url]: https://github.com/rsp/deno-clipboard
[readme-url]: https://github.com/rsp/deno-clipboard#readme
[issues-url]: https://github.com/rsp/deno-clipboard/issues
[license-url]: https://github.com/rsp/deno-clipboard/blob/master/LICENSE.md
[actions-url]: https://github.com/rsp/deno-clipboard/actions
[actions-img]: https://github.com/rsp/deno-clipboard/workflows/ci/badge.svg?branch=master&event=push
[travis-url]: https://travis-ci.org/rsp/deno-clipboard
[travis-img]: https://travis-ci.org/rsp/deno-clipboard.svg?branch=master
[snyk-url]: https://snyk.io/test/github/rsp/deno-clipboard
[snyk-img]: https://snyk.io/test/github/rsp/deno-clipboard/badge.svg
[david-url]: https://david-dm.org/rsp/deno-clipboard
[david-img]: https://david-dm.org/rsp/deno-clipboard/status.svg
[install-img]: https://nodei.co/npm/ende.png?compact=true
[downloads-img]: https://img.shields.io/npm/dt/ende.svg
[license-img]: https://img.shields.io/npm/l/ende.svg
[stats-url]: http://npm-stat.com/charts.html?package=ende
[github-follow-url]: https://github.com/rsp
[github-follow-img]: https://img.shields.io/github/followers/rsp.svg?style=social&logo=github&label=Follow
[twitter-follow-url]: https://twitter.com/intent/follow?screen_name=pocztarski
[twitter-follow-img]: https://img.shields.io/twitter/follow/pocztarski.svg?style=social&logo=twitter&label=Follow
[stackoverflow-url]: https://stackoverflow.com/users/613198/rsp
[stackexchange-url]: https://stackexchange.com/users/303952/rsp
[stackexchange-img]: https://stackexchange.com/users/flair/303952.png
<file_sep>#!/bin/sh
deno test --allow-run test.ts
<file_sep>// Copyright (c) 2019 <NAME>, <NAME>. All rights reserved.
// MIT License (Expat). See: https://github.com/rsp/deno-clipboard
const decoder = new TextDecoder();
const encoder = new TextEncoder();
type LinuxBinary = 'wsl' | 'xclip' | 'xsel';
type Config = {
linuxBinary: LinuxBinary;
};
const config: Config = {linuxBinary: 'xsel'};
const errMsg = {
genericRead: 'There was a problem reading from the clipboard',
genericWrite: 'There was a problem writing to the clipboard',
noClipboard: 'No supported clipboard utility. "xsel" or "xclip" must be installed.',
noClipboardWSL: 'Windows tools not found in $PATH. See https://docs.microsoft.com/en-us/windows/wsl/interop#run-windows-tools-from-linux',
osUnsupported: 'Unsupported operating system',
};
const normalizeNewlines = (str: string) => str.replace(/\r\n/gu, '\n');
const trimNewlines = (str: string) => str.replace(/(?:\r\n|\n)+$/u, '');
/**
* Options to change the parsing behavior when reading the clipboard text
*
* `trimFinalNewlines?` — Trim trailing newlines. Default is `true`.
*
* `unixNewlines?` — Convert all CRLF newlines to LF newlines. Default is `true`.
*/
export type ReadTextOptions = {
trimFinalNewlines?: boolean;
unixNewlines?: boolean;
};
type TextClipboard = {
readText: (readTextOptions?: ReadTextOptions) => Promise<string>;
writeText: (data: string) => Promise<void>;
};
const shared = {
async readText (
cmd: string[],
{trimFinalNewlines = true, unixNewlines = true}: ReadTextOptions = {},
): Promise<string> {
const p = Deno.run({cmd, stdout: 'piped'});
const {success} = await p.status();
const stdout = decoder.decode(await p.output());
p.close();
if (!success) throw new Error(errMsg.genericRead);
let result = stdout;
if (unixNewlines) result = normalizeNewlines(result);
if (trimFinalNewlines) return trimNewlines(result);
return result;
},
async writeText (cmd: string[], data: string): Promise<void> {
const p = Deno.run({cmd, stdin: 'piped'});
if (!p.stdin) throw new Error(errMsg.genericWrite);
await p.stdin.write(encoder.encode(data));
p.stdin.close();
const {success} = await p.status();
if (!success) throw new Error(errMsg.genericWrite);
p.close();
},
};
const darwin: TextClipboard = {
readText (readTextOptions?: ReadTextOptions): Promise<string> {
const cmd: string[] = ['pbpaste'];
return shared.readText(cmd, readTextOptions);
},
writeText (data: string): Promise<void> {
const cmd: string[] = ['pbcopy'];
return shared.writeText(cmd, data);
},
};
const linux: TextClipboard = {
readText (readTextOptions?: ReadTextOptions): Promise<string> {
const cmds: {[key in LinuxBinary]: string[]} = {
wsl: ['powershell.exe', '-NoProfile', '-Command', 'Get-Clipboard'],
xclip: ['xclip', '-selection', 'clipboard', '-o'],
xsel: ['xsel', '-b', '-o'],
};
const cmd = cmds[config.linuxBinary];
return shared.readText(cmd, readTextOptions);
},
writeText (data: string): Promise<void> {
const cmds: {[key in LinuxBinary]: string[]} = {
wsl: ['clip.exe'],
xclip: ['xclip', '-selection', 'clipboard'],
xsel: ['xsel', '-b', '-i'],
};
const cmd = cmds[config.linuxBinary];
return shared.writeText(cmd, data);
},
};
const windows: TextClipboard = {
readText (readTextOptions?: ReadTextOptions): Promise<string> {
const cmd: string[] = ['powershell', '-NoProfile', '-Command', 'Get-Clipboard'];
return shared.readText(cmd, readTextOptions);
},
writeText (data: string): Promise<void> {
const cmd: string[] = ['powershell', '-NoProfile', '-Command', '$input|Set-Clipboard'];
return shared.writeText(cmd, data);
},
};
const getProcessOutput = async (cmd: string[]): Promise<string> => {
try {
const p = Deno.run({cmd, stdout: 'piped'});
const stdout = decoder.decode(await p.output());
p.close();
return stdout.trim();
}
catch (err) {
return '';
}
};
const resolveLinuxBinary = async (): Promise<LinuxBinary> => {
type BinaryEntry = [LinuxBinary, () => boolean | Promise<boolean>];
const binaryEntries: BinaryEntry[] = [
['wsl', async () => {
const isWSL = (await getProcessOutput(['uname', '-r', '-v'])).toLowerCase().includes('microsoft');
if (!isWSL) return false;
const hasWindowsUtils = (
Boolean(await getProcessOutput(['which', 'clip.exe']))
&& Boolean(await getProcessOutput(['which', 'powershell.exe']))
);
if (hasWindowsUtils) return true;
throw new Error(errMsg.noClipboardWSL);
}],
['xsel', async () => Boolean(await getProcessOutput(['which', 'xsel']))],
['xclip', async () => Boolean(await getProcessOutput(['which', 'xclip']))],
];
for (const [binary, matchFn] of binaryEntries) {
const binaryMatches = await matchFn();
if (binaryMatches) return binary;
}
throw new Error(errMsg.noClipboard);
};
type Clipboards = {[key in typeof Deno.build.os]: TextClipboard};
const clipboards: Clipboards = {
darwin,
linux,
windows,
};
const {build: {os}} = Deno;
if (os === 'linux') config.linuxBinary = await resolveLinuxBinary();
else if (!clipboards[os]) throw new Error(errMsg.osUnsupported);
/**
* Reads the clipboard and returns a string containing the text contents. Requires the `--allow-run` flag.
*/
export const readText: (readTextOptions?: ReadTextOptions) => Promise<string> = clipboards[os].readText;
/**
* Writes a string to the clipboard. Requires the `--allow-run` flag.
*/
export const writeText: (data: string) => Promise<void> = clipboards[os].writeText;
| bf6426013443b5bcb15488c5e74ddb0b1f1085a0 | [
"Markdown",
"TypeScript",
"Shell"
]
| 7 | TypeScript | jsejcksn/deno-clipboard | 4f7dfd2bac74a4cf2f2a69e2176b0e8bedb31231 | b7b0a92db208a30287624bb22a2a657cc50f85f4 |
refs/heads/master | <file_sep># anuglar2-bootstrap JSPM demo application
This a demo application based on JSPM for the [angular2-bootstrap](https://github.com/SebastianM/angular2-bootstrap) project.
## Installation
1. Install JSPM `npm i -g jspm` - (For more details see: https://jspm.io/)
2. run `npm i`
3. run `jspm install`
4. run `npm run bundle` (and every time you have changed the sourcecode)
5. run `./node_modules/.bin/http-server` to start a local HTTP server.
<file_sep>import {Component, View, bootstrap} from 'angular2/angular2';
import {Progressbar} from 'angular2-bootstrap/angular2-bootstrap';
@Component({
selector: 'demo-app'
})
@View({
template: `
<h2>Progressbar</h2>
<boot-progressbar [value]="progressbarValue"></boot-progressbar>
`,
directives: [Progressbar]
})
class DemoAppCmp {
progressbarValue: number;
constructor() {
this.progressbarValue = 10;
setInterval(() => {
this.progressbarValue = Math.random() * 100;
}, 2000)
}
}
bootstrap(DemoAppCmp);
| 073d658cbe66c323d3db554722fb4ec92589876d | [
"Markdown",
"TypeScript"
]
| 2 | Markdown | SebastianM/angular2-bootstrap-demo-app | 3ba5e5d6b0664fb6dd7ee8eb6bff3b7badd159c8 | 4426ddce5d3f4bd6adad68281c006b39f4dfb284 |
refs/heads/master | <repo_name>bustosadrian/FNZ.Bomb<file_sep>/FNZ.Bomb/Controls/KeyPad.xaml.cs
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace FNZ.Bomb.Controls
{
/// <summary>
/// Interaction logic for KeyPad.xaml
/// </summary>
public partial class KeyPad : UserControl
{
public KeyPad()
{
InitializeComponent();
}
private void SetDigit(string value)
{
if (CanDigitExecute())
{
if (Code.Length < Length)
{
Code += value;
}
RaiseAllCanExecute();
}
}
private void ClearEverything()
{
if (CanClearExecute())
{
if (!string.IsNullOrEmpty(Code))
{
Code = "";
RaiseAllCanExecute();
}
}
}
private void Clear()
{
if (CanClearExecute())
{
if (Code.Length > 0)
{
Code = Code.Substring(0, Code.Length - 1);
}
RaiseAllCanExecute();
}
}
private void Submit()
{
if (CanSubmitExecute())
{
Command?.Execute(Code);
RaiseAllCanExecute();
}
}
private void Press(Button button)
{
button.GetType().GetMethod("set_IsPressed",
BindingFlags.Instance |
BindingFlags.NonPublic)
.Invoke(button, new object[] { true });
button.GetType().GetMethod("set_IsPressed",
BindingFlags.Instance |
BindingFlags.NonPublic)
.Invoke(button, new object[] { false });
button.Command?.Execute(button.CommandParameter);
}
private void Self_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
RaiseAllCanExecute();
}
#region Key Handler
public void Hit(KeyEventArgs e)
{
if (IsEnabled)
{
if (!e.Handled)
{
Button b = null;
if ((e.Key >= Key.D0 && e.Key <= Key.D9)
|| (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
{
if (CanDigitExecute())
{
switch (e.Key)
{
case Key.D0:
case Key.NumPad0:
b = btn0;
break;
case Key.D1:
case Key.NumPad1:
b = btn1;
break;
case Key.D2:
case Key.NumPad2:
b = btn2;
break;
case Key.D3:
case Key.NumPad3:
b = btn3;
break;
case Key.D4:
case Key.NumPad4:
b = btn4;
break;
case Key.D5:
case Key.NumPad5:
b = btn5;
break;
case Key.D6:
case Key.NumPad6:
b = btn6;
break;
case Key.D7:
case Key.NumPad7:
b = btn7;
break;
case Key.D8:
case Key.NumPad8:
b = btn8;
break;
case Key.D9:
case Key.NumPad9:
b = btn9;
break;
}
}
}
else if (e.Key == Key.Delete
|| e.Key == Key.Back
|| e.Key == Key.Decimal)
{
if (CanClearExecute())
{
b = btnClear;
}
}
else if (e.Key == Key.Escape)
{
if (CanClearExecute())
{
ClearEverything();
}
}
else if (e.Key == Key.Enter)
{
if (CanSubmitExecute())
{
b = btnSubmit;
}
}
if (b != null)
{
Press(b);
e.Handled = true;
}
}
}
}
#endregion
#region Commands
private DelegateCommand<string> _digitCommand;
public DelegateCommand<string> DigitCommand
{
get
{
if(_digitCommand == null)
{
_digitCommand = new DelegateCommand<string>(SetDigit, CanDigitExecute);
}
return _digitCommand;
}
}
private DelegateCommand _clearCommand;
public DelegateCommand ClearCommand
{
get
{
if (_clearCommand == null)
{
_clearCommand = new DelegateCommand(Clear, CanClearExecute);
}
return _clearCommand;
}
}
private DelegateCommand _submitCommand;
public DelegateCommand SubmitCommand
{
get
{
if (_submitCommand == null)
{
_submitCommand = new DelegateCommand(Submit, CanSubmitExecute);
}
return _submitCommand;
}
}
private bool CanExecute()
{
return IsEnabled;
}
private bool CanDigitExecute(string value = null)
{
if (!CanExecute())
{
return false;
}
return true;
}
private bool CanOperationsExecute()
{
if (!CanExecute())
{
return false;
}
if(Code == null || Code.Length == 0)
{
return false;
}
return true;
}
private bool CanClearExecute()
{
if (!CanOperationsExecute())
{
return false;
}
return true;
}
private bool CanSubmitExecute()
{
if (!CanOperationsExecute())
{
return false;
}
return true;
}
private void RaiseAllCanExecute()
{
DigitCommand.RaiseCanExecuteChanged();
ClearCommand.RaiseCanExecuteChanged();
SubmitCommand.RaiseCanExecuteChanged();
}
#endregion
#region Commands Properties
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(DelegateCommand<string>),
typeof(KeyPad), new PropertyMetadata(null));
public DelegateCommand<string> Command
{
get { return (DelegateCommand<string>)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
#endregion
#region Properties
public static readonly DependencyProperty CodeProperty =
DependencyProperty.Register("Code", typeof(string),
typeof(KeyPad), new PropertyMetadata(""));
public string Code
{
get { return (string)GetValue(CodeProperty); }
set { SetValue(CodeProperty, value); }
}
public static readonly DependencyProperty LenghtProperty =
DependencyProperty.Register("Length", typeof(int),
typeof(KeyPad), new PropertyMetadata(0));
public int Length
{
get { return (int)GetValue(LenghtProperty); }
set { SetValue(LenghtProperty, value); }
}
public static readonly DependencyProperty AlignmentProperty =
DependencyProperty.Register("Alignment", typeof(TextAlignment),
typeof(KeyPad), new PropertyMetadata(TextAlignment.Right));
public TextAlignment Alignment
{
get { return (TextAlignment)GetValue(AlignmentProperty); }
set { SetValue(LenghtProperty, value); }
}
#endregion
}
}
<file_sep>/FNZ.Bomb/Converters/NullToEmptyConverter.cs
using System;
using System.Globalization;
using System.Windows.Data;
namespace FNZ.Bomb.Converters
{
public class NullToEmptyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string retval = null;
retval = value as string ?? "";
return retval;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
}
<file_sep>/FNZ.Bomb/Extensions.cs
using System.Windows;
using System.Windows.Controls;
namespace FNZ.Bomb
{
public class Extensions
{
public static CornerRadius GetCornerRadius(DependencyObject obj) => (CornerRadius)obj.GetValue(CornerRadiusProperty);
public static void SetCornerRadius(DependencyObject obj, CornerRadius value) => obj.SetValue(CornerRadiusProperty, value);
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.RegisterAttached(nameof(Border.CornerRadius), typeof(CornerRadius),
typeof(Extensions), new UIPropertyMetadata(new CornerRadius()));
}
}
<file_sep>/FNZ.Bomb/AppSettings.cs
using System.Windows;
namespace FNZ.Bomb
{
public class AppSettings
{
public AppSettings()
{
CodeLength = 6;
WindowStyle = System.Windows.WindowStyle.SingleBorderWindow;
Alignment = TextAlignment.Right;
}
#region Properties
public int? CodeLength
{
get;
set;
}
public WindowStyle? WindowStyle
{
get;
set;
}
public TextAlignment? Alignment
{
get;
set;
}
#endregion
}
}
<file_sep>/FNZ.Bomb/Controls/Display.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
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;
namespace FNZ.Bomb.Controls
{
/// <summary>
/// Interaction logic for Display.xaml
/// </summary>
public partial class Display : UserControl
{
public Display()
{
InitializeComponent();
}
private void DisplayCode()
{
string[] digits = new string[Length];
if(Code != null)
{
char[] chars = Code.ToCharArray();
if(Alignment == TextAlignment.Left)
{
for (int i = 0; i < digits.Length && i < Code.Length; i++)
{
var o = chars[i];
digits[i] = o.ToString();
}
}
else
{
for (int i = 0; i < digits.Length && i < Code.Length; i++)
{
var o = chars[i];
digits[Length - i - 1] = o.ToString();
}
}
}
if(Digits == null || Digits.Count != digits.Length)
{
Digits = new ObservableCollection<string>(digits.ToList());
}
else
{
for(int i = 0; i < digits.Length; i++)
{
Digits[i] = digits[i];
}
}
}
#region Properties
public static readonly DependencyProperty CodeProperty =
DependencyProperty.Register("Code", typeof(string),
typeof(Display), new PropertyMetadata(null, UpdateDisplay));
public string Code
{
get { return (string)GetValue(CodeProperty); }
set { SetValue(CodeProperty, value); }
}
public static readonly DependencyProperty DigitsProperty =
DependencyProperty.Register("Digits", typeof(ObservableCollection<string>),
typeof(Display), new PropertyMetadata(null));
public ObservableCollection<string> Digits
{
get { return (ObservableCollection<string>)GetValue(DigitsProperty); }
set { SetValue(DigitsProperty, value); }
}
public static readonly DependencyProperty LenghtProperty =
DependencyProperty.Register("Length", typeof(int),
typeof(Display), new PropertyMetadata(0, UpdateDisplay));
public int Length
{
get { return (int)GetValue(LenghtProperty); }
set { SetValue(LenghtProperty, value); }
}
private static void UpdateDisplay(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((Display)d).DisplayCode();
}
public static readonly DependencyProperty AlignmentProperty =
DependencyProperty.Register("Alignment", typeof(TextAlignment),
typeof(Display), new PropertyMetadata(TextAlignment.Right));
public TextAlignment Alignment
{
get { return (TextAlignment)GetValue(AlignmentProperty); }
set { SetValue(LenghtProperty, value); }
}
#endregion
}
}
<file_sep>/FNZ.Bomb/MainWindowViewModel.cs
using System.Windows;
namespace FNZ.Bomb
{
public class MainWindowViewModel : BaseViewModel
{
public MainWindowViewModel()
{
WindowStyle = SettingsHandler.Instance.WindowStyle.Value;
CodeLength = SettingsHandler.Instance.CodeLength.Value;
Alignment = SettingsHandler.Instance.Alignment.Value;
EnableKeyPad();
}
private void HeaderTapped()
{
if(WindowStyle == WindowStyle.SingleBorderWindow)
{
WindowStyle = WindowStyle.None;
}
else
{
WindowStyle = WindowStyle.SingleBorderWindow;
}
}
private void Submit(string code)
{
DisableKeyPad();
SubmitedCode = code;
}
private void VerbiageHidden()
{
Code = null;
EnableKeyPad();
}
private void EnableKeyPad()
{
IsKeyPadEnabled = true;
}
private void DisableKeyPad()
{
IsKeyPadEnabled = false;
}
#region Commands
private DelegateCommand _headerCommand;
public DelegateCommand HeaderCommand
{
get
{
if (_headerCommand == null)
{
_headerCommand = new DelegateCommand(HeaderTapped);
}
return _headerCommand;
}
}
private DelegateCommand<string> _submitCommand;
public DelegateCommand<string> SubmitCommand
{
get
{
if(_submitCommand == null)
{
_submitCommand = new DelegateCommand<string>(Submit);
}
return _submitCommand;
}
}
private DelegateCommand _verbiageHiddenCommand;
public DelegateCommand VerbiageHiddenCommand
{
get
{
if (_verbiageHiddenCommand == null)
{
_verbiageHiddenCommand = new DelegateCommand(VerbiageHidden);
}
return _verbiageHiddenCommand;
}
}
#endregion
#region Properties
private WindowStyle _windowStyle;
public WindowStyle WindowStyle
{
get
{
return _windowStyle;
}
set
{
_windowStyle = value;
if (_windowStyle == WindowStyle.None)
{
ResizeMode = ResizeMode.NoResize;
}
else
{
ResizeMode = ResizeMode.CanResize;
}
OnPropertyChanged("WindowStyle");
}
}
private ResizeMode _resizeMode;
public ResizeMode ResizeMode
{
get
{
return _resizeMode;
}
set
{
_resizeMode = value;
OnPropertyChanged("ResizeMode");
}
}
private WindowState _windowState;
public WindowState WindowState
{
get
{
return _windowState;
}
set
{
_windowState = value;
OnPropertyChanged("WindowState");
}
}
private int _codeLength;
public int CodeLength
{
get
{
return _codeLength;
}
set
{
_codeLength = value;
OnPropertyChanged("CodeLength");
}
}
private TextAlignment _alignment;
public TextAlignment Alignment
{
get
{
return _alignment;
}
set
{
_alignment = value;
OnPropertyChanged("Alignment");
}
}
private string _code;
public string Code
{
get
{
return _code;
}
set
{
_code = value;
OnPropertyChanged("Code");
}
}
private string _submitedCode;
public string SubmitedCode
{
get
{
return _submitedCode;
}
set
{
_submitedCode = value;
OnPropertyChanged("SubmitedCode");
}
}
private bool _isKeyPadEnabled;
public bool IsKeyPadEnabled
{
get
{
return _isKeyPadEnabled;
}
set
{
_isKeyPadEnabled = value;
OnPropertyChanged("IsKeyPadEnabled");
}
}
#endregion
}
}
<file_sep>/FNZ.Bomb/Controls/Header.xaml.cs
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.Navigation;
using System.Windows.Shapes;
namespace FNZ.Bomb.Controls
{
/// <summary>
/// Interaction logic for Header.xaml
/// </summary>
public partial class Header : UserControl
{
public Header()
{
InitializeComponent();
}
private void UserControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
Command?.Execute(null);
}
#region Properties
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(DelegateCommand),
typeof(Header), new PropertyMetadata(null));
public DelegateCommand Command
{
get { return (DelegateCommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
#endregion
}
}
<file_sep>/FNZ.Bomb/Converters/BooleanToVisibilityConverter.cs
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace FNZ.Bomb.Converters
{
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var flag = false;
if (value is bool)
{
flag = (bool)value;
}
else if (value is bool?)
{
var nullable = (bool?)value;
flag = nullable.HasValue ? nullable.Value : false;
}
if (IsInverse)
{
flag = !flag;
}
return (flag ? Visibility.Visible : Visibility.Collapsed);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public bool IsInverse { get; set; }
}
}
<file_sep>/FNZ.Bomb/Controls/Verbiage.xaml.cs
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace FNZ.Bomb.Controls
{
/// <summary>
/// Interaction logic for Verbiage.xaml
/// </summary>
public partial class Verbiage : UserControl
{
public Verbiage()
{
InitializeComponent();
}
private void DefuseCode()
{
if(Code == null)
{
State = null;
}
else
{
State = VerbiageState.DEFUSING;
RaiseDefusing();
}
}
public void Hit(KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
case Key.Escape:
Hide();
e.Handled = true;
break;
}
}
private void Self_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Hide();
}
private void Hide()
{
switch (State)
{
case VerbiageState.DEFUSED:
case VerbiageState.EXPLODED:
ExplodeStoryboard.Stop(this);
Code = null;
State = null;
RaiseHiden();
break;
default:
break;
}
}
private void Storyboard_Completed(object sender, EventArgs e)
{
bool defused = BombCore.Defuse(Code);
if (defused)
{
State = VerbiageState.DEFUSED;
}
else
{
ExplodeStoryboard.Begin(this, true);
State = VerbiageState.EXPLODED;
}
}
#region Commands Properties
public static readonly DependencyProperty HiddenCommandProperty =
DependencyProperty.Register("HiddenCommand", typeof(DelegateCommand),
typeof(Verbiage), new PropertyMetadata(null));
public DelegateCommand HiddenCommand
{
get { return (DelegateCommand)GetValue(HiddenCommandProperty); }
set { SetValue(HiddenCommandProperty, value); }
}
#endregion
#region Events
public static readonly RoutedEvent DefusingEvent = EventManager.RegisterRoutedEvent(
"Defusing", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Verbiage));
public event RoutedEventHandler Defusing
{
add { AddHandler(DefusingEvent, value); }
remove { RemoveHandler(DefusingEvent, value); }
}
private void RaiseDefusing()
{
RaiseEvent(new RoutedEventArgs(DefusingEvent));
}
public static readonly RoutedEvent HiddenEvent = EventManager.RegisterRoutedEvent(
"Hidden", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Verbiage));
public event RoutedEventHandler Hidden
{
add { AddHandler(HiddenEvent, value); }
remove { RemoveHandler(HiddenEvent, value); }
}
private void RaiseHiden()
{
//RaiseEvent(new RoutedEventArgs(HiddenEvent));
HiddenCommand?.Execute(null);
}
#endregion
#region Properties
private Storyboard ExplodeStoryboard
{
get
{
return (Storyboard)FindResource("ExplodeStoryboard"); }
}
public static readonly DependencyProperty CodeProperty =
DependencyProperty.Register("Code", typeof(string),
typeof(Verbiage), new PropertyMetadata(null, OnCodeChanged));
public string Code
{
get { return (string)GetValue(CodeProperty); }
set { SetValue(CodeProperty, value); }
}
private static void OnCodeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((Verbiage)d).DefuseCode();
}
public static readonly DependencyProperty StateProperty =
DependencyProperty.Register("State", typeof(VerbiageState?),
typeof(Verbiage), new PropertyMetadata(null));
public VerbiageState? State
{
get { return (VerbiageState?)GetValue(StateProperty); }
set { SetValue(StateProperty, value); }
}
#endregion
}
public enum VerbiageState
{
DEFUSING, DEFUSED, EXPLODED
}
public class VerbiageBoxConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
SolidColorBrush retval = null;
if(value is VerbiageState)
{
VerbiageState state = (VerbiageState)value;
switch (state)
{
case VerbiageState.DEFUSING:
retval = (SolidColorBrush)Application.Current.FindResource("VerbiageDefusing");
break;
case VerbiageState.DEFUSED:
retval = (SolidColorBrush)Application.Current.FindResource("VerbiageDefused");
break;
case VerbiageState.EXPLODED:
retval = (SolidColorBrush)Application.Current.FindResource("VerbiageExploded");
break;
}
}
return retval;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class VerbiageBoxMessageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string retval = null;
if (value is VerbiageState)
{
VerbiageState state = (VerbiageState)value;
switch (state)
{
case VerbiageState.DEFUSING:
//retval = (string)Application.Current.FindResource("to.defusing");
retval = "DEFUSING...";
break;
case VerbiageState.DEFUSED:
//retval = (string)Application.Current.FindResource("defused");
retval = "DEFUSED!";
break;
case VerbiageState.EXPLODED:
//retval = (string)Application.Current.FindResource("explosion");
retval = "BOOM!";
break;
}
}
return retval;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
<file_sep>/FNZ.Bomb/Controls/Digit.xaml.cs
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace FNZ.Bomb.Controls
{
/// <summary>
/// Interaction logic for Digit.xaml
/// </summary>
public partial class Digit : UserControl
{
public Digit()
{
InitializeComponent();
}
private void ValueChanged(string oldValue, string newValue)
{
if(!string.IsNullOrEmpty(oldValue) && string.IsNullOrEmpty(newValue))
{
ClearStoryboard.Begin(this, true);
}
}
#region Properties
private Storyboard ClearStoryboard
{
get
{
return (Storyboard)FindResource("ClearStoryboard");
}
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(string),
typeof(Digit), new PropertyMetadata("*", OnValueChanged));
public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((Digit)d).ValueChanged(e.OldValue as string, e.NewValue as string);
}
public static readonly DependencyProperty NumberProperty =
DependencyProperty.Register("Number", typeof(string),
typeof(Digit), new PropertyMetadata(null));
public string Number
{
get { return (string)GetValue(NumberProperty); }
set { SetValue(NumberProperty, value); }
}
//public static new readonly DependencyProperty FontSizeProperty =
// DependencyProperty.Register("FontSize", typeof(string),
// typeof(Digit), new PropertyMetadata(null));
//public new string FontSizde
//{
// get { return (string)GetValue(FontSizeProperty); }
// set { SetValue(FontSizeProperty, value); }
//}
#endregion
}
}
<file_sep>/FNZ.Bomb/BombCore.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace FNZ.Bomb
{
public class BombCore
{
public static bool Defuse(string code)
{
List<char> input = code.ToCharArray().ToList();
if (!input.Any()) return false;
var iDay = DateTime.ParseExact("28-October-1918", "dd-MMMM-yyyy", null);
var sIDay = iDay.ToString("yyyyMMdd");
var a = char.Parse((int.Parse(iDay.ToString(("MM"))) - 1).ToString());
var n_a = int.Parse(a.ToString());
if (input[0] != a)
{
return false;
}
input.RemoveAt(0);
if (!input.Any()) return false;
if (input[0] != char.Parse(sIDay.Substring(6, 1)))
{
return false;
}
input.RemoveAt(0);
if (!input.Any()) return false;
if (input[0] != char.Parse(Math.Abs(n_a - int.Parse(sIDay)).ToString().Substring(0, 1)))
{
return false;
}
input.RemoveAt(0);
if (!input.Any()) return false;
if (input[0] != char.Parse((n_a / 2).ToString()))
{
return false;
}
input.RemoveAt(0);
if (input.Any())
{
return false;
}
return true;
}
}
}
<file_sep>/FNZ.Bomb/MainWindow.xaml.cs
using System.Windows;
using System.Windows.Input;
namespace FNZ.Bomb
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
KeyPad.Hit(e);
if (!e.Handled)
{
Verbiage.Hit(e);
}
Focus();
}
}
}
<file_sep>/FNZ.Bomb/Converters/CountConverter.cs
using System;
using System.Globalization;
using System.Windows.Data;
namespace FNZ.Bomb.Converters
{
class CountConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int retval = 0;
if (value is System.Collections.ICollection)
{
System.Collections.ICollection collection = (System.Collections.ICollection)value;
retval = collection.Count;
}
return retval;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
<file_sep>/FNZ.Bomb/SettingsHandler.cs
using System;
using System.Configuration;
using System.Windows;
namespace FNZ.Bomb
{
public class SettingsHandler
{
private SettingsHandler()
{
}
private static AppSettings Load()
{
AppSettings retval = null;
AppSettings defaultSettings = new AppSettings();
retval = new AppSettings();
try
{
retval.CodeLength = int.Parse(ConfigurationManager.AppSettings["CodeLength"]);
}
catch
{
}
try
{
retval.WindowStyle = (WindowStyle)System.Enum.Parse(
typeof(WindowStyle), ConfigurationManager.AppSettings["WindowStyle"]);
}
catch
{
}
try
{
retval.Alignment = (TextAlignment)System.Enum.Parse(
typeof(TextAlignment), ConfigurationManager.AppSettings["Alignment"]);
}
catch
{
}
retval.CodeLength = retval.CodeLength ?? defaultSettings.CodeLength;
retval.WindowStyle = retval.WindowStyle ?? defaultSettings.WindowStyle;
retval.Alignment = retval.Alignment ?? defaultSettings.Alignment;
return retval;
}
#region Properties
private static AppSettings _instance;
public static AppSettings Instance
{
get
{
if(_instance == null)
{
_instance = Load();
}
return _instance;
}
}
#endregion
}
}
| 3a6aabb25c6720c0e3c6e8044123d78b3f9674e6 | [
"C#"
]
| 14 | C# | bustosadrian/FNZ.Bomb | fcb511744432a7a7ed1a3b6f5418b3db62919a6f | 27c2c395405e1c140f88a778e0ee319dbcb83cc8 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
class PcdReader
{
Header header;
List<Point3D> point3Ds;
int pointCount = 0;
/// <summary>
/// 获取头部信息
/// </summary>
/// <param name="s"></param>
private void GetHeader(string s)
{
header = new Header();
Regex reg_VERSION = new Regex("VERSION .*"); //版本
Regex reg_FIELDS = new Regex("FIELDS .*"); //字段
Regex reg_SIZE = new Regex("SIZE .*"); //数据大小
Regex reg_TYPE = new Regex("TYPE .*"); //存储数据的格式 F-Float U-uint
Regex reg_COUNT = new Regex("COUNT .*");
Regex reg_WIDTH = new Regex("WIDTH .*");
Regex reg_HEIGHT = new Regex("HEIGHT .*");
Regex reg_VIEWPOINT = new Regex("VIEWPOINT .*");
Regex reg_POINTS = new Regex("POINTS .*"); //点的数量
Regex reg_DATA = new Regex("DATA .*"); //数据类型
Match m_VERSION = reg_VERSION.Match(s);
header.VERSION = m_VERSION.Value;
header.FistLine = "# .PCD v" + header.VERSION.Split(' ')[1] + " - Point Cloud Data file format";
Match m_FIELDS = reg_FIELDS.Match(s);
header.FIELDS = m_FIELDS.Value;
Match m_SIZE = reg_SIZE.Match(s);
header.SIZE = m_SIZE.Value;
Match m_TYPE = reg_TYPE.Match(s);
header.TYPE = m_TYPE.Value;
Match m_COUNT = reg_COUNT.Match(s);
header.COUNT = m_COUNT.Value;
Match m_WIDTH = reg_WIDTH.Match(s);
header.WIDTH = m_WIDTH.Value;
Match m_HEIGHT = reg_HEIGHT.Match(s);
header.HEIGHT = m_HEIGHT.Value;
Match m_VIEWPOINT = reg_VIEWPOINT.Match(s);
header.VIEWPOINT = m_VIEWPOINT.Value;
Match m_POINTS = reg_POINTS.Match(s);
header.POINTS = m_POINTS.Value;
Match m_DATA = reg_DATA.Match(s);
header.DATA = m_DATA.Value;
}
/// <summary>
/// 读取 binary 和 binary_compressed 格式的 pcd 文件
/// </summary>
private void ReadPcdFile(string path)
{
byte[] bytes = File.ReadAllBytes(path); //读取文件到字节数组
string text = Encoding.UTF8.GetString(bytes); //转为文本,方便分离文件头部信息
GetHeader(text);
string dataType = header.DATA.Split(' ')[1]; //储存的数据类型,ascii binary binary_compressed
int size = header.SIZE.Split(' ').Length - 1; //SIZE的长度,可以判断是否包含rgb信息
pointCount = Convert.ToInt32(header.POINTS.Split(' ')[1]); //点的数量
int index = text.IndexOf(header.DATA) + header.DATA.Length + 1; //数据开始的索引
point3Ds = new List<Point3D>();
Point3D point;
if (dataType == "binary")
{
//二进制文件,直接按字节数组读取即可
for (int i = index; i < bytes.Length;)
{
point = new Point3D();
point.x = BitConverter.ToSingle(bytes, i);
point.y = BitConverter.ToSingle(bytes, i + 4);
point.z = BitConverter.ToSingle(bytes, i + 8);
if (size == 4)
{
point.color = BitConverter.ToUInt32(bytes, i + 12);
}
point3Ds.Add(point);
if (point3Ds.Count == pointCount) break;
i += 4 * size;
}
}
else if(dataType == "binary_compressed")
{
//二进制压缩,先解析压缩前的数据量和压缩后数据量
int[] bys = new int[2];
int dataIndex = 0;
for (int i = 0; i < bys.Length; i++)
{
bys[i] = BitConverter.ToInt32(bytes, index + i * 4);
dataIndex = index + i * 4;
}
dataIndex += 4; //数据开始的索引
int compressedSize = bys[0]; //压缩之后的长度
int decompressedSize = bys[1]; //解压之后的长度
//将压缩后的数据单独拿出来
byte[] compress = new byte[compressedSize];
//将bs,从索引为a开始,复制到compress的[0至compressedSize]区间内
Array.Copy(bytes, dataIndex, compress, 0, compressedSize);
//LZF解压算法
byte[] data = Decompress(compress, decompressedSize);
int type = 0;
for (int i = 0; i < data.Length; i += 4)
{
//先读取x坐标
if (type == 0)
{
point = new Point3D();
point.x = BitConverter.ToSingle(data, i);
point3Ds.Add(point);
if (point3Ds.Count == pointCount) type++;
}
else if (type == 1) //y 坐标
{
point3Ds[i / 4 - pointCount].y = BitConverter.ToSingle(data, i);
if (i / 4 == pointCount * 2 - 1) type++;
}
else if (type == 2) //z 坐标
{
point3Ds[i / 4 - pointCount * 2].z = BitConverter.ToSingle(data, i);
if (i / 4 == pointCount * 3 - 1) type++;
}
else if (size == 4) //颜色信息
{
point3Ds[i / 4 - pointCount * 3].color = BitConverter.ToUInt32(data, i);
if (i / 4 == pointCount * 4 - 1) break;
}
}
}
}
/// <summary>
/// 使用LZF算法解压缩数据
/// </summary>
/// <param name="input">要解压的数据</param>
/// <param name="outputLength">解压之后的长度</param>
/// <returns>返回解压缩之后的内容</returns>
public static byte[] Decompress(byte[] input, int outputLength)
{
uint iidx = 0;
uint oidx = 0;
int inputLength = input.Length;
byte[] output = new byte[outputLength];
do
{
uint ctrl = input[iidx++];
if (ctrl < (1 << 5))
{
ctrl++;
if (oidx + ctrl > outputLength)
{
return null;
}
do
output[oidx++] = input[iidx++];
while ((--ctrl) != 0);
}
else
{
var len = ctrl >> 5;
var reference = (int)(oidx - ((ctrl & 0x1f) << 8) - 1);
if (len == 7)
len += input[iidx++];
reference -= input[iidx++];
if (oidx + len + 2 > outputLength)
{
return null;
}
if (reference < 0)
{
return null;
}
output[oidx++] = output[reference++];
output[oidx++] = output[reference++];
do
output[oidx++] = output[reference++];
while ((--len) != 0);
}
}
while (iidx < inputLength);
return output;
}
}
/// <summary>
/// Pcd 中的点
/// </summary>
class Point3D
{
public float x;
public float y;
public float z;
public uint color;
}
/// <summary>
/// Pcd 文件的头部信息
/// </summary>
class Header
{
public string FistLine = ""; //pcd 文件的第一行
public string VERSION;
public string FIELDS;
public string SIZE;
public string TYPE;
public string COUNT;
public string WIDTH;
public string HEIGHT;
public string VIEWPOINT;
public string POINTS;
public string DATA;
}
<file_sep># PcdReader
Read PCD file with C#. Include the binary file.
用C#读取PCD点云文件,包括二进制文件和压缩的二进制文件
| 35d634781ad9484c1291d20db183c48dd775aa82 | [
"Markdown",
"C#"
]
| 2 | C# | LimeRabbit/PcdReader | 3923b11cf79efc0a1e98b693ebdd92b4fb1ef4f6 | 5572e74eb2123dcbf8a057004d068bcc54c6740f |
refs/heads/master | <file_sep>package event;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.text.Text;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import calendar.CalendarController;
import models.*;
public class EventController {
@FXML private Node root;
@FXML private TextField tittelField;
@FXML private Text tittelFieldValid;
@FXML private TextField besField;
@FXML private Text besFieldValid;
@FXML private TextField roomTextField;
@FXML private Text romFieldValid;
@FXML private ComboBox<String> romField;
@FXML private DatePicker datoField;
@FXML private Text datoFieldValid;
@FXML private TextField fraField;
@FXML private Text fraFieldValid;
@FXML private TextField tilField;
@FXML private Text tilFieldValid;
@FXML private TextField alarmField;
@FXML private Text alarmFieldValid;
@FXML private CheckBox personCheck;
@FXML private CheckBox gruppeCheck;
@FXML private CheckBox reserveCheck;
@FXML private CheckBox alarmCheck;
@FXML private ListView<String> userList;
@FXML private ListView<String> inviteList;
@FXML private ComboBox<String> timeBox;
ArrayList<Group> grouplist = Database.getAllGroups();
ArrayList<String> StringGroups = null;
ArrayList<Room> currentRooms = new ArrayList<Room>();
@FXML private Button lagre;
private CalendarController con = new CalendarController();
private String valid="000000"; //Samtlige felt er ugyldige idet de instansieres.
void initialize() {}
void initData(CalendarController c) {
con=c;
fraField.setDisable(true);
tilField.setDisable(true);
roomTextField.setDisable(true);
romField.setDisable(true);
reserveCheck.setDisable(true);
alarmCheck.setSelected(false);
alarmField.setDisable(true);
ArrayList<User> items = Database.getAllUsers();
ObservableList<String> list = FXCollections.observableArrayList();
for(User u :items) {
if(!u.getUname().equals(Database.getCurrentUser().getUname())){
list.add(u.getUname());
}
}
userList.setItems(list);
}
@FXML
private void tittelFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue) {
String a = valid.substring(1);
if (isTittelValid(newValue)) {
tittelFieldValid.setVisible(false);
valid="1"+a;
} else {
tittelFieldValid.setVisible(true);
valid="0"+a;
}
isAllValid();
}
@FXML
private void besFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue) {
String a = valid.substring(0,1);
String b = valid.substring(2);
if (isBesValid(newValue)) {
besFieldValid.setVisible(false);
valid=a+"1"+b;
} else {
besFieldValid.setVisible(true);
valid=a+"0"+b;
}
isAllValid();
}
@FXML
private void romFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue) {
String a = valid.substring(0,2);
String b = valid.substring(3);
if (isRomValid(newValue)) {
romFieldValid.setVisible(false);
valid=a+"1"+b;
} else {
romFieldValid.setVisible(true);
valid=a+"0"+b;
}
isAllValid();
}
@FXML
private void datoFieldChange(ActionEvent dato) {
String a = valid.substring(0,3);
String b = valid.substring(4);
if (isDatoValid(datoField.getValue())) {
datoFieldValid.setVisible(false);
fraField.setDisable(false);
valid=a+"1"+b;
} else {
datoFieldValid.setVisible(true);
fraField.setDisable(true);
valid=a+"0"+b;
}
isAllValid();
updateAvailableRooms();
}
@FXML
private void fraFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue){
String a = valid.substring(0,4);
String b = valid.substring(5);
if (isFraValid(newValue)) {
fraFieldValid.setVisible(false);
tilField.setDisable(false);
valid=a+"1"+b;
tilField.setText("");
} else {
fraFieldValid.setVisible(true);
tilField.setDisable(true);
valid=a+"0"+b;
tilField.setText("");
}
isAllValid();
updateAvailableRooms();
}
@FXML
private void onAlarmCheck(ActionEvent action){
if(alarmCheck.isSelected()){
alarmField.setDisable(false);
timeBox.setDisable(false);
ObservableList<String> list = FXCollections.observableArrayList();
list.add("min");list.add("timer");list.add("dager");
timeBox.setItems(list);
timeBox.setValue("min");
}else{
alarmField.setText("");
alarmFieldValid.setVisible(false);
alarmField.setDisable(true);
timeBox.getSelectionModel().clearSelection();
ObservableList<String> empty = FXCollections.observableArrayList();
empty.add("");
timeBox.setItems(empty);
timeBox.setDisable(true);
}
isAllValid();
}
private void updateAvailableRooms() {
currentRooms.removeAll(currentRooms);
romField.getSelectionModel().clearSelection();
ObservableList<String> romListe = FXCollections.observableArrayList();
ArrayList<Room> rom = Database.getAvailableRooms(datoField.getValue(), fraField.getText(), tilField.getText());
for(Room room:rom) {
romListe.add(room.getName()+"- Kapasitet:"+room.getCapasity()+"");
currentRooms.add(room);
}
romField.setItems(romListe);
}
@FXML
private void onRoomFieldChange(ActionEvent action) {
if(romField.getValue()!=null){
String a = valid.substring(0,2);
String b = valid.substring(3);
valid=a+"1"+b;
}else{
String a = valid.substring(0,2);
String b = valid.substring(3);
valid=a+"0"+b;
}
isAllValid();
}
@FXML
private void tilFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue){
String b = valid.substring(0,5);
reserveCheck.setSelected(false);
if (isTilValid(newValue)) {
tilFieldValid.setVisible(false);
roomTextField.setDisable(false);
reserveCheck.setDisable(false);
romField.setDisable(true);
updateAvailableRooms();
valid=b+"1";
if(roomTextField.getText().equals("")){
String c = valid.substring(0,2);
String d = valid.substring(3);
valid=c+"0"+d;
}
} else {
roomTextField.setDisable(true);
reserveCheck.setDisable(true);
tilFieldValid.setVisible(true);
romField.getSelectionModel().clearSelection();
valid=b+"0";
}
isAllValid();
}
@FXML
private void onAlarmChange(ReadOnlyStringProperty property, String oldValue, String newValue){
if(isAlarmValid(newValue)){
alarmFieldValid.setVisible(false);
}else{
alarmFieldValid.setVisible(true);
}
isAllValid();
}
@FXML
private void avbrytButtonAction(ActionEvent action){
close();
}
@FXML
private void lagreButtonAction(ActionEvent action){
int i= Integer.parseInt(fraField.getText().substring(0, 2));
int j= Integer.parseInt(fraField.getText().substring(3));
int k= Integer.parseInt(tilField.getText().substring(0, 2));
int l= Integer.parseInt(tilField.getText().substring(3));
User current=Database.getCurrentUser();
ObservableList<String> invites = inviteList.getItems();
Event e = new Event(0,"","",LocalDate.now(),LocalTime.now(),LocalTime.now(),"",1,true,false);
if(reserveCheck.isSelected()){
int index = romField.getSelectionModel().getSelectedIndex();
e = Database.createEvent(tittelField.getText(), besField.getText(), datoField.getValue(), LocalTime.of(i, j), LocalTime.of(k, l), "", current,currentRooms.get(index));
}else{
e = Database.createEvent(tittelField.getText(), besField.getText(), datoField.getValue(), LocalTime.of(i, j), LocalTime.of(k, l), roomTextField.getText(), current,null);
}
ArrayList<Integer> indexflertall= new ArrayList<Integer>();
for(String name:invites){
for (j = 0; j <grouplist.size() ; j++) {
if(grouplist.get(j).GetName().equalsIgnoreCase(name)){
Database.registrateGInvitation(grouplist.get(j),e);
int index = invites.indexOf(name);
indexflertall.add(index);
}
}
}
int q=0;
if(!indexflertall.isEmpty()){
for (int index:indexflertall){
invites.remove(index-q,index+1-q);
q++;}}
for(String name:invites){
if(!name.equalsIgnoreCase(null)){
Database.registrateInvitation(name,e);
}
}
Database.registrateParticipation(current, e,true);
if(alarmCheck.isSelected()){
int alarm = Integer.parseInt(alarmField.getText());
System.out.println(alarm);
String time = timeBox.getValue();
if(time.equals("min")){
Database.setAlarmTime(current,e,alarm);
}else if(time.equals("timer")){
Database.setAlarmTime(current,e,alarm*60);
}else if(time.equals("dager")){
Database.setAlarmTime(current, e, alarm*1440);
}
}
con.update(Calendar.getToday(),Calendar.getDay());
close();
}
@FXML
private void addButtonAction(ActionEvent action){
if(personCheck.isSelected()){
String user = userList.getSelectionModel().getSelectedItem();
ObservableList<String> users= userList.getItems();
users.remove(user);
userList.setItems(users);
ObservableList<String> items= inviteList.getItems();
items.add(user);
inviteList.setItems(items);}
else if(gruppeCheck.isSelected()){
String group = userList.getSelectionModel().getSelectedItem();
ObservableList<String> groups = userList.getItems();
groups.remove(group);
userList.setItems(groups);
ObservableList<String> items= inviteList.getItems();
items.add(group);
inviteList.setItems(items);
}
}
@FXML
private void removeButtonAction(ActionEvent action){
String user = inviteList.getSelectionModel().getSelectedItem();
ObservableList<String> users= inviteList.getItems();
users.remove(user);
inviteList.setItems(users);
ObservableList<String> items= userList.getItems();
items.add(user);
userList.setItems(items);
}
@FXML
private void personCheckAction(ActionEvent action){
gruppeCheck.setSelected(false);
ArrayList<User> items = Database.getAllUsers();
ObservableList<String> list = FXCollections.observableArrayList();
for(User u :items) {
if(!u.getUname().equals(Database.getCurrentUser().getUname())){
list.add(u.getUname());
for(String s:inviteList.getItems()){
if(s.equalsIgnoreCase(u.getUname())){
list.remove(u.getUname());}}
}
}
userList.setItems(list);}
@FXML
private void gruppeCheckAction(ActionEvent action){
personCheck.setSelected(false);
ArrayList<Group> groups = Database.getAllGroups();
ObservableList<String> list2 = FXCollections.observableArrayList();
for(Group g :groups) {
list2.add(g.GetName());
for(String s:inviteList.getItems()){
if(s.equalsIgnoreCase(g.GetName())){
list2.remove(g.GetName());}
}userList.setItems(list2);}
}
@FXML
private void onReserveAction(ActionEvent action){
String a = valid.substring(0,2);
String b = valid.substring(3);
valid=a+"0"+b;
if(reserveCheck.isSelected()){
romField.setDisable(false);
roomTextField.setText("");
roomTextField.setDisable(true);
}else{
romField.getSelectionModel().clearSelection();
romField.setDisable(true);
roomTextField.setDisable(false);
}
isAllValid();
}
private void isAllValid(){
if(valid.contains("0")){
lagre.setDisable(true);
}else{
if(!alarmCheck.isSelected()){
lagre.setDisable(false);
}else if(!isAlarmValid(alarmField.getText())){
lagre.setDisable(true);
}else{
lagre.setDisable(false);
}
}
}
private boolean isTittelValid(String newValue) {
if(newValue.length()<=30){
return true;
}else{
return false;
}
}
private boolean isBesValid(String newValue) {
if(newValue.length()>255){
return false;
}
return true;
}
private boolean isRomValid(String value) {
if(value.length()<31 && !value.equals("")){
return true;
}
return false;
}
private boolean isDatoValid(LocalDate dato){
LocalDate d = LocalDate.now();
if (dato.isBefore(d)){
return false;
}
return true;
}
private boolean isFraValid(String newValue){
if(isValidTime(newValue)){
int hour=Integer.parseInt(newValue.substring(0,2));
int minute =Integer.parseInt(newValue.substring(3));
LocalTime time = LocalTime.of(hour,minute);
LocalDate d = datoField.getValue();
if(hour>=8){
if(d.equals(LocalDate.now())&& !time.isAfter(LocalTime.now())){
return false;
}
return true;
}
}
return false;
}
private boolean isTilValid(String newValue){
if(!isValidTime(newValue)){
return false;
}
int i= Integer.parseInt(fraField.getText().substring(0, 2));
int j= Integer.parseInt(fraField.getText().substring(3));
int a= Integer.parseInt(newValue.substring(0, 2));
int b= Integer.parseInt(newValue.substring(3));
if(a>21 || (a==21 && b>0)){
return false;
}
if(a<i || (a==i && b<(j+30))){
return false;
}
return true;
}
private boolean isAlarmValid(String value){
if(isNum(value) && !value.equals("")){
int min =Integer.parseInt(value);
if(min<1){
return false;
}
return true;
}
return false;
}
private boolean isValidTime(String text){
if (text.length()!=5){
return false;
}
char c = text.charAt(2);
if (c!=':'){
return false;
}
if(!isNum(text.substring(0, 2))|| !isNum(text.substring(3))){
return false;
}
int a= Integer.parseInt(text.substring(0, 2));
int b= Integer.parseInt(text.substring(3));
if(a>23 || b>59){
return false;
}
return true;
}
public static boolean isNum(String str){
return str.matches("\\d+");
}
public void close() {
root.getScene().getWindow().hide();
}
}<file_sep>package utils;
import javafx.application.Platform;
import calendar.CalendarController;
public class AlarmThread implements Runnable {
private Thread t = null;
private volatile boolean isPaused = true;
private volatile boolean isRunning = true;
public AlarmThread() {
t = new Thread(this);
t.start();
}
public void run() {
while(isRunning) {
if(!isPaused) {
Platform.runLater(new Runnable() {
public void run() {
CalendarController.updateAlarm();
}
});
}
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void pause() {
isPaused = true;
}
public void start() {
isPaused = false;
}
public void stop() {
isRunning = false;
}
}<file_sep>package models;
import java.io.IOException;
import java.util.ArrayList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import calendar.CalendarController;
import event.InfoViewController;
public class Group {
private int id;
private String gName;
private String description;
public Group(int id, String groupName, String description) {
this.id = id;
this.gName = groupName;
this.description = description;
}
public int getId() {
return id;
}
public String GetName() {
return gName;
}
public String getDescription() {
return description;
}
public ArrayList<User> getMembers() {
return Database.getUsersFromGroup(this);
}
public ArrayList<Event> getEvents() {
return Database.getEventsFromGroup(this);
}
public void showView() throws IOException{
FXMLLoader loader = new FXMLLoader(getClass().getResource("/event/InfoView.fxml"));
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(new Scene((Pane) loader.load()));
InfoViewController controller = loader.<InfoViewController>getController();
controller.initData(this);
stage.show();
}
}
<file_sep>package event;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import models.Database;
import models.Event;
import models.Group;
import models.User;
import calendar.CalendarController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
public class InviteController {
@FXML private Node root;
@FXML private CheckBox personCheck;
@FXML private CheckBox groupCheck;
@FXML private ListView<String> userList;
@FXML private ListView<String> inviteList;
@FXML private Button invite;
private Event event = new Event(0,"","",LocalDate.now(),LocalTime.now(),LocalTime.now(),"",1,true,false);
private EditController con = new EditController();
private ArrayList<String> users =new ArrayList<String>();
private ArrayList<String> groups =new ArrayList<String>();
void initialize() {}
void initData(EditController c, Event e, ArrayList<String> newUsers, ArrayList<Group> newGroups) {
con =c;
event = e;
invite.setDisable(true);
ArrayList<User> allUsers = Database.getAllUsers();
ArrayList<User> eventInvites =Database.getInviteesFromEvent(event);
for(User u:allUsers){
int k =1;
for (User i :eventInvites){
if(i.getUname().equals(u.getUname())){
k=0;
}
}
for(String j: newUsers){
if(j.equals(u.getUname())){
k=0;
}
}
if(k==1){
users.add(u.getUname());
}
}
ObservableList<String> list = FXCollections.observableArrayList(users);
userList.setItems(list);
ArrayList<Group> allGroups = Database.getAllGroups();
ArrayList<Group> eventGroups = Database.getGroupsFromEvent(event);
for(Group g:allGroups){
int k =1;
for (Group j :eventGroups){
if(j.GetName().equals(g.GetName())){
k=0;
}
}
for (Group i:newGroups){
if(i.GetName().equals(g.GetName())){
k=0;
}
}
if(k==1){
groups.add(g.GetName());
}
}
personCheck.setSelected(true);
}
private void canInvite(){
if (inviteList.getItems().size()>0){
invite.setDisable(false);;
}else{
invite.setDisable(true);
}
}
@FXML
private void addButtonAction(ActionEvent action){
if(personCheck.isSelected() && userList.getSelectionModel().getSelectedItem()!=null){
String invite = userList.getSelectionModel().getSelectedItem();
users.remove(invite);
userList.setItems(FXCollections.observableArrayList(users));
ObservableList<String> items= inviteList.getItems();
items.add(invite);
inviteList.setItems(items);
}else if(groupCheck.isSelected() && userList.getSelectionModel().getSelectedItem()!=null){
String invite = userList.getSelectionModel().getSelectedItem();
groups.remove(invite);
userList.setItems(FXCollections.observableArrayList(groups));
ObservableList<String> items= inviteList.getItems();
items.add(invite);
inviteList.setItems(items);
}
canInvite();
}
@FXML
private void personCheckAction(ActionEvent action){
groupCheck.setSelected(false);
ObservableList<String> list = FXCollections.observableArrayList(users);
userList.setItems(list);}
@FXML
private void groupCheckAction(ActionEvent action){
personCheck.setSelected(false);
ObservableList<String> list = FXCollections.observableArrayList(groups);
userList.setItems(list);
}
@FXML
private void removeButtonAction(ActionEvent action){
if(inviteList.getSelectionModel().getSelectedItem()!=null){
String user = inviteList.getSelectionModel().getSelectedItem();
ObservableList<String> invites= inviteList.getItems();
invites.remove(user);
inviteList.setItems(invites);
if(isGroup(user)){
groups.add(user);
groupCheck.setSelected(true);
personCheck.setSelected(false);
ObservableList<String> list = FXCollections.observableArrayList(groups);
userList.setItems(list);
}else{
users.add(user);
personCheck.setSelected(true);
groupCheck.setSelected(false);
ObservableList<String> list = FXCollections.observableArrayList(users);
userList.setItems(list);
}
canInvite();
}
}
@FXML
private void inviteAction(ActionEvent action){
ArrayList<Group> gList = new ArrayList<Group>();
ArrayList<String> uList = new ArrayList<String>();
for (String uname:inviteList.getItems()){
if(isGroup(uname)){
for(Group g: Database.getAllGroups()){
if(g.GetName().equals(uname)){
gList.add(g);
for(User u: g.getMembers()){
if(uList.indexOf(u.getUname())==-1){
uList.add(u.getUname());
}
}
}
}
}else{
if(uList.indexOf(uname)==-1){
uList.add(uname);
}
}
}
con.update(uList,gList);
close();
}
@FXML
private void avbrytAction(ActionEvent action){
close();
}
private boolean isGroup(String name){
ArrayList<Group> allGroups = Database.getAllGroups();
for(Group g:allGroups){
if(g.GetName().equals(name)){
return true;
}
}
return false;
}
public void close() {
root.getScene().getWindow().hide();
}
}
<file_sep>package calendar;
import java.io.IOException;
import java.util.ArrayList;
import models.Calendar;
import models.Database;
import event.EventViewController;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
public class LoginController {
@FXML private Node root;
@FXML private TextField brukerField;
@FXML private PasswordField passordField;
@FXML private Text loginFieldValid;
@FXML private Button logInnButton;
@FXML
private void buttonFieldChange(ActionEvent action) throws IOException{
logIn();
}
private void logIn() throws IOException{
Database.connect();
if (Database.loginUser(brukerField.getText(), passordField.getText())) {
loginFieldValid.setVisible(false);
//lukk og åpne:
FXMLLoader loader = new FXMLLoader(getClass().getResource("CalendarPane.fxml"));
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(new Scene((Pane) loader.load()));
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we) {
CalendarController.alarmThread.stop();
}
});
CalendarController controller = loader.<CalendarController>getController();
controller.initData(Calendar.getWeekNumber(),Calendar.getMonth(),Calendar.getYear(),Calendar.getDay(),Calendar.getToday());
close();
stage.show();
} else {
loginFieldValid.setVisible(true);
loginFieldValid.setText("Feil brukernavn/passord.");
Database.close();
}
}
@FXML
private void brukerFieldChange() throws IOException {
if(brukerField.getLength() > 10) {
logInnButton.setDisable(true);
loginFieldValid.setVisible(true);
loginFieldValid.setText("<NAME>");
}
else {
logInnButton.setDisable(false);
loginFieldValid.setVisible(false);
loginFieldValid.setText("");
}
}
@FXML
private void enterAction(KeyEvent event) throws IOException{
if(event.getCode()==KeyCode.ENTER){
logIn();
}
}
public void close() {
root.getScene().getWindow().hide();
}
}
<file_sep>package calendar;
import event.InviteController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import models.Calendar;
import models.Database;
import models.Group;
import models.User;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
//import com.mysql.fabric.xmlrpc.base.Array;
/**
* Created by ingridng on 12.03.15.
*/
public class ConfController {
private CalendarController con = new CalendarController();
@FXML private Button RedigerBrukereButton, LagreButton;
@FXML private TextField emailField;
@FXML private Node root;
@FXML private Text confNavn,confBruk, confMail,confGrupper,confBilde;
@FXML private Text redigerEpost,sysadmtext,ikkegyldigmail;
@FXML private ImageView yiha;
boolean v =false;
private Boolean sysadm = false;
void initialize() {}
void initData(CalendarController c) {
con = c;
update();
}
@FXML private void epostDragOver(MouseEvent action){
}
@FXML private void closeButtonAction(ActionEvent action){
con.update(Calendar.getToday(),Calendar.getDay());
close();
}
@FXML private void lagreButtonAction(ActionEvent action){
con.update(Calendar.getToday(),Calendar.getDay());
if(!ikkegyldigmail.isVisible()&&!emailField.getText().isEmpty())
{Database.changeEmail(emailField.getText(),Database.getCurrentUser().getUname());
close();}
else{close();}
}
@FXML private void RedigerBrukereButtonAction(ActionEvent action) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ConfUsers.fxml"));
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(new Scene((Pane)loader.load()));
ConfUsersController controller = loader.<ConfUsersController>getController();
controller.initData();
stage.show();
}
@FXML private void paneAction(MouseEvent action){
if(!ikkegyldigmail.isVisible()&&v){v=false;confMail.setText(emailField.getText());emailField.setVisible(false);emailField.setDisable(true);}
else{}
}
@FXML private void confEmailAction(MouseEvent action){
emailField.setDisable(false);
emailField.setVisible(true);
emailField.setText(confMail.getText());
}
private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public boolean isEmailValid(String email){
if(email.length()<6){
return false;
}
return email.matches(EMAIL_REGEX);
}
@FXML private void emailFieldAction(javafx.scene.input.KeyEvent action) throws IOException{
v=true;
String s = emailField.getText() + action.getCharacter();
if(!isEmailValid(s)){ikkegyldigmail.setVisible(true);LagreButton.setDisable(true);}
else{ikkegyldigmail.setVisible(false);LagreButton.setDisable(false);}
}
@FXML private void confBildeAction(MouseEvent action){
String supportedFileFormats[] = {"png", "jpg", "jpeg", "gif", "PNG", "JPG", "JPEG", "GIF"};
FileChooser fileChooser = new FileChooser();
Stage stage = new Stage(StageStyle.DECORATED);
File file = fileChooser.showOpenDialog(stage);
String extension = "";
if(file!=null){
String path = file.getAbsoluteFile().toString();
int i = path.lastIndexOf('.');
if (i > 0) {
extension = path.substring(i+1);
}
if(Arrays.asList(supportedFileFormats).contains(extension)) {
Database.setProfilePicture(Database.getCurrentUser(), file);
Database.updateCurrentProfilePicture();
yiha.setImage(Database.getCurrentProfilePicture());
}else{
System.out.println("File not an image!");
}
}
}
@FXML private void confPassordAction(MouseEvent action) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ConfPassord.fxml"));
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(new Scene((Pane)loader.load()));
PassordController passordcontroller = loader.<PassordController>getController();
passordcontroller.initData(con);
stage.show();
}
@FXML private void confGrupperAction(MouseEvent action){
System.out.println("du vil endre grupper");
}
public void update(){
confNavn.setText(Database.getCurrentUser().getFullname()+" ");
confBruk.setText(Database.getCurrentUser().getUname());
confMail.setText(Database.getCurrentUser().getEmail());
yiha.setImage(Database.getCurrentProfilePicture());
String grupper = "";
for(Group g: Database.getCurrentUser().getGroups()){
if(g.GetName().equalsIgnoreCase("Sysadmins")){sysadm = true;}
grupper = grupper + g.GetName().toString();
if(Database.getCurrentUser().getGroups().indexOf(g)+1!=Database.getCurrentUser().getGroups().size()){grupper = grupper + " , " ;}
}
if(!grupper.isEmpty()){grupper=grupper.substring(0,grupper.length()-3);}
confGrupper.setText(grupper+"");
if(sysadm){sysadmtext.setVisible(true);RedigerBrukereButton.setDisable(false);RedigerBrukereButton.setVisible(true);}
else{}
}
public void close() {
root.getScene().getWindow().hide();
}
}
<file_sep>package event;
import models.Database;
import models.Group;
import models.User;
import calendar.CalendarController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.ListView;
import javafx.scene.text.Text;
public class InfoViewController {
@FXML private Node root;
@FXML private Text infoField;
@FXML private ListView<String> medlemList;
@FXML private ListView<String> subList;
private Group group = new Group(0, null, null);
void initialize() {}
public void initData(Group g) {
this.group = g;
// Gruppe beskrivelse
infoField.setText(group.getDescription());
// Gruppe medlemmer
ObservableList<String> fullname= FXCollections.observableArrayList();
for(User bruker:group.getMembers()) {
fullname.add(bruker.getFullname());
}
medlemList.setItems(fullname);
// Sub grupper
ObservableList<String> subGroup= FXCollections.observableArrayList();
for(Group subgruppe: Database.getAllSubGroups(group)) {
subGroup.add(subgruppe.GetName());
}
subList.setItems(subGroup);
}
public void close() {
root.getScene().getWindow().hide();
}
}
<file_sep>package event;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import calendar.CalendarController;
import models.Calendar;
import models.Database;
import models.Event;
import models.Group;
import models.Room;
import models.User;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class EditController {
@FXML private Node root;
@FXML private TextField tittelField;
@FXML private Text tittelFieldValid;
@FXML private TextField besField;
@FXML private Text besFieldValid;
@FXML private TextField roomTextField;
@FXML private Text romFieldValid;
@FXML private ComboBox<String> romField;
@FXML private CheckBox reserveCheck;
@FXML private DatePicker datoField;
@FXML private Text datoFieldValid;
@FXML private TextField fraField;
@FXML private Text fraFieldValid;
@FXML private TextField tilField;
@FXML private Text tilFieldValid;
@FXML private ListView<String> deltarList;
@FXML private ListView<String> inviteList;
@FXML private Button lagre;
@FXML private Button addInvites;
private String valid="000000";
private String original="";
private ArrayList<String> participants= new ArrayList<String>();
private ArrayList<String> invites = new ArrayList<String>();
private ArrayList<String> newInvites = new ArrayList<String>();
private ArrayList<Group> newGroups = new ArrayList<Group>();
private ArrayList<User> deleted = new ArrayList<User>();
private CalendarController con = new CalendarController();
private Event event = new Event(0,"","",LocalDate.now(),LocalTime.now(),LocalTime.now(),"",1,true,false);
private LocalDate originalDate = LocalDate.now();
private LocalTime originalStart = LocalTime.now();
private LocalTime originalEnd = LocalTime.now();
private Room originalRoom = new Room(0,"Navn",0);
ArrayList<Room> currentRooms = new ArrayList<Room>();
void initialize() {}
public void initData(Event e, CalendarController c) {
con=c;
event = e;
String fra = e.getStartHour().toString().substring(0, 5);
String til =e.getEndHour().toString().substring(0, 5);
originalDate =e.getEvdate();
originalStart =LocalTime.of(Integer.parseInt(fra.substring(0,2)),Integer.parseInt(fra.substring(3)));
originalEnd = LocalTime.of(Integer.parseInt(til.substring(0,2)),Integer.parseInt(til.substring(3)));
originalRoom = e.getRoom();
besField.setText(e.getDescr());
tittelField.setText(e.getTitle());
datoField.setValue(e.getEvdate());
fraField.setText(fra);
tilField.setText(til);
if(e.getRoomName().equals("")){
roomTextField.setText("");
reserveCheck.setSelected(true);
romField.setDisable(false);
updateAvailableRooms();
romField.setValue(e.getRoom().getName()+"- Kapasitet:"+e.getRoom().getCapasity()+"");
}else{
roomTextField.setText(e.getRoomName());
}
ArrayList<User> deltakerliste = event.getParticipants();
for (User bruker : deltakerliste ) {
participants.add(bruker.getUname());
}
ObservableList<String> items = FXCollections.observableArrayList(participants);
deltarList.setItems(items);
ArrayList<User> userList = event.getNonParticipantsFromEvent();
for (User bruker: userList){
invites.add(bruker.getUname());
}
ObservableList<String> list = FXCollections.observableArrayList(invites);
inviteList.setItems(list);
String day= ""+e.getEvdate().getDayOfMonth();
String month=""+e.getEvdate().getMonthValue();
String year = Integer.toString(e.getEvdate().getYear());
original=e.getTitle()+e.getDescr()+e.getRoomName()+day+month+year+fra+til;
if(e.getRoom()!=null){
original+=e.getRoom().getName()+"- Kapasitet:"+e.getRoom().getCapasity()+"";
}
original=e.getTitle()+e.getDescr()+e.getRoomName()+day+month+year+fra+til;
lagre.setDisable(true);
}
public void update(ArrayList<String> list, ArrayList<Group> Groups){
newInvites=list;
newGroups = Groups;
ObservableList<String> users= inviteList.getItems();
for (String i:newInvites){
users.add(i);
}
inviteList.setItems(users);
isAllValid();
}
@FXML
private void tittelFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue) {
String a = valid.substring(1);
if (isTittelValid(newValue)) {
tittelFieldValid.setVisible(false);
valid="1"+a;
} else {
tittelFieldValid.setVisible(true);
valid="0"+a;
}
isAllValid();
}
@FXML
private void besFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue) {
String a = valid.substring(0,1);
String b = valid.substring(2);
if (isBesValid(newValue)) {
besFieldValid.setVisible(false);
valid=a+"1"+b;
} else {
besFieldValid.setVisible(true);
valid=a+"0"+b;
}
isAllValid();
}
@FXML
private void roomTextFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue) {
String a = valid.substring(0,2);
String b = valid.substring(3);
if (isRomValid(newValue)) {
romFieldValid.setVisible(false);
valid=a+"1"+b;
} else {
romFieldValid.setVisible(true);
valid=a+"0"+b;
}
isAllValid();
}
@FXML
private void datoFieldChange(ActionEvent dato) {
String a = valid.substring(0,3);
String b = valid.substring(4);
if (isDatoValid(datoField.getValue())) {
datoFieldValid.setVisible(false);
fraField.setDisable(false);
valid=a+"1"+b;
} else {
datoFieldValid.setVisible(true);
fraField.setDisable(true);
valid=a+"0"+b;
}
isAllValid();
if(isFraValid(fraField.getText())&& isTilValid(tilField.getText())){
updateAvailableRooms();
}
}
@FXML
private void fraFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue){
String a = valid.substring(0,4);
String b = valid.substring(5);
if (isFraValid(newValue)) {
fraFieldValid.setVisible(false);
tilField.setDisable(false);
valid=a+"1"+b;
tilField.setText("");
} else {
fraFieldValid.setVisible(true);
tilField.setDisable(true);
valid=a+"0"+b;
tilField.setText("");
}
isAllValid();
if(isDatoValid(datoField.getValue()) && isTilValid(tilField.getText())){
updateAvailableRooms();
}
}
@FXML
private void tilFieldChange(ReadOnlyStringProperty property, String oldValue, String newValue){
String b = valid.substring(0,5);
reserveCheck.setSelected(false);
if (isTilValid(newValue)) {
tilFieldValid.setVisible(false);
roomTextField.setDisable(false);
reserveCheck.setDisable(false);
romField.setDisable(true);
valid=b+"1";
if(roomTextField.getText().equals("")){
String c = valid.substring(0,2);
String d = valid.substring(3);
valid=c+"0"+d;
}
} else {
roomTextField.setDisable(true);
reserveCheck.setDisable(true);
tilFieldValid.setVisible(true);
romField.getSelectionModel().clearSelection();
valid=b+"0";
}
isAllValid();
if(isDatoValid(datoField.getValue()) && isTilValid(fraField.getText())){
updateAvailableRooms();
}
}
@FXML
private void updateAvailableRooms() {
currentRooms.removeAll(currentRooms);
romField.getSelectionModel().clearSelection();
ObservableList<String> romListe = FXCollections.observableArrayList();
ArrayList<Room> rom = Database.getAvailableRooms(datoField.getValue(), fraField.getText(), tilField.getText());
for(Room room:rom) {
romListe.add(room.getName()+"- Kapasitet:"+room.getCapasity()+"");
currentRooms.add(room);
}
int i= Integer.parseInt(fraField.getText().substring(0, 2));
int j= Integer.parseInt(fraField.getText().substring(3));
int k= Integer.parseInt(tilField.getText().substring(0, 2));
int l= Integer.parseInt(tilField.getText().substring(3));
LocalTime start =LocalTime.of(i, j);
LocalTime end = LocalTime.of(k, l);
//check if originalRoom is in list after change
if(datoField.getValue().equals(originalDate) && originalDate!=null && testDate(start,end) ){
if(originalStart.toString().equals(start.toString()) && originalEnd.toString().equals(end.toString())){
romListe.add(originalRoom.getName()+"- Kapasitet:"+originalRoom.getCapasity()+"");
currentRooms.add(originalRoom);
}else if(start.isBefore(originalStart)){
if(end.isBefore(originalEnd) || end.toString().equals(originalEnd.toString())){
ArrayList<Room> notBooked =Database.getAvailableRooms(originalDate, start.toString(), originalStart.toString());
for(Room r:notBooked){
if(r.getId()==originalRoom.getId()){
romListe.add(originalRoom.getName()+"- Kapasitet:"+originalRoom.getCapasity()+"");
currentRooms.add(originalRoom);
break;
}
}
}else{
ArrayList<Room> notBooked1 =Database.getAvailableRooms(originalDate, start.toString(), originalStart.toString());
ArrayList<Room> notBooked2 =Database.getAvailableRooms(originalDate, originalEnd.toString(), end.toString());
int a = 0;
int b = 0;
for(Room r:notBooked1){
if(r.getId()==originalRoom.getId()){
a=1;
break;
}
}
for(Room r:notBooked2){
if(r.getId()==originalRoom.getId()){
b=1;
break;
}
}
if(a==1 && b==1){
romListe.add(originalRoom.getName()+"- Kapasitet:"+originalRoom.getCapasity()+"");
currentRooms.add(originalRoom);
}
}
}else if(end.isAfter(originalEnd)){
if(start.isAfter(originalStart) || start.toString().equals(originalStart.toString())){
System.out.println("etter");
ArrayList<Room> notBooked =Database.getAvailableRooms(originalDate, originalEnd.toString(), end.toString());
for(Room r:notBooked){
if(r.getId()==originalRoom.getId()){
romListe.add(originalRoom.getName()+"- Kapasitet:"+originalRoom.getCapasity()+"");
currentRooms.add(originalRoom);
break;
}
}
}
}
}
romField.setItems(romListe);
}
private boolean testDate(LocalTime start, LocalTime end){
if((end.isBefore(originalStart)&&start.isBefore(originalStart))||(end.isAfter(originalEnd)&&start.isAfter(originalEnd))){
return false;
}
return true;
}
@FXML
private void onRoomFieldChange(ActionEvent action) {
if(romField.getValue()!=null){
String a = valid.substring(0,2);
String b = valid.substring(3);
valid=a+"1"+b;
}else{
String a = valid.substring(0,2);
String b = valid.substring(3);
valid=a+"0"+b;
}
isAllValid();
}
@FXML
private void avbrytButtonAction(ActionEvent action){
close();
}
@FXML
private void addButton(ActionEvent action){
String user = inviteList.getSelectionModel().getSelectedItem();
if (user!=null){
ObservableList<String> users= inviteList.getItems();
users.remove(user);
inviteList.setItems(users);
ObservableList<String> items= deltarList.getItems();
items.add(user);
deltarList.setItems(items);
isAllValid();
}
}
@FXML
private void removeButton(ActionEvent action){
String user = deltarList.getSelectionModel().getSelectedItem();
if (user!=null && !Database.getCurrentUser().getUname().equals(user)){
ObservableList<String> users= deltarList.getItems();
users.remove(user);
deltarList.setItems(users);
ObservableList<String> items= inviteList.getItems();
items.add(user);
inviteList.setItems(items);
isAllValid();
}
}
@FXML
private void deleteButtonAction(ActionEvent action){
String user = inviteList.getSelectionModel().getSelectedItem();
if (user!=null){
if(newInvites.indexOf(user)!=-1){
newInvites.remove(user);
}else{
ObservableList<String> users= inviteList.getItems();
users.remove(user);
inviteList.setItems(users);
deleted.add(Database.getUserFromUsername(user));
}
isAllValid();
}
}
@FXML
private void inviteMoreAction(ActionEvent action) throws IOException{
FXMLLoader loader = new FXMLLoader(getClass().getResource("InviteView.fxml"));
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(new Scene((Pane) loader.load()));
InviteController controller = loader.<InviteController>getController();
controller.initData(this,event,newInvites,newGroups);
stage.show();
}
@FXML
private void onReserveAction(ActionEvent action){
String a = valid.substring(0,2);
String b = valid.substring(3);
valid=a+"0"+b;
if(reserveCheck.isSelected()){
romField.setDisable(false);
roomTextField.setText("");
roomTextField.setDisable(true);
}else{
romField.getSelectionModel().clearSelection();
romField.setDisable(true);
roomTextField.setDisable(false);
}
isAllValid();
}
@FXML
private void lagreButtonAction(ActionEvent action) throws IOException{
if(hasTextChanged()){
int i= Integer.parseInt(fraField.getText().substring(0, 2));
int j= Integer.parseInt(fraField.getText().substring(3));
int k= Integer.parseInt(tilField.getText().substring(0, 2));
int l= Integer.parseInt(tilField.getText().substring(3));
User current = Database.getCurrentUser();
if(reserveCheck.isSelected()){
int index = romField.getSelectionModel().getSelectedIndex();
Database.changeEvent(tittelField.getText(), besField.getText(), datoField.getValue(), LocalTime.of(i, j), LocalTime.of(k, l), "", current, event,currentRooms.get(index));
}else{
Database.changeEvent(tittelField.getText(), besField.getText(), datoField.getValue(), LocalTime.of(i, j), LocalTime.of(k, l), roomTextField.getText(), current, event,null);
}
}
if(isListChanged()){
for(String uname:inviteList.getItems()){
Database.registrateInvitation(Database.getUserFromUsername(uname),event);
}
for(String uname:deltarList.getItems()){
Database.registrateInvitation(Database.getUserFromUsername(uname),event);
Database.registrateParticipation(Database.getUserFromUsername(uname),event, true);
}
if(deleted.size()>0){
for (User user:deleted){
Database.deleteUserInvitation(user, event);
}
}
if(newGroups.size()>0){
for(Group g:newGroups){
Database.registrateGInvitation(g, event);
}
}
}
con.update(Calendar.getToday(),Calendar.getDay());
close();
}
private void isAllValid(){
if(isListChanged() && !hasTextChanged()){
lagre.setDisable(false);
}else if(isListChanged() && hasTextChanged()){
if(!valid.contains("0")){
lagre.setDisable(false);
}else{
lagre.setDisable(true);
}
}else if(!isListChanged() && hasTextChanged()){
if(!valid.contains("0")){
lagre.setDisable(false);
}else{
lagre.setDisable(true);
}
}else{
lagre.setDisable(true);
}
}
private boolean isListChanged(){
String i="";
if(deltarList.getItems().size()==participants.size()){
for(String uname:deltarList.getItems()){
String b="";
for (String d:participants){
if(uname.equals(d)){
b="1";
}
}
i+=b;
}
}
String j ="";
if(inviteList.getItems().size()==invites.size()){
for(String user:invites){
String a = "0";
for (String in:inviteList.getItems()){
if(in.equals(user)){
a="1";
}
}
j+=a;
}
}
if(i!="" && j!="" && !i.contains("0") && !j.contains("0")){
return false;
}else{
return true;
}
}
private boolean hasTextChanged(){
if(datoField.getValue()!=null){
String day =Integer.toString(datoField.getValue().getDayOfMonth());
String month = Integer.toString(datoField.getValue().getMonthValue());
String year = Integer.toString(datoField.getValue().getYear());
String test=tittelField.getText()+besField.getText()+roomTextField.getText()+day+month+year+fraField.getText()+tilField.getText()+romField.getValue();
if(!test.matches(original)){
return true;
}
}
return false;
}
private boolean isTittelValid(String newValue) {
if(newValue.length()<=30){
return true;
}else{
return false;
}
}
private boolean isBesValid(String newValue) {
if(newValue.length()>255){
return false;
}
return true;
}
private boolean isRomValid(String newValue) {
if(newValue.length()<31 && !newValue.equals("")){
return true;
}
return false;
}
private boolean isDatoValid(LocalDate dato){
LocalDate d = LocalDate.now();
if (dato.isBefore(d)){
return false;
}
return true;
}
private boolean isFraValid(String newValue){
if(isValidTime(newValue)){
int hour=Integer.parseInt(newValue.substring(0,2));
int minute =Integer.parseInt(newValue.substring(3));
if (datoField.getValue()!=null){
LocalTime time = LocalTime.of(hour,minute);
LocalDate d = datoField.getValue();
if(hour>=8){
if(d.equals(LocalDate.now())&& !time.isAfter(LocalTime.now())){
return false;
}
return true;
}
}
}
return false;
}
private boolean isTilValid(String newValue){
if(!isValidTime(newValue)){
return false;
}
int i= Integer.parseInt(fraField.getText().substring(0, 2));
int j= Integer.parseInt(fraField.getText().substring(3));
int a= Integer.parseInt(newValue.substring(0, 2));
int b= Integer.parseInt(newValue.substring(3));
if(a>21 || (a==21 && b>0)){
return false;
}
if(a<i || (a==i && b<(j+30))){
return false;
}
return true;
}
private boolean isValidTime(String text){
if (text.length()!=5){
return false;
}
char c = text.charAt(2);
if (c!=':'){
return false;
}
if(!isNum(text.substring(0, 2))|| !isNum(text.substring(3))){
return false;
}
int a= Integer.parseInt(text.substring(0, 2));
int b= Integer.parseInt(text.substring(3));
if(a>23 || b>59){
return false;
}
return true;
}
public static boolean isNum(String str){
return str.matches("\\d+");
}
public void close() {
root.getScene().getWindow().hide();
}
}
<file_sep>package event;
import java.io.IOException;
import calendar.CalendarController;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class EventForm extends Application {
private static Stage eventStage;
@Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(EventForm.class.getResource("EventPane.fxml"));
primaryStage.setScene(new Scene(root));
primaryStage.show();
eventStage = primaryStage;
}
public static void main(String[] args) {
launch(args);
}
public static Stage getEventStage(){return eventStage;}
public void newEventView(CalendarController c)throws IOException{
FXMLLoader loader = new FXMLLoader(getClass().getResource("EventPane.fxml"));
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(new Scene((Pane) loader.load()));
EventController controller = loader.<EventController>getController();
controller.initData(c);
stage.show();
}
}<file_sep>package models;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.Calendar;
import javafx.scene.image.Image;
public final class Database {
//------------------------------
// Variables
//------------------------------
private static User currentUser = null;
private static Image currentImg = null;
private static Connection connection = null;
private static String connectionURL = "jdbc:mysql://mysql.stud.ntnu.no/haakojj_TDT4140_db";
@SuppressWarnings("unused")
private static Statement stat = null;
private static String username = "haakojj_TDT4140";
private static String pw = "12345678";
//------------------------------
// Private constructor
//------------------------------
private Database() {
// Database is static
}
//------------------------------
// Private Query methods
//------------------------------
private static void updateQuery(String query) {
try {
Statement s = connection.createStatement();
s.executeUpdate(query);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private static ArrayList<HashMap<String, String>> readQuery(String query) {
ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
try {
Statement s = connection.createStatement();
ResultSet rs = s.executeQuery(query);
while(rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
HashMap<String, String> row = new HashMap<String, String>();
for(int i = 1; i <= rsmd.getColumnCount(); i++) {
row.put(rsmd.getColumnLabel(i), rs.getString(i));
}
result.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//------------------------------
// Private object generators
//------------------------------
private static User generateUser(HashMap<String, String> user) {
return new User(user.get("brukernavn"), user.get("fornavn"), user.get("etternavn"), user.get("epost"));
}
private static Group generateGroup(HashMap<String, String> group) {
return new Group(Integer.parseInt(group.get("gruppeId")), group.get("gruppeNavn"), group.get("beskrivelse"));
}
private static Room generateRoom(HashMap<String, String> room) {
return new Room(Integer.parseInt(room.get("romId")), room.get("romNavn"), Integer.parseInt(room.get("kapasitet")));
}
private static Event generateEvent(HashMap<String, String> event) {
return new Event(Integer.parseInt(event.get("eventId")), event.get("eventNavn"), event.get("beskrivelse"), LocalDate.parse(event.get("dato")),
LocalTime.parse(event.get("fraKl")), LocalTime.parse(event.get("tilKl")), event.get("sted"), Integer.parseInt(event.get("alarmTid")), !"0".equals(event.get("endring")), !"0".equals(event.get("ny")));
}
//------------------------------
// Private misc methods
//------------------------------
private static Set<Integer> getAllSubGroupIds(int groupId) {
Set<Integer> groups = new HashSet<Integer>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Gruppe.* " +
"FROM UnderGruppe " +
"INNER JOIN Gruppe ON UnderGruppe.underGruppeId = Gruppe.gruppeId " +
"WHERE UnderGruppe.superGruppeId = '"+groupId+"'");
groups.add(groupId);
for(int i=0; i<tmp.size(); i++) {
groups.addAll(getAllSubGroupIds(Integer.parseInt(tmp.get(i).get("gruppeId"))));
}
return groups;
}
private static Set<Integer> getAllSuperGroups(int groupId) {
Set<Integer> groups = new HashSet<Integer>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Gruppe.gruppeId " +
"FROM UnderGruppe " +
"INNER JOIN Gruppe ON UnderGruppe.superGruppeId = Gruppe.gruppeId " +
"WHERE UnderGruppe.underGruppeId = '"+groupId+"'");
groups.add(groupId);
for(int i=0; i<tmp.size(); i++) {
groups.addAll(getAllSuperGroups(Integer.parseInt(tmp.get(i).get("gruppeId"))));
}
return groups;
}
private static Group getGroupFromId(int id) {
return generateGroup(readQuery(
"SELECT * " +
"FROM Gruppe " +
"WHERE gruppeId = "+id).get(0));
}
private static String hash(byte bytes[]) {
String hash = new String();
try {
// Hashes byte array
MessageDigest MD;
MD = MessageDigest.getInstance("MD5");
MD.update(bytes);
bytes = MD.digest();
// Converts it to hexadecimal
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
hash = new String(hexChars);
} catch (Exception e) {
System.out.println("Cant hash");
e.printStackTrace();
}
return hash;
}
private static String encryptPassword(String password, String salt) {
// Append salt to password hashes it and returns it
return hash((password+salt).getBytes());
}
private static Image getProfilePicture(String username) {
Image img = null;
ResultSet rs = null;
try {
PreparedStatement s = connection.prepareStatement(
"SELECT bilde " +
"FROM ProfilBilde " +
"WHERE brukernavn = '"+username+"'");
rs = s.executeQuery();
if(rs.next()) {
img = new Image(rs.getBinaryStream(1));
}else{
img = new Image(new FileInputStream("etc/defaultPicture.png"));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return img;
}
private static void updateCurrentUser() {
if(currentUser != null) {
currentUser = getUserFromUsername(currentUser.getUname());
}
}
//------------------------------
// public login functions
//------------------------------
public static boolean loginUser(String username, String password) {
// Reset
loggout();
// Validate user
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT * " +
"FROM Bruker " +
"WHERE brukernavn = '"+username+"'");
if(tmp.size() == 0) return false;
if(!tmp.get(0).get("passord").equals(encryptPassword(password, tmp.get(0).get("salt")))) return false;
// Login
currentUser = generateUser(tmp.get(0));
currentImg = getProfilePicture(username);
return true;
}
public static void loggout() {
currentUser = null;
currentImg = null;
}
public static User getCurrentUser() {
return currentUser;
}
public static Image getCurrentProfilePicture() {
return currentImg;
}
public static boolean validateUser(String username, String password) {
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT * " +
"FROM Bruker " +
"WHERE brukernavn = '"+username+"'");
if(tmp.size() == 0) return false;
return tmp.get(0).get("passord").equals(encryptPassword(password, tmp.get(0).get("salt")));
}
public static void updateCurrentProfilePicture() {
currentImg = getProfilePicture(getCurrentUser().getUname());
}
//------------------------------
// public connection functions
//------------------------------
public static void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL, username, pw);
stat = connection.createStatement();
} catch (Exception ex) {
System.out.println("Tilkobling til databaseserver feilet: "+ ex.getMessage());
System.out.println("For aa koble til databaseserveren maa du vere paa NTNU-nettet. Bruk VPN hvis du er utenfor NTNU-nettet.");
}
}
public static void close() {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//------------------------------
// Public getters
//------------------------------
public static ArrayList<Event> getEventsWithActiveAlarms(User user) {
return getEventsWithActiveAlarms(user.getUname());
}
public static ArrayList<Event> getEventsWithActiveAlarms(String username) {
ArrayList<Event> events = new ArrayList<Event>();
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
String nowDate = dateFormat.format(cal.getTime());
String nowTime = timeFormat.format(cal.getTime());
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Event.*, BrukerInvitert.endring, BrukerInvitert.alarmTid, BrukerInvitert.ny " +
"FROM BrukerInvitert " +
"INNER JOIN Event ON Event.eventId = BrukerInvitert.eventId " +
"WHERE BrukerInvitert.brukernavn = '"+username+"'");
for(int i=0; i<tmp.size(); i++) {
events.add(generateEvent(tmp.get(i)));
}
return events;
}
public static ArrayList<Event> getEventsFromUser(User user) {
return getEventsFromUser(user.getUname());
}
public static ArrayList<Event> getEventsFromUser(String username) {
ArrayList<Event> events = new ArrayList<Event>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Event.*, BrukerInvitert.endring, BrukerInvitert.alarmTid, BrukerInvitert.ny " +
"FROM BrukerInvitert " +
"INNER JOIN Event ON Event.eventId = BrukerInvitert.eventId " +
"WHERE BrukerInvitert.brukernavn = '"+username+"'");
for(int i=0; i<tmp.size(); i++) {
events.add(generateEvent(tmp.get(i)));
}
return events;
}
public static ArrayList<Event> getChangedEventsFromUser(User user) {
ArrayList<Event> events = new ArrayList<Event>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Event.*, BrukerInvitert.endring, BrukerInvitert.alarmTid, BrukerInvitert.ny " +
"FROM BrukerInvitert " +
"INNER JOIN Event ON Event.eventId = BrukerInvitert.eventId " +
"WHERE endring = 1 " +
"AND BrukerInvitert.brukernavn = '"+user.getUname()+"'");
for(int i=0; i<tmp.size(); i++) {
events.add(generateEvent(tmp.get(i)));
}
return events;
}
public static ArrayList<Event> getNewEventsFromUser(User user) {
ArrayList<Event> events = new ArrayList<Event>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Event.*, BrukerInvitert.endring, BrukerInvitert.alarmTid, BrukerInvitert.ny " +
"FROM BrukerInvitert " +
"INNER JOIN Event ON Event.eventId = BrukerInvitert.eventId " +
"WHERE ny = 1 " +
"AND BrukerInvitert.brukernavn = '"+user.getUname()+"'");
for(int i=0; i<tmp.size(); i++) {
events.add(generateEvent(tmp.get(i)));
}
return events;
}
public static ArrayList<Event> getEventsFromGroup(Group group) {
ArrayList<Event> events = new ArrayList<Event>();
Set<Integer> groups = getAllSuperGroups(group.getId());
String query =
"SELECT DISTINCT Event.* " +
"FROM GruppeInvitert " +
"INNER JOIN Event ON GruppeInvitert.eventId = Event.eventId " +
"WHERE GruppeInvitert.gruppeId = '"+group.getId()+"' ";
for(int id : groups) {
query += "OR GruppeInvitert.gruppeId = '"+id+"' ";
}
ArrayList<HashMap<String, String>> tmp = readQuery(query);
for(int i=0; i<tmp.size(); i++) {
// Event does not have change, new and alarmTime fields
tmp.get(i).put("endring", "0");
tmp.get(i).put("alarmTid", "0");
tmp.get(i).put("ny", "0");
events.add(generateEvent(tmp.get(i)));
}
return events;
}
public static ArrayList<Event> getEventsFromRom(Room room) {
ArrayList<Event> events = new ArrayList<Event>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Event.* " +
"FROM Rom " +
"INNER JOIN Event ON Event.romId = Rom.romId " +
"WHERE Rom.romId = '"+room.getId()+"'");
for(int i=0; i<tmp.size(); i++) {
// Event does not have change, new and alarmTime fields
tmp.get(i).put("endring", "0");
tmp.get(i).put("alarmTid", "0");
tmp.get(i).put("ny", "0");
events.add(generateEvent(tmp.get(i)));
}
return events;
}
public static ArrayList<User> getAllUsers() {
ArrayList<User> users = new ArrayList<User>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT * " +
"FROM Bruker");
for(int i=0; i<tmp.size(); i++) {
users.add(generateUser(tmp.get(i)));
}
return users;
}
public static ArrayList<User> getUsersFromGroup(Group group) {
ArrayList<User> users = new ArrayList<User>();
Set<Integer> groups = getAllSubGroupIds(group.getId());
String query =
"SELECT DISTINCT Bruker.* " +
"FROM Bruker " +
"INNER JOIN MedlemAv ON MedlemAv.brukernavn = Bruker.brukernavn " +
"WHERE MedlemAv.gruppeId = '"+group.getId()+"' ";
for(int id : groups) {
query += "OR MedlemAv.gruppeId = '"+id+"' ";
}
ArrayList<HashMap<String, String>> tmp = readQuery(query);
for(int i=0; i<tmp.size(); i++) {
users.add(generateUser(tmp.get(i)));
}
return users;
}
public static ArrayList<User> getInviteesFromEvent(Event event) {
ArrayList<User> users = new ArrayList<User>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Bruker.* " +
"FROM BrukerInvitert " +
"INNER JOIN Bruker ON BrukerInvitert.brukernavn = Bruker.brukernavn " +
"WHERE BrukerInvitert.eventId = '"+event.getId()+"'");
for(int i=0; i<tmp.size(); i++) {
users.add(generateUser(tmp.get(i)));
}
return users;
}
public static ArrayList<User> getNonParticipantsFromEvent(Event event) {
ArrayList<User> users = new ArrayList<User>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Bruker.* " +
"FROM BrukerInvitert " +
"INNER JOIN Bruker ON BrukerInvitert.brukernavn = Bruker.brukernavn " +
"WHERE BrukerInvitert.eventId = '"+event.getId()+"' " +
"AND BrukerInvitert.deltar != 'ja'");
for(int i=0; i<tmp.size(); i++) {
users.add(generateUser(tmp.get(i)));
}
return users;
}
public static ArrayList<User> getParticipantsFromEvent(Event event) {
ArrayList<User> users = new ArrayList<User>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Bruker.* " +
"FROM BrukerInvitert " +
"INNER JOIN Bruker ON BrukerInvitert.brukernavn = Bruker.brukernavn " +
"WHERE BrukerInvitert.eventId = '"+event.getId()+"' " +
"AND BrukerInvitert.deltar = 'ja'");
for(int i=0; i<tmp.size(); i++) {
users.add(generateUser(tmp.get(i)));
}
return users;
}
public static User getAdminFromEvent(Event event) {
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Bruker.* " +
"FROM Event " +
"INNER JOIN Bruker ON Event.admin = Bruker.brukernavn " +
"WHERE Event.eventId = '"+event.getId()+"'");
return generateUser(tmp.get(0));
}
public static User getUserFromUsername(String username) {
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT * " +
"FROM Bruker " +
"WHERE Bruker.brukernavn = '"+username+"'");
return generateUser(tmp.get(0));
}
public static ArrayList<Group> getAllGroups() {
ArrayList<Group> groups = new ArrayList<Group>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT * " +
"FROM Gruppe");
for(int i=0; i<tmp.size(); i++) {
groups.add(generateGroup(tmp.get(i)));
}
return groups;
}
public static ArrayList<Group> getGroupsFromUser(User user) {
ArrayList<Group> groups = new ArrayList<Group>();
Set<Integer> ids = new HashSet<Integer>();
Set<Integer> ans = new HashSet<Integer>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Gruppe.gruppeId " +
"FROM MedlemAv " +
"INNER JOIN Gruppe ON MedlemAv.gruppeId = Gruppe.gruppeId " +
"WHERE MedlemAv.brukernavn = '"+user.getUname()+"'");
for(HashMap<String, String> row : tmp) {
ids.add(Integer.parseInt(row.get("gruppeId")));
}
for(int id : ids) {
ans.addAll(getAllSuperGroups(id));
}
for(int id : ans) {
groups.add(getGroupFromId(id));
}
return groups;
}
public static ArrayList<Group> getGroupsFromEvent(Event event) {
ArrayList<Group> groups = new ArrayList<Group>();
Set<Integer> ids = new HashSet<Integer>();
Set<Integer> ans = new HashSet<Integer>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Gruppe.* " +
"FROM GruppeInvitert " +
"INNER JOIN Gruppe ON GruppeInvitert.gruppeId = Gruppe.gruppeId " +
"WHERE GruppeInvitert.eventId = '"+event.getId()+"'");
for(HashMap<String, String> row : tmp) {
ids.add(Integer.parseInt(row.get("gruppeId")));
}
for(int id : ids) {
ans.addAll(getAllSubGroupIds(id));
}
for(int id : ans) {
groups.add(getGroupFromId(id));
}
return groups;
}
public static ArrayList<Group> getAllSubGroups(Group group) {
Set<Integer> ids = getAllSubGroupIds(group.getId());
ArrayList<Group> groups = new ArrayList<Group>();
for(int id : ids) {
groups.add(getGroupFromId(id));
}
return groups;
}
public static int getParticipantCount(Event event) {
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT COUNT(*) AS count " +
"FROM BrukerInvitert " +
"WHERE eventId = '"+event.getId()+"' " +
"AND BrukerInvitert.deltar = 'ja'");
return Integer.parseInt(tmp.get(0).get("count"));
}
public static int getInviteeCount(Event event) {
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT COUNT(*) AS count " +
"FROM BrukerInvitert " +
"WHERE eventId = '"+event.getId()+"'");
return Integer.parseInt(tmp.get(0).get("count"));
}
public static ArrayList<Room> getAllRooms() {
ArrayList<Room> rooms = new ArrayList<Room>();
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT * " +
"FROM Rom");
for(int i=0; i<tmp.size(); i++) {
rooms.add(generateRoom(tmp.get(i)));
}
return rooms;
}
public static ArrayList<Room> getAvailableRooms(LocalDate date, String fromTime, String toTime) {
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT * " +
"FROM Rom " +
"WHERE Rom.romId NOT IN " +
"(SELECT DISTINCT romId " +
"FROM Event " +
"WHERE dato = '"+date+"' " +
"AND tilKl > '"+fromTime+"' " +
"AND fraKl < '"+toTime+"' " +
"AND romId IS NOT NULL)");
ArrayList<Room> rooms = new ArrayList<Room>();
for(HashMap<String, String> room : tmp) {
rooms.add(generateRoom(room));
}
return rooms;
}
public static Room getRoomFromEvent(Event event) {
ArrayList<HashMap<String, String>> tmp = readQuery(
"SELECT Rom.* " +
"FROM Event " +
"INNER JOIN Rom ON Event.romId = Rom.romId " +
"WHERE Event.eventId = '"+event.getId()+"'");
if(tmp.size() == 0) return null;
return generateRoom(tmp.get(0));
}
//------------------------------
// Public setters
//------------------------------
public static void setProfilePicture(User user, File file) {
setProfilePicture(user.getUname(), file);
}
public static void setProfilePicture(String username, File file) {
try {
updateQuery(
"INSERT IGNORE INTO ProfilBilde " +
"VALUES('"+username+"', null)");
PreparedStatement s = connection.prepareStatement(
"UPDATE ProfilBilde " +
"SET bilde = ? " +
"WHERE brukernavn = '"+username+"'");
FileInputStream img = new FileInputStream(file);
s.setBinaryStream(1, img, img.available());
s.executeUpdate();
} catch (IOException e) {
System.out.println("ERROR! Could not load picture!");
deleteProfilePicture(username);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void deleteProfilePicture(User user) {
deleteProfilePicture(user.getUname());
}
public static void deleteProfilePicture(String username) {
updateQuery(
"DELETE FROM ProfilBilde " +
"WHERE brukernavn = '"+username+"'");
}
public static Event createEvent(String title, String descr, LocalDate evdate, LocalTime startHour, LocalTime endHour, String place, User admin, Room room) {
String roomId = "null";
if(room != null) roomId = Integer.toString(room.getId());
updateQuery(
"INSERT INTO Event(eventNavn, sted, beskrivelse, dato, fraKl, tilKl, romId, admin) " +
"VALUES('"+title+"', '"+place+"', '"+descr+"', '"+evdate+"', '"+startHour+"', '"+endHour+"', "+roomId+", '"+admin.getUname()+"')");
int id = Integer.parseInt(readQuery("SELECT LAST_INSERT_ID() AS id").get(0).get("id"));
HashMap<String, String> event = readQuery(
"SELECT * " +
"FROM Event " +
"WHERE eventId = "+id).get(0);
// Event does not have change, new and alarmTime fields
event.put("endring", "0");
event.put("alarmTid", "0");
event.put("ny", "0");
return generateEvent(event);
}
public static void changeEvent(String title, String descr, LocalDate evdate, LocalTime startHour, LocalTime endHour, String place, User admin, Event event, Room room) {
String roomId = "null";
if(room != null) roomId = Integer.toString(room.getId());
updateQuery(
"UPDATE Event " +
"SET eventNavn = '"+title+"', sted = '"+place+"', beskrivelse = '"+descr+"', dato = '"+evdate+"', fraKl = '"+startHour+"', tilKl = '"+endHour+"', romId = "+roomId+", admin = '"+admin.getUname()+"' " +
"WHERE eventId = '"+event.getId()+"'");
updateQuery(
"UPDATE BrukerInvitert " +
"SET endring = 1 " +
"WHERE eventId = '"+event.getId()+"' ");
}
public static void deleteEvent(Event event) {
updateQuery(
"DELETE FROM Event " +
"WHERE eventId = '"+event.getId()+"'");
}
public static void registrateInvitation(User user, Event event) {
registrateInvitation(user.getUname(), event);
}
public static void registrateInvitation(String username, Event event) {
updateQuery(
"INSERT INTO BrukerInvitert " +
"VALUES('"+event.getId()+"', '"+username+"', 'ingenSvar', 0, 0, 1) " +
"ON DUPLICATE KEY UPDATE " +
"deltar = 'ingenSvar', alarmTid = 0, endring = 0, ny = 0");
}
public static void registrateGInvitation(Group group, Event event) {
updateQuery(
"INSERT IGNORE INTO GruppeInvitert " +
"VALUES('"+event.getId()+"', '"+group.getId()+"')");
ArrayList<User> users = getUsersFromGroup(group);
for(User user : users) {
registrateInvitation(user, event);
}
}
public static void registrateParticipation(User user, Event event, boolean participate) {
registrateParticipation(user.getUname(), event, participate);
}
public static void registrateParticipation(String username, Event event, boolean participate) {
String tmp = "nei";
if(participate) tmp = "ja";
updateQuery(
"INSERT INTO BrukerInvitert " +
"VALUES('"+event.getId()+"', '"+username+"', '"+tmp+"', 0, 0, 0) " +
"ON DUPLICATE KEY UPDATE " +
"deltar = '"+tmp+"', alarmTid = 0, endring = 0, ny = 0");
}
public static void deleteUserInvitation(User user, Event event) {
updateQuery(
"DELETE FROM BrukerInvitert " +
"WHERE brukernavn = '"+user.getUname()+"' " +
"AND eventId = "+event.getId());
}
public static void setInvitationChange(String username, Event event, boolean change) {
int state = 0;
if(change) state = 1;
updateQuery(
"UPDATE BrukerInvitert " +
"SET endring = '"+state+"' " +
"WHERE eventId = '"+event.getId()+"' " +
"AND brukernavn = '"+username+"'");
}
public static void setInvitationChange(User user, Event event, boolean change) {
setInvitationChange(user.getUname(), event, change);
}
public static void setInvitationIsNew(String username, Event event, boolean invitationIsNew) {
int state = 0;
if(invitationIsNew) state = 1;
updateQuery(
"UPDATE BrukerInvitert " +
"SET ny = '"+state+"' " +
"WHERE eventId = '"+event.getId()+"' " +
"AND brukernavn = '"+username+"'");
}
public static void setInvitationIsNew(User user, Event event, boolean change) {
setInvitationIsNew(user.getUname(), event, change);
}
public static void setAlarmTime(User user, Event event, int alarmTime) {
updateQuery(
"UPDATE BrukerInvitert " +
"SET alarmTid = '"+alarmTime+"' " +
"WHERE eventId = '"+event.getId()+"' " +
"AND brukernavn = '"+user.getUname()+"'");
}
public static void createUser(String username, String password, String firstname, String lastname, String email) {
// Create salt
Random rn = new Random();
byte[] bytes = new byte[16];
rn.nextBytes(bytes);
String salt = hash(bytes);
updateQuery(
"INSERT IGNORE INTO Bruker " +
"VALUES('"+username+"','"+encryptPassword(password, salt)+"','"+firstname+"','"+lastname+"','"+email+"','"+salt+"')");
}
public static void changeUser(String newUsername, String firstname, String lastname, String email, User oldUser) {
changeUser(newUsername, firstname, lastname, email, oldUser.getUname());
}
public static void changeUser(String newUsername, String firstname, String lastname, String email, String oldUsername) {
updateQuery(
"UPDATE Bruker " +
"SET brukernavn = '"+newUsername+"', fornavn = '"+firstname+"', etternavn = '"+lastname+"', epost = '"+email+"' " +
"WHERE brukernavn = '"+oldUsername+"'");
updateCurrentUser();
}
public static void changeEmail(String email, User user) {
changeEmail(email, user.getUname());
}
public static void changeEmail(String email, String username) {
updateQuery(
"UPDATE Bruker " +
"SET epost = '"+email+"' " +
"WHERE brukernavn = '"+username+"'");
updateCurrentUser();
}
public static void changePassword(String password, User user) {
changePassword(password, user.getUname());
}
public static void changePassword(String password, String username) {
Random rn = new Random();
byte[] bytes = new byte[16];
rn.nextBytes(bytes);
String salt = hash(bytes);
updateQuery(
"UPDATE Bruker " +
"SET passord = '"+encryptPassword(password, salt)+"', salt = '"+salt+"'" +
"WHERE brukernavn = '"+username+"'");
}
public static void deleteUser(User user) {
deleteUser(user.getUname());
}
public static void deleteUser(String username) {
updateQuery(
"DELETE FROM Bruker " +
"WHERE brukernavn = '"+username+"'");
}
public static void addUserToGroup(User user, Group group) {
addUserToGroup(user.getUname(), group);
}
public static void addUserToGroup(String username, Group group) {
updateQuery(
"INSERT IGNORE INTO MedlemAv " +
"VALUES('"+username+"', '"+group.getId()+"')");
}
public static void removeUserFromGroup(User user, Group group) {
removeUserFromGroup(user.getUname(), group);
}
public static void removeUserFromGroup(String username, Group group) {
updateQuery(
"DELETE FROM MedlemAv " +
"WHERE brukernavn = '"+username+"'");
}
}<file_sep># TDT4140-fproj36
Samlemappe til fellesprosjektet til gruppe 36 i emnetTDT4140 Programvareutvikling.
Dududu<file_sep>package tester;
/*
import static org.junit.Assert.*;
import java.time.LocalDate;
import java.time.LocalTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import prosjektKlasser.Calendar;
import prosjektKlasser.Event;
import prosjektKlasser.User;
import prosjektKlasser.Event;
public class CalendarTest {
private Calendar kalender = null; //kaller paa konstruktoren til kalenderkalssen i setup - metoden
public void setUp() throws Exception {
this.kalender = new Calendar();
//Instansierer testbrukerne johjoh, gurkun, hermos, og lisnyp.
User johjoh = new User("johjoh", "hAn7r0tMo", "<NAME>");
User gurkun = new User("gurkun", "skJitKj6Rr9NG", "<NAME>");
User lisnyp = new User("lisnyp", "FeTtKj6Rr9NG", "<NAME>");
User hermos = new User("hermos", "hordisMesl1tt", "<NAME>");
//Instansierer Event kodeKveld
Event kodeKveld = new Event("kodeKveld", "Samling for aa skrive koden til programmet.", LocalDate.of(2015,3,1), LocalTime.of(19,00), LocalTime.of(22,00), "5-20");
kalender.addEvent(kodeKveld);
kodeKveld.addUser(johjoh);
kodeKveld.addUser(gurkun);
kodeKveld.addUser(lisnyp);
kodeKveld.addUser(hermos);
}
public void testRemoveNonExistentElementFromList() {
try {
//Her er testobjektene som skal lage feil;)
Event tull = new Event("Dasstur", "E gaar paa dass", LocalDate.of(2015,3,1), LocalTime.of(19,00), LocalTime.of(19,05), "5-DASS2");
kalender.removeEvent(tull);
//Og her er testobjektene som skal lage artige feil ;)
Event tull = new Event("Dasstur", "E gaar paa dass", LocalDate.of(2015,3,1), LocalTime.of(19,00), LocalTime.of(19,05), "5-DASS2");
}
void testRemoveNonExistentElementFromList(Event ev) {
try {
kalender.removeEvent(ev);
}
catch (IndexOutOfBoundsException err) {
fail("Tried to search for nonexisting element."); }
}
public void testRemoveExistentElementFromList() {
try {
Event kodeKveld = new Event("kodeKveld", "Samling for aa skrive koden til programmet.", LocalDate.of(2015,3,1), LocalTime.of(19,00), LocalTime.of(22,00), "5-20");
kalender.removeEvent(kodeKveld);
}
catch (Exception e) {
System.out.println("M");
}
}
public void tearDown() throws Exception {
this.kalender = null;
}
public static void main(String[] args) throws Exception {
CalendarTest o = new CalendarTest();
Instansierer testbrukerne johjoh, gurkun, hermos, og lisnyp.
o.setUp();
o.testRemoveNonExistentElementFromList();
System.out.println("Test passed.");
o.tearDown();
public void test() {
fail("Not yet implemented");
}
public static void main(String[] args) throws Exception {
CalendarTest o = new CalendarTest();
o.setUp();
Event tull = new Event("Dasstur", "E gaar paa dass", LocalDate.of(2015,3,1), LocalTime.of(19,00), LocalTime.of(19,05), "5-DASS2");
o.testRemoveNonExistentElementFromList(tull);
}
}
*/<file_sep>package models;
import java.time.LocalDate;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
public class Calendar {
//Behandle tid i kalenderen, en veldig viktig funksjon i de fleste kalendere...
private List<Event> eventList = new ArrayList<Event>();
private LocalDate dato;
//Ment for å vise ukenummer, men er trolig unodvendige.
private WeekFields weekFields;
private int weekNumber;
//Konstruktor til kalender - objektet.
public Calendar() {
this.dato = LocalDate.now();
weekFields = WeekFields.of(Locale.getDefault());
//weekNumber = dato.get(weekFields.weekOfWeekBasedYear());
//weekNumber = this.dato.get((TemporalField) WeekFields.WEEK_BASED_YEARS);
LocalDate date = LocalDate.now();
TemporalField woy = WeekFields.of(Locale.getDefault()).weekOfWeekBasedYear();
weekNumber = date.get(woy);
}
//Behandle listen av events som er inneholdt i kalenderen.
public void addEvent (Event ev) {
eventList.add(ev);
}
// Fjerne hendelse fra kalenderen
public void removeEvent (Event ev) {
int i = searchList (ev);
if (i != -1) { eventList.remove(i); }
}
private int searchList (Event ev) {
for (Event e : eventList) {
if (e == ev) {
return eventList.indexOf(e);
}
}
return -1;
}
// Lager nytt datoobjekt som tilsvarer dagen i dag ifølge kalendertjeneren.
void update (LocalDate dato) {
dato = (LocalDate.now());
}
public LocalDate getDato() {
return dato;
}
//Her må kanskje noe gjøres:
public static int getWeekNumber() {
//Dette er ikke helt bra,men fikk ikke hentet det ellers.....
LocalDate date = LocalDate.now();
TemporalField woy = WeekFields.of(Locale.getDefault()).weekOfWeekBasedYear();
int weekNumbah = date.get(woy);
return weekNumbah;
}
public static String getMonth(){
LocalDate date = LocalDate.now();
String monthNr = date.getMonth().toString();
return monthNr;
}
public static int getYear(){
LocalDate date = LocalDate.now();
int year = date.getYear();
return year;
}
public static String getDay(){
LocalDate date = LocalDate.now();
String day = date.getDayOfWeek().toString();
return day;
}
public static LocalDate getToday(){
LocalDate date = LocalDate.now();
return date;
}
// public static String dateView(Date dato){
// String dag = dato.toString();
// return dag;
//}
//public static String getDateAsString(){
// LocalDate date = LocalDate.now();
// int dateAsInt = date.getDayOfMonth();
// int dateAsString = (date.getDayOfMonth());
//return dateAsString;
//}
//public static String dateView(Date dato){
// int dateAsInt = dato.getDayOfMonth();
// return dateAsInt.toString();
//}
}
| eb956bacb5c9c0070162927b4a8b0eba50232a46 | [
"Markdown",
"Java"
]
| 13 | Java | vegardbb/TDT4140-fproj36 | 681d55b4d77713c48fdec877214f2daf0a9254ff | de6aa9d994b41939da7faa6311992b23709b4bb4 |
refs/heads/master | <file_sep>import { galacticAge } from './../src/galactic.js';
describe('Age', function () {
it('should convert a persons age into seconds', function() {
let age = new galacticAge(1);
expect(age.yearsToSeconds(1)).toEqual(31536000);
});
it('should determine the difference between two dates in seconds', function() {
// take two dates get diff (d2-d1) = results / 1000;
let age = new galacticAge(26, "1991-08-04");
expect(age.dateDifference()).toBeGreaterThan(840096418); // differnt matcher for flexibility round up or down.
});
it('should return user age into Mercury age', function() {
let age = new galacticAge(26, "1991-08-04");
expect(age.mercuryAge()).toBeGreaterThanOrEqual(108);
});
it('should return user age into Venus age', function() {
let age = new galacticAge(26, "1991-08-04");
expect(age.venusAge()).toBeGreaterThanOrEqual(41);
});
it('should return user age into Mars age', function() {
let age = new galacticAge(26, "1991-08-04");
expect(age.marsAge()).toBeGreaterThanOrEqual(13);
});
it('should return user age into Jupiter age', function() {
let age = new galacticAge(26, "1991-08-04");
expect(age.jupiterAge()).toBeGreaterThanOrEqual(2);
});
it('returns remaining time on Earth', function() {
let age = new galacticAge(26, "1991-08-04");
expect(age.remainingEarth()).toEqual(46);
});
it('returns remaining time on Mercury', function () {
let age = new galacticAge(26, "1991-08-04");
expect(age.remainingMercury()).toEqual(191);
});
it('returns remaining time on Venus', function() {
let age = new galacticAge(26, "1991-08-04");
expect(age.remainingVenus()).toEqual(74);
})
it('returns remaining time on Mars', function() {
let age = new galacticAge(26);
expect(age.remainingMars()).toEqual(24);
})
it('returns remaining time on Jupiter', function() {
let age = new galacticAge(26);
expect(age.remainingJupiter()).toEqual(3);
})
});
<file_sep>// import { Galactic } from './galatic.js';
// import $ from 'jquery';
// import 'bootstrap';
// import './styles.css';
<file_sep># Galactic Age
#### Javascript webpacks with testing, 3/19/2018
#### By <NAME>
## Description
A javascript application that focuses on using test specs with webpack and jasmine use. In a neat package on finding your age on other planets in our solar system.
## Setup/Installation Requirements
Open Terminal <br/>
Clone on your local machine, run the following in the Terminal
```
$ git clone https://github.com/kihuynh/age-calculator
```
Run the following!
```
$ npm install
$ npm run build
$ npm run test
```
## Technologies Used
* JavaScript
* Webpack
* Jasmine
* Karma
## License
*Licensed under MIT license*
Copyright (c) 2018 **_<NAME>_**
| 3ccac5e8c331b9a06dabf0b1a60e037dd914de9f | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | kihuynh/age-calculator | 65361d4bc8b8bd8ac4c3e0639cc61d5869e51810 | 54da45583a3ecc1d6f8137a73b7f7d99bd760994 |
refs/heads/main | <file_sep># Seaport-Project
Stuff for the project with seaport
<file_sep>function lookup() {
console.log(working);
}
$(document).ready(function(){
console.log('ready');
$('#lookupButton').click(function(){
console.log('hi');
});
}) | b14f584f715a825d109260d76007748023b1ccbc | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | ejd237/Seaport-Project | 4ea4de4a3a6ba9c3d6b115b7325561de14a48b19 | e20c096ba8e9188c28c0103636d495c9d5da298c |
refs/heads/master | <file_sep>"""
Implementing custom encryption, as the default "fernet" method from the cryptography package
uses random initialization numbers, which cause a different encrypted string for identical content all the time.
We don't need message authentication in our case, and changing strings would be annoying in Git.
"""
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
def encrypt(data: bytes, key: bytes, iv_bytes: bytes) -> bytes:
"""
data can be bytes of arbitrary length
key must be 32 bytes long
iv_bytes can be of arbitrary length, as they will be hashed
"""
iv_digest = hashes.Hash(hashes.SHA256(), default_backend())
iv_digest.update(iv_bytes)
iv = iv_digest.finalize()[:16]
algorithm = algorithms.AES(key)
mode = modes.CBC(iv)
cipher = Cipher(algorithm, mode=mode, backend=default_backend())
encryptor = cipher.encryptor()
padder = padding.PKCS7(algorithm.block_size).padder()
to_encrypt = padder.update(iv + data) + padder.finalize()
encrypted = encryptor.update(to_encrypt) + encryptor.finalize()
return base64.b64encode(encrypted)
def decrypt(data: bytes, key: bytes) -> bytes:
"""
data should be encrypted binary, encoded as base64 - as it is produced by 'encrypt()'
key must be 32 bytes long
"""
data = base64.b64decode(data)
iv = data[:16]
message = data[16:]
algorithm = algorithms.AES(key)
mode = modes.CBC(iv)
cipher = Cipher(algorithm, mode=mode, backend=default_backend())
decryptor = cipher.decryptor()
decrypted_padded = decryptor.update(message) + decryptor.finalize()
unpadder = padding.PKCS7(algorithm.block_size).unpadder()
decrypted = unpadder.update(decrypted_padded) + unpadder.finalize()
return decrypted
<file_sep>from pathlib import Path
from typing import List
from .. import cipher
class GenericFileHandler:
def __init__(self, filepath: Path, data: List[str]):
self.filepath = filepath
def dump_decrypted(self, target: Path, key: bytes):
target.write_bytes(cipher.decrypt(self.filepath.read_bytes(), key))
def dump_encrypted(self, target: Path, key: bytes):
target.write_bytes(cipher.encrypt(self.filepath.read_bytes(), key, str(self.filepath).encode('utf8')))
<file_sep>[tool.poetry]
name = "secrets_tool"
description = "A lightweight tool to easily encrypt/decrypt secrets inside a repository"
authors = ["<NAME> <<EMAIL>>"]
license = "MIT"
readme = "README.md"
repository = "https://github.com/defreng/secrets-tool"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
# Version is set by GitHub action workflow (on release)
version = "0.0.1+local"
[tool.poetry.dependencies]
python = "^3.8"
cryptography = "^2.9.2"
"ruamel.yaml" = "^0.16.10"
[tool.poetry.scripts]
secrets_tool = "secrets_tool.__main__:main"
[tool.poetry.dev-dependencies]
mypy = "^0.782"
flake8 = "^3.8.3"
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
<file_sep>"""
Classes to encrypt and decrypt YAML files.
This 'compatibility' handler doesn't need additional tags in the YAML files. Instead, the desired paths
to en- and decrypt are given in the .gitignore file
The desired paths for encryption MUST refer to a string field.
"""
from pathlib import Path
from typing import List
import ruamel.yaml
from .. import cipher
def getitem(obj, path: str):
if len(path) == 0:
return obj
path_parts = path.split('.', maxsplit=1)
key = path_parts[0]
remainder = path_parts[1] if len(path_parts) > 1 else ''
if isinstance(obj, dict):
return getitem(obj[key], remainder)
if isinstance(obj, list):
return getitem(obj[int(key)], remainder)
else:
ValueError('Cant read object', obj)
def setitem(root, path, value):
if path.find('.') < 0:
obj = root
key = path
else:
obj = getitem(root, path.rsplit('.', maxsplit=1)[0])
key = path.rsplit('.', maxsplit=1)[1]
if isinstance(obj, dict):
obj[key] = value
elif isinstance(obj, list):
obj[int(key)] = value
else:
ValueError('Cant write object', obj)
class YamlCompatFileHandler:
def __init__(self, filepath: Path, data: List[str]):
self.yaml = ruamel.yaml.YAML()
self.filepath = filepath
self.data = data
def dump_decrypted(self, target: Path, key: bytes):
tree = self.yaml.load(self.filepath)
for path in self.data:
encrypted = getitem(tree, path)
decrypted = cipher.decrypt(encrypted.encode('ascii'), key).decode('utf8')
setitem(tree, path, decrypted)
self.yaml.dump(tree, target)
def dump_encrypted(self, target: Path, key: bytes):
tree = self.yaml.load(self.filepath)
for path in self.data:
decrypted = getitem(tree, path)
encrypted = cipher.encrypt(decrypted.encode('utf8'), key, path.encode('ascii')).decode('ascii')
setitem(tree, path, encrypted)
self.yaml.dump(tree, target)
<file_sep># Secrets Tool
This is a small tool which helps to encrypt secrets that must be committed to a Git repository.
It has the advantage to natively support partial encryption of YAML files. This is of great advantage, as it allows to see the YAML file structure even when some of its contents are encrypted (your PR reviewers and diff tools will thank you)
## Installation
Docker build:
`docker build --build-arg VERSION=0.0.1+local -t secrets_tool .`
## Usage
The tool reads a list of files to encrypt/decrypt from a `.gitignore` file. In there it will only consider files that are sorrounded by a comment block as in the following example:
```
# BEGIN ENCRYPTED
kaas-rubik-stage/values.yaml
# END ENCRYPTED
```
Execute the tool in the directory containing the `.gitignore` file:
* decrypt: `docker run -v $(pwd):/repo -v ~/.my-secret-key:/secrets-tool-key secrets_tool`
* encrypt: `docker run -v $(pwd):/repo -v ~/.my-secret-key:/secrets-tool-key secrets_tool encrypt`
## .gitignore Syntax
The tool provides different encryption handlers for all kind of file types.
* `yaml` for YAML files that are used by tools which are okay having a `!decrypted` tag in front of strings
* `yamlcompat` for tools that don't like the additional 'encryption marker' tag.
* `generic` for all other file types. It encrypts the complete file.
The desired encryption handler is inferred from the filetype - or it can be given explicitly in the gitignore file using the `# type:` hint:
```
# BEGIN ENCRYPTED
kaas-rubik-stage/values.yaml
# type: yaml
kaas-rubik-stage/values2.txt
# END ENCRYPTED
```
### yamlcompat
This encryption handler can encrypt individual YAML keys without relying on 'parser visible' changes in the YAML file structure.
Instead of marking the desired keys directly in the file, they are listed in the .gitignore file using a `# data: ` comment:
```
# BEGIN ENCRYPTED
kaas-rubik-stage/values.yaml
# type: yamlcompat
# data: splunk.apiToken
# data: splunk.host
kaas-rubik-stage/values2.yaml
# END ENCRYPTED
```
*WARNING* It is recommended to use the normal YAML handler whenever possible. When using the yamlcompat module, you split up your encryption logic over multiple files, which might lead to errors (especially on fragile YAML files that contain unnamed structures - like lists)
<file_sep>FROM python:3.8 AS build-image
RUN curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python
ARG VERSION
COPY . /app
WORKDIR /app
RUN $HOME/.poetry/bin/poetry version $VERSION && \
$HOME/.poetry/bin/poetry build && \
$HOME/.poetry/bin/poetry export -f requirements.txt -o dist/requirements.txt
FROM python:3.8
COPY --from=build-image /app/dist/requirements.txt /tmp
RUN pip install -r /tmp/requirements.txt
COPY --from=build-image /app/dist/*.whl /tmp
RUN pip install /tmp/*.whl
USER 1000
VOLUME ["/repo"]
WORKDIR /repo
ENTRYPOINT ["secrets_tool"]
CMD ["decrypt"]
<file_sep>"""
Classes to encrypt and decrypt YAML files
- Encryption operation will look for fields with the "!decrypted" hint and replace them with an encrypted version of
their content. This will be marked with the "!encrypted" hint
- Decryption operation will look for fields with the "!encrypted" hint and replace them with a decrypted version of
their content. This will be marked with the "!decrypted" hint
"""
from pathlib import Path
from typing import List
import ruamel.yaml
from .. import cipher
class DecryptedString:
yaml_tag = '!decrypted'
def __init__(self, data: str):
self.data = data
@classmethod
def from_encrypted(cls, data: str, key):
return cls(cipher.decrypt(data.encode('ascii'), key).decode('utf8'))
@classmethod
def from_yaml(cls, constructor, node):
return cls(node.value)
@classmethod
def to_yaml(cls, representer, node):
return representer.represent_scalar(cls.yaml_tag, node.data)
class EncryptedString:
yaml_tag = '!encrypted'
def __init__(self, data: str):
self.data = data
@classmethod
def from_decrypted(cls, data: str, key: bytes, iv: bytes):
return cls(cipher.encrypt(data.encode('utf8'), key, iv).decode('ascii'))
@classmethod
def from_yaml(cls, constructor, node):
return cls(node.value)
@classmethod
def to_yaml(cls, representer, node):
return representer.represent_scalar(cls.yaml_tag, node.data)
class YamlFileHandler:
def __init__(self, filepath: Path, data: List[str]):
self.yaml = ruamel.yaml.YAML()
self.yaml.register_class(DecryptedString)
self.yaml.register_class(EncryptedString)
self.filepath = filepath
def dump_decrypted(self, target: Path, key: bytes):
tree = self.yaml.load(self.filepath)
self._walk_item(tree, EncryptedString,
lambda enc_string, iv: DecryptedString.from_encrypted(enc_string.data, key))
self.yaml.dump(tree, target)
def dump_encrypted(self, target: Path, key: bytes):
tree = self.yaml.load(self.filepath)
self._walk_item(tree, DecryptedString,
lambda dec_string, iv: EncryptedString.from_decrypted(dec_string.data, key, iv.encode('utf8')))
self.yaml.dump(tree, target)
def _walk_item(self, item, type_, callback, path=''):
if isinstance(item, dict):
for key in item.keys():
if isinstance(item[key], type_):
item[key] = callback(item[key], path + f'.{key}')
else:
self._walk_item(item[key], type_, callback, path=path + f'.{key}')
elif isinstance(item, list):
for i in range(len(item)):
if isinstance(item[i], type_):
item[i] = callback(item[i], path + f'.{i}')
else:
self._walk_item(item[i], type_, callback, path=path + f'.{i}')
<file_sep>import argparse
import re
from pathlib import Path
from .handlers.generic import GenericFileHandler
from .handlers.yaml import YamlFileHandler
from .handlers.yamlcompat import YamlCompatFileHandler
HANDLERS = {
'yaml': YamlFileHandler,
'yamlcompat': YamlCompatFileHandler,
'generic': GenericFileHandler,
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--filename', default='.gitignore')
parser.add_argument('command', choices=('e', 'encrypt', 'd', 'decrypt'))
args = parser.parse_args()
secrets_file_locations = (
Path('/secrets-tool-key'),
Path(Path.home(), '.secrets-tool-key'),
)
for path in secrets_file_locations:
if path.exists():
key = path.read_bytes().strip()[:32]
break
else:
raise Exception('Could not find file with your secret key.')
gitignore_filepath = Path(args.filename)
base_path = gitignore_filepath.parent
gi_content = gitignore_filepath.read_text('ascii')
gi_content_match = re.search(r'(?s)# BEGIN ENCRYPTED\n(.*)\n# END ENCRYPTED', gi_content)
if gi_content_match is None:
raise Exception("Couldn't find a # BEGIN/END ENCRYPTED section in the provided .gitignore file")
gi_content_match = gi_content_match.group(1)
statement_expr = r'^(?:# type: (?P<type>\w+)\n(?P<data_raw>(?:# data: .+\n)*))?^(?P<filepath>[^#\n].*)$'
for statement in re.finditer(statement_expr, gi_content_match, flags=re.MULTILINE):
data_raw = statement.group('data_raw')
data = [raw.strip() for raw in data_raw.split('# data: ') if len(raw) > 0] if data_raw is not None else None
filepath = base_path / statement.group('filepath')
type_ = statement.group('type')
if type_ is None:
if filepath.suffix in ('.yml', '.yaml'):
type_ = 'yaml'
else:
type_ = 'generic'
handler = HANDLERS[type_]
if args.command in ('e', 'encrypt'):
target_path = Path(str(filepath) + '.enc')
handler(filepath, data).dump_encrypted(target_path, key)
print(f'ENCRYPTED {filepath.resolve()} (into {target_path.resolve()})')
elif args.command in ('d', 'decrypt'):
source_path = Path(str(filepath) + '.enc')
handler(source_path, data).dump_decrypted(filepath, key)
print(f'DECRYPTED {source_path.resolve()} (into {filepath.resolve()})')
if __name__ == '__main__':
main()
| 79aa96fc072d6e215e6a07e704fabdb7954e5a71 | [
"TOML",
"Python",
"Dockerfile",
"Markdown"
]
| 8 | Python | defreng/secrets-tool | a9011a50cdb179c65312e05fe4798f68cb66cac8 | 1327b74bfe442d3095ff9e880e37aeaeb853dd5c |
refs/heads/master | <repo_name>KaSliK/KaSliK.github.io<file_sep>/TenisGame/script.js
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d');
canvas.width = 1000;
canvas.height = 500;
const cw = canvas.width;
const ch = canvas.height;
const ballSize = 20;
let ballX
let ballY
let playerY
let aiY
let ballSpeedX
let ballSpeedY
const paddleHeight = 100;
const paddleWidth = 20
const playerX = 70;
const aiX = cw - 90;
const lineWidth = 6;
const lineHeight = 16;
let level=0
let gameRender = setInterval(game, 1000 / 60);
function startGame() {
document.getElementById('currentLevel').innerHTML
= "Current level: "+(level+1);
setStartState()
gameRender = setInterval(game, 1000 / 60);
}
function nextLevel() {
level++;
startGame();
}
function setStartState() {
clearInterval(gameRender)
playerY = 200;
aiY = 200;
ballSpeedX = 2+level*3;
ballSpeedY = 2+level*3;
ballX = cw / 2 - ballSize / 2;
ballY = ch / 2 - ballSize / 2;
canvas.addEventListener("mousemove", playerPosition)
game()
}
function player() {
ctx.fillStyle = '#7FFF00';
ctx.fillRect(playerX, playerY, paddleWidth, paddleHeight)
}
function ai() {
ctx.fillStyle = 'yellow';
ctx.fillRect(aiX, aiY, paddleWidth, paddleHeight)
}
function ball() {
ctx.fillStyle = '#ffffff';
ctx.fillRect(
ballX,
ballY,
ballSize,
ballSize)
ballX += ballSpeedX;
ballY += ballSpeedY;
if (ballY <= 0 || ballY + ballSize >= ch) {
ballSpeedY = -ballSpeedY
speedUp()
}
if (ballX <= 0) {
alert("Wygrał komputer");
setStartState()
} else if (ballX + ballSize > cw) {
setStartState()
alert("Wygrałeś!!!");
}
if ((ballX <= playerX + paddleWidth) && (ballY + ballSize / 2 >= playerY) && (ballY + ballSize / 2 <= playerY + paddleHeight)) {
ballX += 5;
ballSpeedX = -ballSpeedX;
speedUp();
}
// Odbicia piłki od paletki AI
if ((ballX + ballSize >= aiX) && (ballY + ballSize / 2 >= aiY) && (ballY + ballSize / 2 <= aiY + paddleHeight)) {
ballX -= 5;
ballSpeedX = -ballSpeedX;
speedUp();
}
}
function table() {
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, cw, ch);
for (let linePosition = 20; linePosition < ch; linePosition += 30) {
ctx.fillStyle = 'gray';
ctx.fillRect(cw / 2 - lineWidth / 2, linePosition, lineWidth, lineHeight)
}
}
topCanvas = canvas.offsetTop;
function playerPosition(e) {
playerY = e.clientY - topCanvas - paddleHeight / 2;
if (playerY >= ch - paddleHeight) {
playerY = ch - paddleHeight
} else if (playerY <= 0) {
playerY = 0;
}
}
function speedUp() {
if (ballSpeedX > 0 && ballSpeedX < 16) {
ballSpeedX += .4;
} else if (ballSpeedX < 0 && ballSpeedX > -16) {
ballSpeedX -= .4;
}
if (ballSpeedY > 0 && ballSpeedY < 16) {
ballSpeedY += .3;
} else if (ballSpeedY < 0 && ballSpeedY > -16) {
ballSpeedY -= .3;
}
}
function aiPosition() {
let middlePaddle = aiY + paddleHeight / 2;
let middleBall = ballY + ballSize / 2;
if (ballX > 500) {
if (middlePaddle - middleBall > 200) {
aiY -= 15
} else if (middlePaddle - middleBall > 50) {
aiY -= 5;
} else if (middlePaddle - middleBall < -200) {
aiY += 15
} else if (middlePaddle - middleBall < -50) {
aiY += 5
}
} else if (ballX <= 500 && ballX > 150) {
if (middlePaddle - middleBall > 100) {
aiY -= 3;
} else if (middlePaddle - middleBall < -100) {
aiY += 3;
}
}
}
function game() {
table();
ball();
player();
ai();
aiPosition();
} | 266bb53d3e05a7801e6af72f364739488a5ecc8d | [
"JavaScript"
]
| 1 | JavaScript | KaSliK/KaSliK.github.io | a9fc7373946fc57d1c2e1f9c59835f8a9822318c | 2f818351483c1c305f6ba4de36339c6d20645a50 |
refs/heads/master | <repo_name>sbwtech/sbw_sort<file_sep>/README.md
Sortable Lists
==============

Wrapper for sortable lists, including:
- Comments
- Discussions
- Discussion replies
Allows users to preset their preferred sorting order for the sortable lists.
<file_sep>/start.php
<?php
/**
* Sortable lists
*/
elgg_register_event_handler('init', 'system', function() {
// Handler for getting a list of comments/replies
elgg_register_plugin_hook_handler('route', 'responses', [SBW\Sort\Router::class, 'routeResponses']);
// Hijack the Latest discussions tab
elgg_register_plugin_hook_handler('route', 'groups', [SBW\Sort\Router::class, 'routeGroups']);
});<file_sep>/views/default/resources/discussion/group.php
<?php
/**
* Lists discussions created inside a specific group
*/
$guid = elgg_extract('guid', $vars);
elgg_set_page_owner_guid($guid);
elgg_group_gatekeeper();
$group = get_entity($guid);
if (!elgg_instanceof($group, 'group')) {
forward('', '404');
}
elgg_push_breadcrumb($group->name, $group->getURL());
elgg_push_breadcrumb(elgg_echo('item:object:discussion'));
elgg_register_title_button('discussion', 'add', 'object', 'discussion');
$title = elgg_echo('item:object:discussion');
$options = array(
'type' => 'object',
'subtype' => 'discussion',
'limit' => max(20, elgg_get_config('default_limit')),
'order_by' => 'e.last_action desc',
'container_guid' => $guid,
'full_view' => false,
'no_results' => elgg_echo('discussion:none'),
'preload_owners' => true,
'base_url' => elgg_normalize_url("discussion/group/$group->guid"),
'list_id' => "group-discussion-$group->guid",
'pagination_type' => 'infinite',
);
$content = elgg_view('lists/objects', [
'show_filter' => true,
'show_search' => true,
'show_sort' => true,
'sort_options' => [
'last_action::desc',
'last_action::asc',
'time_created::desc',
'time_created::asc',
'responses_count::desc',
'likes_count::desc',
],
'sort' => get_input('sort', elgg_get_plugin_user_setting('sort_discussions', 0, 'sbw_sort', 'last_action::desc')),
'options' => $options,
]);
if (elgg_is_xhr()) {
echo $content;
return;
}
$params = array(
'content' => $content,
'title' => $title,
'sidebar' => elgg_view('discussion/sidebar'),
'filter' => '',
);
$body = elgg_view_layout('content', $params);
echo elgg_view_page($title, $body);<file_sep>/classes/SBW/Sort/Router.php
<?php
namespace SBW\Sort;
class Router {
/**
* Handler for /responses/list/<guid> route
*
* @param string $hook "route"
* @param string $type "responses"
* @param mixed $return Route
* @param array $params Hook params
* @return mixed
*/
public function routeResponses($hook, $type, $return, $params) {
if (!is_array($return)) {
return;
}
$identifier = elgg_extract('identifier', $return);
$segments = (array) elgg_extract('segments', $return);
if ($identifier !== 'responses') {
return;
}
if ($segments[0] != 'list') {
return;
}
$guid = (int) $segments[1];
elgg_entity_gatekeeper($guid);
echo elgg_view_resource('responses/list', [
'guid' => $guid,
]);
return false;
}
/**
* Handler for /groups/all?filter=discussion
*
* @param string $hook "route"
* @param string $type "groups"
* @param mixed $return Route
* @param array $params Hook params
* @return mixed
*/
public function routeGroups($hook, $type, $return, $params) {
if (!is_array($return)) {
return;
}
$identifier = elgg_extract('identifier', $return);
$segments = (array) elgg_extract('segments', $return);
if ($identifier !== 'groups') {
return;
}
if ($segments[0] != 'all') {
return;
}
if (get_input('filter') !== 'discussion') {
return;
}
echo elgg_view_resource('discussion/all');
return false;
}
}
<file_sep>/views/default/page/elements/comments.php
<?php
/**
* List comments with optional add form
*
* @uses $vars['entity'] ElggEntity
* @uses $vars['show_add_form'] Display add form or not
* @uses $vars['id'] Optional id for the div
* @uses $vars['class'] Optional additional class for the div
* @uses $vars['limit'] Optional limit value (default is 25)
*
* @todo look into restructuring this so we are not calling elgg_list_entities()
* in this view
*/
$entity = elgg_extract('entity', $vars);
$show_add_form = elgg_extract('show_add_form', $vars, true);
$full_view = elgg_extract('full_view', $vars, true);
$limit = elgg_extract('limit', $vars, get_input('limit', 0));
if (!$limit) {
$limit = elgg_trigger_plugin_hook('config', 'comments_per_page', [], 25);
}
$attr = [
'id' => elgg_extract('id', $vars, 'comments'),
'class' => (array) elgg_extract('class', $vars, []),
];
$attr['class'][] = 'elgg-comments';
// work around for deprecation code in elgg_view()
unset($vars['internalid']);
$options = array(
'type' => 'object',
'subtype' => 'comment',
'container_guid' => $entity->guid,
'full_view' => true,
'limit' => $limit,
'preload_owners' => true,
'distinct' => false,
'url_fragment' => $attr['id'],
'base_url' => elgg_normalize_url("responses/list/$entity->guid"),
'list_id' => "comments-$entity->guid",
'pagination_type' => 'infinite',
);
$content = elgg_view('lists/objects', [
'options' => $options,
'show_filter' => true,
'show_sort' => true,
'show_search' => true,
'expand_form' => false,
'sort_options' => [
'time_created::desc',
'time_created::asc',
'likes_count::desc',
],
'sort' => get_input('sort', elgg_get_plugin_user_setting('sort_comments', 0, 'sbw_sort', 'time_created::desc')),
]);
if ($show_add_form) {
$content .= elgg_view_form('comment/save', array(), $vars);
}
echo elgg_format_element('div', $attr, $content);
<file_sep>/views/default/resources/responses/list.php
<?php
$guid = elgg_extract('guid', $vars);
$entity = get_entity($guid);
if (!$entity) {
return;
}
if (!elgg_is_xhr()) {
forward($entity->getURL());
}
if (elgg_instanceof($entity, 'object', 'discussion')) {
echo elgg_view('discussion/replies', [
'topic' => $entity,
'show_add_form' => false,
]);
} else {
echo elgg_view('page/elements/comments', [
'entity' => $entity,
'show_add_form' => false,
]);
}
<file_sep>/languages/en.php
<?php
return [
'sbw_sort:usersettings:title' => 'Sorting',
'sbw:sort:sort_comments' => 'Comments',
'sbw:sort:sort_replies' => 'Discussion replies',
'sbw:sort:sort_discussions' => 'Discussion topics',
];<file_sep>/views/default/resources/discussion/all.php
<?php
elgg_pop_breadcrumb();
elgg_push_breadcrumb(elgg_echo('discussion'));
$options = array(
'type' => 'object',
'subtype' => 'discussion',
'order_by' => 'e.last_action desc',
'limit' => max(20, elgg_get_config('default_limit')),
'full_view' => false,
'no_results' => elgg_echo('discussion:none'),
'preload_owners' => true,
'preload_containers' => true,
'list_id' => 'discussions-all',
'base_url' => elgg_normalize_url('discussion/all'),
'pagination_type' => 'infinite',
);
$content = elgg_view('lists/objects', [
'show_filter' => true,
'show_search' => true,
'show_sort' => true,
'sort_options' => [
'last_action::desc',
'last_action::asc',
'time_created::desc',
'time_created::asc',
'responses_count::desc',
'likes_count::desc',
],
'sort' => get_input('sort', elgg_get_plugin_user_setting('sort_discussions', 0, 'sbw_sort', 'last_action::desc')),
'options' => $options,
]);
if (elgg_is_xhr()) {
echo $content;
return;
}
if (elgg_in_context('groups')) {
if (elgg_get_plugin_setting('limited_groups', 'groups') != 'yes' || elgg_is_admin_logged_in()) {
elgg_register_title_button('groups', 'add', 'group');
}
$filter = elgg_view('groups/group_sort_menu', array('selected' => $selected_tab));
$sidebar = elgg_view('groups/sidebar/find');
$sidebar .= elgg_view('groups/sidebar/featured');
$title = null;
} else {
$title = elgg_echo('discussion:latest');
$sidebar = elgg_view('discussion/sidebar');
$filter = '';
}
$params = array(
'content' => $content,
'title' => $title,
'sidebar' => $sidebar,
'filter' => $filter,
);
$body = elgg_view_layout('content', $params);
echo elgg_view_page($title, $body);
<file_sep>/views/default/plugins/sbw_sort/usersettings.php
<?php
$entity = elgg_extract('entity', $vars);
$user = elgg_get_page_owner_entity();
echo elgg_view_input('select', [
'name' => 'params[sort_comments]',
'value' => elgg_get_plugin_user_setting('sort_comments', $user->guid, $entity->getId(), 'time_created::desc'),
'options_values' => [
'time_created::desc' => elgg_echo('sort:object:time_created::desc'),
'time_created::asc' => elgg_echo('sort:object:time_created::asc'),
'likes_count::desc' => elgg_echo('sort:object:likes_count::desc'),
],
'label' => elgg_echo('sbw:sort:sort_comments'),
]);
echo elgg_view_input('select', [
'name' => 'params[sort_discussions]',
'value' => elgg_get_plugin_user_setting('sort_discussions', $user->guid, $entity->getId(), 'last_action::desc'),
'options_values' => [
'last_action::desc'=> elgg_echo('sort:object:last_action::desc'),
'last_action::asc'=> elgg_echo('sort:object:last_action::asc'),
'time_created::desc' => elgg_echo('sort:object:time_created::desc'),
'time_created::asc' => elgg_echo('sort:object:time_created::asc'),
'responses_count::desc'=> elgg_echo('sort:object:responses_count::desc'),
'likes_count::desc' => elgg_echo('sort:object:likes_count::desc'),
],
'label' => elgg_echo('sbw:sort:sort_discussions'),
]);
echo elgg_view_input('select', [
'name' => 'params[sort_replies]',
'value' => elgg_get_plugin_user_setting('sort_replies', $user->guid, $entity->getId(), 'time_created::desc'),
'options_values' => [
'time_created::desc' => elgg_echo('sort:object:time_created::desc'),
'time_created::asc' => elgg_echo('sort:object:time_created::asc'),
'likes_count::desc' => elgg_echo('sort:object:likes_count::desc'),
],
'label' => elgg_echo('sbw:sort:sort_replies'),
]);
<file_sep>/views/default/discussion/replies.php
<?php
/**
* List replies with optional add form
*
* @uses $vars['entity'] ElggEntity the group discission
* @uses $vars['show_add_form'] Display add form or not
*/
$entity = elgg_extract('topic', $vars);
if (!elgg_instanceof($entity, 'object', 'discussion')) {
elgg_log("discussion/replies view expects \$vars['topic'] to be a discussion object", 'ERROR');
return;
}
$show_add_form = elgg_extract('show_add_form', $vars);
if (!isset($show_add_form)) {
$show_add_form = $entity->canWriteToContainer(0, 'object', 'discussion_reply');
}
$options = array(
'type' => 'object',
'subtype' => 'discussion_reply',
'container_guid' => $entity->guid,
'distinct' => false,
'url_fragment' => 'group-replies',
'base_url' => elgg_normalize_url("responses/list/$entity->guid"),
'list_id' => "discussion-replies-$entity->guid",
'pagination_type' => 'infinite',
);
$replies = elgg_view('lists/objects', [
'options' => $options,
'show_filter' => true,
'show_sort' => true,
'show_search' => true,
'expand_form' => false,
'sort_options' => [
'time_created::desc',
'time_created::asc',
'likes_count::desc',
],
'sort' => get_input('sort', elgg_get_plugin_user_setting('sort_replies', 0, 'sbw_sort', 'time_created::desc')),
]);
if ($show_add_form) {
$form_vars = array('class' => 'mtm');
$replies .= elgg_view_form('discussion/reply/save', $form_vars, $vars);
}
?>
<div id="group-replies" class="elgg-comments">
<?= $replies ?>
</div>
<file_sep>/views/default/resources/discussion/owner.php
<?php
$guid = elgg_extract('guid', $vars);
$target = get_entity($guid);
if ($target instanceof ElggGroup) {
// Before Elgg 2.0 only groups could work as containers for discussions.
// Back then the URL that listed all discussions within a group was
// "discussion/owner/<guid>". Now that any entity can be used as a
// container, we use the standard "<content type>/group/<guid>" URL
// also with discussions.
forward("discussion/group/$guid", '301');
}
elgg_set_page_owner_guid($guid);
elgg_push_breadcrumb(elgg_echo('item:object:discussion'));
elgg_register_title_button('discussion', 'add', 'object', 'discussion');
$title = elgg_echo('item:object:discussion');
$options = array(
'type' => 'object',
'subtype' => 'discussion',
'limit' => max(20, elgg_get_config('default_limit')),
'order_by' => 'e.last_action desc',
'full_view' => false,
'no_results' => elgg_echo('discussion:none'),
'preload_owners' => true,
'base_url' => elgg_normalize_url("discussion/owner/$target->guid"),
'list_id' => "owned-discussion-$target->guid",
'pagination_type' => 'infinite',
);
if ($target instanceof ElggUser) {
// Display all discussions started by the user regardless of
// the entity that is working as a container. See #4878.
$options['owner_guid'] = $guid;
} else {
$options['container_guid'] = $guid;
}
$content = elgg_view('lists/objects', [
'show_filter' => true,
'show_search' => true,
'show_sort' => true,
'sort_options' => [
'last_action::desc',
'last_action::asc',
'time_created::desc',
'time_created::asc',
'responses_count::desc',
'likes_count::desc',
],
'sort' => get_input('sort', elgg_get_plugin_user_setting('sort_discussions', 0, 'sbw_sort', 'last_action::desc')),
'options' => $options,
]);
if (elgg_is_xhr()) {
echo $content;
return;
}
$params = array(
'content' => $content,
'title' => $title,
'sidebar' => elgg_view('discussion/sidebar'),
'filter' => '',
);
$body = elgg_view_layout('content', $params);
echo elgg_view_page($title, $body); | 808fcfb92b71bc5e6ea53d590da0db401125b81c | [
"Markdown",
"PHP"
]
| 11 | Markdown | sbwtech/sbw_sort | 2a48ef1f2c95fae6a962b1db7fc4561b0bef2020 | 2a03cdac319d31ef0421f6e5859a899bd859ae86 |
refs/heads/master | <repo_name>xudailin/xudailin.github.com<file_sep>/README.md
dolphinx.github.com
===================
My web resume
<file_sep>/js/cookie.js
Cookie={
cookie:function(key, value, options){
options = options || {};
//write
if(value!==undefined){
if(typeof options.expires==='number'){
var days=options.expires, t=options.expires=new Date();
t.setDate(t.getDate()+days);
}
return (document.cookie=[
key,'=',value,
options.expires? ';expires='+options.expires.toUTCString() : '',
options.path? ';path='+options.path : '',
options.domain? ';domain='+options.domain : '',
options.secure? ';secure' : ''
].join(''));
}
//read
var cookies=document.cookie? document.cookie.split(';') : [];
for(var i=0; l=cookies.length, i<l;i++){
var parts=cookies[i].split('=');
var name=parts.shift();
if(key===name){
return parts.join('=');
}
}
},
removeCookie:function(key){
if(Cookie.cookie(key)!==undefined){
Cookie.cookie(key,'',{expires:-1});
return true;
}
return false;
}
} | 27cc50e4e62d0412731e31110dc984db5b478709 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | xudailin/xudailin.github.com | bbe2e9c7e1f261a7fadc36545ee484a25af82f6a | 39eba2f9862f467f0b384462d07ab8b0dd36dea7 |
refs/heads/master | <file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class AirBallToggle : MonoBehaviour {
public Toggle aToggle;
public ToggleGroup tg;
public GameObject aBall;
private GameObject lastBall;
Vector3 lastBallPos = Vector3.zero;
private int sumBalls;
public void Awake (){
aBall = GameObject.FindWithTag ("AirBall");
lastBall = new GameObject ();
aBall.SetActive (false);
aToggle = aBall.GetComponent<Toggle> ();
aToggle.interactable = false;
sumBalls = WaterBall.hit + FireBall.hit + LandBall.hit + BowlingBall.hit;
Debug.Log ("Number of hits (AirBall): " + sumBalls.ToString ());
}
public void Start(){
// Unlocking AirBall
if (sumBalls == 3) {
aToggle.interactable = true;
aBall.SetActive (true);
// Treasure Unlocking animation
}
if (aBall.activeSelf) {
aBall.GetComponent<Renderer>().enabled = true;
lastBall = EventSystem.current.lastSelectedGameObject;
lastBallPos = new Vector3 (lastBall.transform.position.x, lastBall.transform.position.y, lastBall.transform.position.z);
aBall.transform.position = lastBallPos;
}
else {
aBall.SetActive(false);
aBall.GetComponent<Renderer>().enabled = false;
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class LandBallToggle : MonoBehaviour {
public Toggle lToggle;
public ToggleGroup tg;
public GameObject lBall;
private GameObject lastBall;
Vector3 lastBallPos = Vector3.zero;
private int sumBalls;
public void Awake (){
lBall = GameObject.FindWithTag ("LandBall");
lastBall = new GameObject ();
lBall.SetActive (false);
lToggle = lBall.GetComponent<Toggle> ();
lToggle.interactable = false;
sumBalls = AirBall.hit + FireBall.hit + WaterBall.hit + BowlingBall.hit;
Debug.Log ("Number of hits (LandBall): " + sumBalls.ToString ());
}
public void Start (){
// Unlocking LandBall
if (sumBalls == 3) {
lToggle.interactable = true;
lBall.SetActive (true);
//Treasure unlocking animation
}
if (lBall.activeSelf) {
lBall.GetComponent<Renderer>().enabled = true;
lastBall = EventSystem.current.lastSelectedGameObject;
lastBallPos = new Vector3 (lastBall.transform.position.x, lastBall.transform.position.y, lastBall.transform.position.z);
lBall.transform.position = lastBallPos;
}
else {
lBall.SetActive(false);
lBall.GetComponent<Renderer>().enabled = false;
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ToggleControl : MonoBehaviour {
public static Toggle bToggle, aToggle, fToggle, lToggle, wToggle;
public static Toggle[] toggles = new Toggle[5]{bToggle, aToggle, fToggle, lToggle, wToggle};
private Toggle[] activeTogs = new Toggle[5];
private Toggle[] interactTogs = new Toggle[5];
private bool interact;
public ToggleGroup tg;
public GameObject bBall, aBall, fBall, lBall, wBall;
private int ballHits;
void Awake () {
tg = GetComponent<ToggleGroup> ();
bToggle = bBall.GetComponent<Toggle> ();
aToggle = aBall.GetComponent<Toggle> ();
aToggle.interactable = false;
fToggle = fBall.GetComponent<Toggle> ();
fToggle.interactable = false;
lToggle = lBall.GetComponent<Toggle> ();
lToggle.interactable = false;
wToggle = wBall.GetComponent<Toggle> ();
wToggle.interactable = false;
ballHits = 0;
}
void Start () {
if (tg.AnyTogglesOn ()) {
activeTogs = FindActiveToggles (toggles); // First glance at any and all toggles are active
interactTogs = FindInteractiveToggles (activeTogs); // find interactable toggles
for (int i = 0; i < interactTogs.Length; i++){
if (interactTogs[i].IsInteractable()){
}
else{
ballHits = BowlingBall.hit + FireBall.hit + LandBall.hit + AirBall.hit + WaterBall.hit;
//checking total hits of specific balls from this and other unity projects
if (ballHits - AirBall.hit == 30)
aToggle.interactable = true;
if (ballHits - FireBall.hit == 30)
fToggle.interactable = true;
if (ballHits - LandBall.hit == 30)
lToggle.interactable = true;
if (ballHits - WaterBall.hit == 30)
wToggle.interactable = true;
}
}
}
}
private Toggle[] FindActiveToggles (Toggle[] t){
Toggle[] tgs = new Toggle[5];
IEnumerable act = tg.ActiveToggles ();
foreach (Toggle tog in act) {
if (tog.IsActive ()) {
for (int i = 0; i < t.Length; i++) {
tgs [i] = tog;
}
}
}
return tgs;
}
private Toggle[] FindInteractiveToggles (Toggle[] at){
Toggle[] interActiveToggles = new Toggle[5];
bool interact = false;
for (int j = 0; j < at.Length; j++) {
interact = at[j].GetComponent<Toggle>().interactable;
if (interact)
interActiveToggles[j] = at[j];
else{
}
}
return interActiveToggles;
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class FireBallToggle : MonoBehaviour {
public Toggle fToggle;
public ToggleGroup tg;
public GameObject fBall;
private GameObject lastBall;
Vector3 lastBallPos = Vector3.zero;
private int sumBalls;
public void Awake (){
fBall = GameObject.FindWithTag ("FireBall");
lastBall = new GameObject ();
fBall.SetActive (false);
fToggle = fBall.GetComponent<Toggle> ();
fToggle.interactable = false;
sumBalls = AirBall.hit + WaterBall.hit + LandBall.hit + BowlingBall.hit;
Debug.Log ("Number of hits (FireBall): " + sumBalls.ToString ());
}
public void Start(){
// Unlocking FireBall
if (sumBalls == 3) {
fToggle.interactable = true;
fBall.SetActive (true);
// Treasure unlocking animation
}
if (fBall.activeSelf) {
fBall.GetComponent<Renderer>().enabled = true;
// this.OnEnable();
lastBall = EventSystem.current.lastSelectedGameObject;
lastBallPos = new Vector3 (lastBall.transform.position.x, lastBall.transform.position.y, lastBall.transform.position.z);
fBall.transform.position = lastBallPos;
}
else {
fBall.SetActive(false);
fBall.GetComponent<Renderer>().enabled = false;
}
}
// public void OnEnable(){
// tg.RegisterToggle (fToggle);
//
// }
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class blueDragonInstantiateScript : MonoBehaviour {
public GameObject bDragon;
Animation bAnim;
// Use this for initialization
void Start () {
GameObject blueD = Instantiate(bDragon, transform.position, transform.rotation) as GameObject;
blueD.transform.localScale = new Vector3(40f, 40f, 40f);
bAnim = blueD.GetComponent<Animation>();
}
// Update is called once per frame
void Update () {
bAnim.Play("fly breath fire");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class redDragonInstantiateSpawn : MonoBehaviour {
public GameObject rDragons;
Animation rAnim;
// Use this for initialization
void Start () {
GameObject redD = Instantiate(rDragons, transform.position, transform.rotation) as GameObject;
redD.transform.localScale = new Vector3(40f, 40f, 40f);
rAnim = redD.GetComponent<Animation>();
}
// Update is called once per frame
void Update () {
rAnim.Play("breath fire");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LavaMonsterScript : MonoBehaviour {
Animator lmAnim;
ParticleSystem psGiantFireBall;
ParticleSystem psBodyFlame;
ParticleSystem psRightArmFlame;
ParticleSystem psLeftArmFlame;
GameObject fireBall;
RaycastHit hit;
GameObject[] lMonsters;
float timeInSecondsOneWay;
Transform lavaMonster1StartPoint;
Transform lavaMonster2StartPoint;
Transform lavaMonster1EndPoint;
Transform lavaMonster2EndPoint;
float speed;
Vector3 targetAngle;
Vector3 currentAngle;
// Use this for initialization
void Start () {
timeInSecondsOneWay = 50f;
speed = 50f;
targetAngle = new Vector3(0f, 180f, 0f);
currentAngle = transform.eulerAngles;
lavaMonster1StartPoint = GameObject.Find("Lava Monster Spawn start").transform;
lavaMonster2StartPoint = GameObject.Find("Lava Monster Spawn 2 start").transform;
lavaMonster1EndPoint = GameObject.Find("Lava Monster Spawn end").transform;
lavaMonster2EndPoint = GameObject.Find("Lava Monster Spawn 2 end").transform;
lMonsters = GameObject.FindGameObjectsWithTag("Lava Monsters");
psGiantFireBall = transform.GetChild(3).GetChild(0).GetChild(0).GetComponent<ParticleSystem>();
psBodyFlame = transform.GetChild(2).GetComponent<ParticleSystem>();
psRightArmFlame = transform.GetChild(0).GetChild(2).GetChild(0).GetChild(4).GetComponent<ParticleSystem>();
psLeftArmFlame = transform.GetChild(0).GetChild(1).GetChild(0).GetChild(4).GetComponent<ParticleSystem>();
fireBall = GameObject.FindGameObjectWithTag("FireBall");
// oneArmFlame();
twoArmFlame();
}
void Update()
{
LavaMonsterPatrol(lMonsters);
if (Physics.Raycast(transform.position, Vector3.forward, out hit, Mathf.Infinity))
{
if (hit.collider.gameObject.tag == "FireBall")
{
Debug.Log("Fire Ball found");
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.white);
transform.LookAt(fireBall.transform);
float distance = hit.distance;
if (distance < 1f)
oneArmFlame();
else
twoArmFlame();
}
}
}
public void LavaMonsterPatrol(GameObject[] lMonsters)
{
for (int i = 0; i < lMonsters.Length; i++)
{
if (i == 0)
{
lMonsters[i].transform.position = Vector3.Lerp(lavaMonster1StartPoint.position, lavaMonster1EndPoint.position, Mathf.SmoothStep(0, 1, Mathf.PingPong(Time.time / timeInSecondsOneWay, 1f)));
if (lavaMonster1StartPoint.position.z - 10f <= lMonsters[i].transform.position.z && lMonsters[i].transform.position.z <= lavaMonster1StartPoint.position.z + 10f)
{
Quaternion a = lMonsters[i].transform.rotation;
Quaternion b = lavaMonster1StartPoint.transform.rotation;
lMonsters[i].transform.rotation = Quaternion.Slerp(a, b, Time.time);
lMonsters[i].transform.LookAt(lavaMonster1EndPoint.transform);
}
if (lMonsters[i].transform.position.z >= lavaMonster1EndPoint.position.z - 10f && lMonsters[i].transform.position.z <= lavaMonster1EndPoint.position.z + 10f)
{
Quaternion a = lMonsters[i].transform.rotation;
Quaternion b = lavaMonster1EndPoint.transform.rotation;
lMonsters[i].transform.rotation = Quaternion.Slerp(a, b, Time.time);
lMonsters[i].transform.LookAt(lavaMonster1StartPoint.transform);
}
}
if (i == 1)
{
lMonsters[i].transform.position = Vector3.Lerp(lavaMonster2StartPoint.position, lavaMonster2EndPoint.position, Mathf.SmoothStep(0, 1, Mathf.PingPong(Time.time / timeInSecondsOneWay, 1f)));
if (lavaMonster2StartPoint.position.x - 10f <= lMonsters[i].transform.position.x && lMonsters[i].transform.position.x <= lavaMonster2StartPoint.position.x + 10f)
{
Quaternion a = lMonsters[i].transform.rotation;
Quaternion b = lavaMonster2StartPoint.transform.rotation;
lMonsters[i].transform.rotation = Quaternion.Slerp(a, b, Time.time);
lMonsters[i].transform.LookAt(lavaMonster2EndPoint.transform);
}
if (lMonsters[i].transform.position.x >= lavaMonster2EndPoint.position.x - 10f && lMonsters[i].transform.position.x <= lavaMonster2EndPoint.position.x + 10f)
{
Quaternion a = lMonsters[i].transform.rotation;
Quaternion b = lavaMonster2EndPoint.transform.rotation;
lMonsters[i].transform.rotation = Quaternion.Slerp(a, b, Time.time);
lMonsters[i].transform.LookAt(lavaMonster2StartPoint.transform);
}
}
if (i == 2)
{
lMonsters[i].transform.position = Vector3.Lerp(lavaMonster1StartPoint.position, lavaMonster1EndPoint.position, Mathf.SmoothStep(0, 1, Mathf.PingPong(Time.time / timeInSecondsOneWay, 1f)));
if (lavaMonster1StartPoint.position.z - 10f <= lMonsters[i].transform.position.z && lMonsters[i].transform.position.z <= lavaMonster1StartPoint.position.z + 10f)
{
Quaternion a = lMonsters[i].transform.rotation;
Quaternion b = lavaMonster1StartPoint.transform.rotation;
lMonsters[i].transform.rotation = Quaternion.Slerp(a, b, Time.time);
lMonsters[i].transform.LookAt(lavaMonster1EndPoint.transform);
}
if (lMonsters[i].transform.position.z >= lavaMonster1EndPoint.position.z - 10f && lMonsters[i].transform.position.z <= lavaMonster1EndPoint.position.z + 10f)
{
Quaternion a = lMonsters[i].transform.rotation;
Quaternion b = lavaMonster1EndPoint.transform.rotation;
lMonsters[i].transform.rotation = Quaternion.Slerp(a, b, Time.time);
lMonsters[i].transform.LookAt(lavaMonster1StartPoint.transform);
}
}
if (i == 3)
{
lMonsters[i].transform.position = Vector3.Lerp(lavaMonster1StartPoint.position, lavaMonster1EndPoint.position, Mathf.SmoothStep(0, 1, Mathf.PingPong(Time.time / timeInSecondsOneWay, 1f)));
if (lavaMonster1StartPoint.position.z - 10f <= lMonsters[i].transform.position.z && lMonsters[i].transform.position.z <= lavaMonster1StartPoint.position.z + 10f)
{
Quaternion a = lMonsters[i].transform.rotation;
Quaternion b = lavaMonster1StartPoint.transform.rotation;
lMonsters[i].transform.rotation = Quaternion.Slerp(a, b, Time.time);
lMonsters[i].transform.LookAt(lavaMonster1EndPoint.transform);
}
if (lMonsters[i].transform.position.z >= lavaMonster1EndPoint.position.z - 10f && lMonsters[i].transform.position.z <= lavaMonster1EndPoint.position.z + 10f)
{
Quaternion a = lMonsters[i].transform.rotation;
Quaternion b = lavaMonster1EndPoint.transform.rotation;
lMonsters[i].transform.rotation = Quaternion.Slerp(a, b, Time.time);
lMonsters[i].transform.LookAt(lavaMonster1StartPoint.transform);
}
}
}
}
public void oneArmFlame()
{
psBodyFlame.Play();
psLeftArmFlame.Play();
lmAnim.SetTrigger("giant fireball");
psGiantFireBall.Play();
}
public void twoArmFlame()
{
psBodyFlame.Play();
psLeftArmFlame.Play();
psRightArmFlame.Play();
lmAnim.SetTrigger("giant fireball");
psGiantFireBall.Play();
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class BallSelector : MonoBehaviour {
public TouchPhase touchPhase;
public Vector2 touch;
public float touch_pos_x_init, touch_pos_y_init, touch_pos_z_init, touch_pos_x_final, touch_pos_y_final, touch_pos_z_final, touch_time_delta, touch_pos_delta_mag, touch_vel_x_delta, touch_vel_z_delta;
public GameObject c;
Vector3 worldPositionsInit, worldPositionsFinal;
public void FixedUpdate (){
if (Input.touchCount == 1) {
foreach (UnityEngine.Touch i in Input.touches) {
touchPhase = i.phase;
touch = i.position;
switch (touchPhase) {
case TouchPhase.Began:
touch_pos_x_init = touch.x;
//xTouchInit = touch_pos_x_init.ToString ();
touch_pos_y_init = touch.y;
//yTouchInit = touch_pos_y_init.ToString ();
touch_pos_z_init = transform.position.z - Camera.main.transform.position.z;
Vector3 touchPos = new Vector3 (touch_pos_x_init, touch_pos_y_init, touch_pos_z_init);
worldPositionsInit = Camera.main.ScreenToWorldPoint (touchPos);
//xTouchInit = touchPos.x.ToString ();
// yTouchInit = touchPos.y.ToString ();
break;
case TouchPhase.Stationary:
EnableCanvas ();
c.transform.Translate(worldPositionsInit);
break;
case TouchPhase.Moved:
//
break;
case TouchPhase.Ended:
touch_pos_x_final = touch.x;
//xTouchInit = touch_pos_x_init.ToString ();
touch_pos_y_final = touch.y;
//yTouchInit = touch_pos_y_init.ToString ();
touch_pos_z_final = transform.position.z - Camera.main.transform.position.z;
Vector3 touchPosfinal = new Vector3 (touch_pos_x_final, touch_pos_y_final, touch_pos_z_final);
worldPositionsFinal = Vector3.zero;
worldPositionsFinal = Camera.main.ScreenToWorldPoint(touchPosfinal);
c.transform.Translate(worldPositionsFinal);
break;
}
}
}
}
void EnableCanvas (){
c.SetActive(true);
//c.transform.Translate (touch_pos_x_init, touch_pos_y_init, 5.0f);
}
void DisableCanvas (){
c.SetActive (false);
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class BowlingBallToggle : MonoBehaviour {
public Toggle bToggle, aToggle, fToggle, lToggle, wToggle;
public ToggleGroup tg;
public GameObject bBall;
GameObject lastBall;
Vector3 lastBallPos = Vector3.zero;
private int sumBalls;
public void Awake (){
bBall = GameObject.FindWithTag ("BowlingBall");
lastBall = EventSystem.current.lastSelectedGameObject;
bBall.SetActive (true);
bToggle = bBall.GetComponent<Toggle> ();
sumBalls = BowlingBall.hit;
}
public void Start(){
if (sumBalls == 3) {
bToggle.interactable = true;
bBall.SetActive (true);
}
if (bBall.activeSelf) {
bBall.GetComponent<Renderer>().enabled = true;
//this.OnEnable();
lastBall = bBall;
lastBallPos = new Vector3 (lastBall.transform.position.x, lastBall.transform.position.y, lastBall.transform.position.z);
bBall.transform.position = lastBallPos;
}
else {
bBall.SetActive(false);
bBall.GetComponent<Renderer>().enabled = false;
}
}
// public void OnEnable(){
// tg.RegisterToggle (bToggle);
//
// }
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class portalscript : MonoBehaviour {
ParticleSystem psPortalStream;
// Use this for initialization
void Start () {
psPortalStream = transform.GetChild(3).GetComponent<ParticleSystem>();
}
void OnTriggerEnter(Collider other)
{
if (other.GetComponent<Collider>().gameObject.layer == 8)
{
if (!psPortalStream.isPlaying)
psPortalStream.Play(true);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VolcanoEruption : MonoBehaviour {
ParticleSystem hotBubbles;
ParticleSystem lavaBurst;
ParticleSystem lavaFlow;
public GameObject volcanoRock;
// Use this for initialization
void Start () {
hotBubbles = transform.GetChild(0).GetComponent<ParticleSystem>();
lavaBurst = transform.GetChild(1).GetComponent<ParticleSystem>();
lavaFlow = transform.GetChild(2).GetComponent<ParticleSystem>();
}
// Update is called once per frame
void Update () {
// if (Time.time % 5 == 0)
// {
erupt();
//}
}
public void erupt()
{
if (!hotBubbles.isPlaying)
hotBubbles.Play();
if (hotBubbles.time == 8.0f)
{
if (!lavaBurst.isPlaying)
lavaBurst.Play();
}
if (lavaBurst.time == 5.0f)
{
if (!lavaFlow.isPlaying)
lavaFlow.Play();
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class WaterBall : MonoBehaviour {
public TouchPhase touchPhase,touchPhase2;
public Vector2 touch, touch1;
public float touch_pos_x_init, touch_pos_y_init, touch_pos_z_init, touch_pos_x_final, touch_pos_y_final, touch_pos_z_final, touch_time_delta, touch_pos_delta_mag, touch_vel_x_delta, touch_vel_z_delta;
public string xTouchInit, yTouchInit;
public float velocityX, velocityZ;
public Vector3 eulerAngleVelocity = new Vector3(0, 100, 0);
//public const float pixel_to_float = 1.0f / 20;
//public GameObject ball;
public GameObject mainC;
public Rigidbody rwball;
public Text speedXValue, speedZValue, upTime;
//private GameObject guiTextXGO, guiTextZGO;
private float speedMax;
private float speedX = 15.0f, speedZ = 15.0f;
private float xAngle, yAngle, zAngle;
Vector3 worldPositionsInit, worldPositionsFinal;
public static int hit;
public Text hitScore;
void Start () {
hit = 0;
hitScore.text = "0";
speedMax = 1000.0f;
Screen.orientation = ScreenOrientation.LandscapeLeft;
//guiTextXGO = GameObject.FindGameObjectWithTag("SpeedX");
//guiTextZGO = GameObject.FindGameObjectWithTag("SpeedZ");
//speedXText = guiTextXGO.GetComponent<GUIText>();
//speedZText = guiTextZGO.GetComponent<GUIText>();
//speedX.ToString ("0.0");
//speedZ.ToString ("0.0");
speedXValue.text = speedX.ToString();
speedZValue.text = speedZ.ToString();
mainC = GameObject.FindWithTag("MainCamera");
//rbball = new Rigidbody ();
rwball = GetComponent<Rigidbody> ();
// tg.RegisterToggle (bball);
}
void Update(){
if (Input.touchCount == 1) {
foreach (UnityEngine.Touch i in Input.touches) {
touchPhase = i.phase;
touch = i.position;
switch (touchPhase) {
case TouchPhase.Began:
touch_pos_x_init = touch.x;
//xTouchInit = touch_pos_x_init.ToString ();
touch_pos_y_init = touch.y;
//yTouchInit = touch_pos_y_init.ToString ();
touch_pos_z_init = transform.position.z - Camera.main.transform.position.z;
Vector3 touchPos = new Vector3 (touch_pos_x_init, touch_pos_y_init, touch_pos_z_init);
worldPositionsInit = Camera.main.ScreenToWorldPoint (touchPos);
xTouchInit = touchPos.x.ToString ();
yTouchInit = touchPos.y.ToString ();
break;
case TouchPhase.Stationary:
break;
case TouchPhase.Moved:
touch_pos_delta_mag = i.deltaPosition.magnitude;
touch_time_delta = i.deltaTime;
// if (i.deltaPosition.x > 0)
// touch_pos_x_delta = -touch_pos_x_delta;
//
// if (i.deltaPosition.y < 0)
// touch_pos_y_delta = -touch_pos_y_delta;
touch_vel_x_delta = touch_pos_delta_mag / touch_time_delta;
touch_vel_z_delta = touch_pos_delta_mag / touch_time_delta;
// rbball.guiText.text = "Speed X: " + speedX.ToString ();
// rbball.guiText.text = "Speed Z: " + speedZ.ToString ();
break;
case TouchPhase.Ended:
touch_pos_x_final = touch.x;
//xTouchInit = touch_pos_x_init.ToString ();
touch_pos_y_final = touch.y;
//yTouchInit = touch_pos_y_init.ToString ();
touch_pos_z_final = transform.position.z - Camera.main.transform.position.z;
Vector3 touchPosfinal = new Vector3 (touch_pos_x_final, touch_pos_y_final, touch_pos_z_final);
worldPositionsFinal = Vector3.zero;
worldPositionsFinal = Camera.main.ScreenToWorldPoint(touchPosfinal);
Debug.Log ("SpeedX(With Touch): " + speedXValue.text + " " + "SpeedZ(With Touch): " + speedZValue.text);
break;
}
}
}
Debug.Log ("SpeedX(No Touch): " + speedXValue.text + " " + "SpeedZ(No Touch): " + speedZValue.text);
transform.Translate (-Input.acceleration.x, 0.0f, Input.acceleration.z, Space.World);
speedX = -Input.acceleration.x + worldPositionsFinal.x;
speedZ = Input.acceleration.z + worldPositionsFinal.z;
speedXValue.text = speedX.ToString();
speedZValue.text = speedZ.ToString ();
// rbball.useGravity = true;
xAngle = Vector3.right.x * Time.deltaTime;
yAngle = 0.0f;
zAngle = Vector3.up.z * Time.deltaTime;
transform.Rotate (xAngle, yAngle, zAngle, Space.Self);
}
void OnCollisionEnter (Collision collision){
if (collision.gameObject.tag != null) {
string pinTag = collision.gameObject.tag;
switch (pinTag.ToString ()) {
case "Pin1":
hit++;
break;
case "Pin2":
hit++;
break;
case "Pin3":
hit++;
break;
case "Pin4":
hit++;
break;
case "Pin5":
hit++;
break;
case "Pin6":
hit++;
break;
case "Pin7":
hit++;
break;
case "Pin8":
hit++;
break;
case "Pin9":
hit++;
break;
case "Pin10":
hit++;
break;
}
hitScore.text = hit.ToString ();
}
}
void OnCollisionExit (Collision collision){
if (collision.gameObject.tag != null) {
string pinTag = collision.gameObject.tag;
switch (pinTag) {
case "Pin1":
break;
case "Pin2":
break;
case "Pin3":
break;
case "Pin4":
break;
case "Pin5":
break;
case "Pin6":
break;
case "Pin7":
break;
case "Pin8":
break;
case "Pin9":
break;
case "Pin10":
break;
}
}
}
void OnGUI(){
}
//
// void onClick (){
// DisableCanvas ();
// }
void FixedUpdate (){
//assuming portrait mode and home button is to the right
Debug.Log ("SpeedX(No Touch): " + speedXValue.text + " " + "SpeedZ(No Touch): " + speedZValue.text);
transform.Translate (-Input.acceleration.x, 0.0f, Input.acceleration.z, Space.World);
speedX = -Input.acceleration.x + worldPositionsFinal.x;
speedZ = Input.acceleration.z + worldPositionsFinal.z;
speedXValue.text = speedX.ToString();
speedZValue.text = speedZ.ToString ();
// rbball.useGravity = true;
xAngle = Vector3.right.x * Time.deltaTime;
yAngle = 0.0f;
zAngle = Vector3.up.z * Time.deltaTime;
transform.Rotate (xAngle, yAngle, zAngle, Space.Self);
if (rwball.IsSleeping ()) {
rwball.WakeUp();
Vector3 movement = new Vector3 (-(worldPositionsFinal.x - worldPositionsInit.x),0.0f, (worldPositionsFinal.y - worldPositionsInit.y));
rwball.AddForce(movement * 150.0f);
rwball.useGravity = true;
xAngle = Vector3.right.x * Time.deltaTime;
yAngle = 0.0f;
zAngle = Vector3.up.z * Time.deltaTime;
transform.Rotate (xAngle, yAngle, zAngle, Space.Self);
if (speedX >= (0.9f * speedMax) || speedZ >= (0.9f * speedMax)){
// Apply special effects for bowling ball here, i.e. sparks.
//Vector3 sbEmitVel = new Vector3(2.5f, 2.5f, 2.5f);
//ParticleEmitter staticBall = GetComponent<ParticleEmitter>();
//staticBall.Emit(rwball.position, sbEmitVel, 0.2f, 15f, Color.cyan);
if (Input.acceleration.y > 0.0f){
// Apply explosionEffects on rigidbody bowling ball
float timePowerUp = 15.0f;
// Display time of power up on GUI decreasing
while (timePowerUp > 0.0f){
//Vector3 warpPos = new Vector3(rbball.position.x + 1.0f, 0.0f, rbball.position.z + 1.0f)
rwball.MovePosition(Vector3.forward);
upTime.text = timePowerUp.ToString();
//staticBall.Emit(rwball.position, sbEmitVel, 0.2f, timePowerUp, Color.cyan);
timePowerUp--;
}
}
}
} else {
rwball.Sleep();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class lava_script : MonoBehaviour {
public Texture[] textures;
public Renderer rend;
float offset;
float scrollSpeed;
// Use this for initialization
void Start () {
rend = GetComponent<Renderer>();
scrollSpeed = 0.5f;
rend.material.mainTexture = textures[0];
}
// Update is called once per frame
void Update () {
offset += (Time.deltaTime * scrollSpeed) / 10.0f;
rend.material.SetTextureOffset("_MainTex", new Vector2(offset, 0));
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
public class FireBall : MonoBehaviour {
TouchPhase touchPhase,touchPhase2;
Vector2 touch, touch1;
float touch_pos_x_init;
float touch_pos_y_init;
float touch_pos_z_init;
float touch_pos_x_final;
float touch_pos_y_final;
float touch_pos_z_final;
float touch_time_delta;
float touch_pos_delta_x;
float touch_pos_delta_z;
float touch_vel_x_delta;
float touch_vel_z_delta;
string xTouchInit, yTouchInit;
float velocityX, velocityZ;
Vector3 worldPositionsInit;
Vector3 eulerAngleVelocity = new Vector3(0, 100, 0);
public GameObject mainC;
public Rigidbody rfball;
public Text speedXValue, speedZValue, upTime;
private float speedMax;
private float speedX = 15.0f, speedZ = 15.0f;
private float xAngle, yAngle, zAngle;
public static int hit;
public Text hitScore;
Slider speedometerSlider;
ParticleSystem psFlames;
private float speed;
void Start () {
hit = 0;
hitScore.text = "0";
Screen.orientation = ScreenOrientation.LandscapeLeft;
speedXValue.text = speedX.ToString();
speedZValue.text = speedZ.ToString();
mainC = GameObject.FindWithTag("MainCamera");
rfball = GetComponent<Rigidbody> ();
speedometerSlider = GameObject.Find("Canvas").transform.GetChild(0).GetChild(2).gameObject.GetComponent<Slider>();
// speedometerImage.fillAmount = 0f;
psFlames = GetComponent<ParticleSystem>();
speed = 2.0f;
}
void Update(){
if (Input.touchCount == 1) {
foreach (UnityEngine.Touch i in Input.touches) {
touchPhase = i.phase;
touch = i.position;
switch (touchPhase) {
case TouchPhase.Began:
touch_pos_x_init = touch.x;
touch_pos_y_init = touch.y;
touch_pos_z_init = transform.position.z - Camera.main.transform.position.z;
Vector3 touchPos = new Vector3 (touch_pos_x_init, touch_pos_y_init, touch_pos_z_init);
worldPositionsInit = Camera.main.ScreenToWorldPoint (touchPos);
xTouchInit = touchPos.x.ToString ();
yTouchInit = touchPos.y.ToString ();
break;
case TouchPhase.Stationary:
break;
case TouchPhase.Moved:
touch_pos_delta_x = i.deltaPosition.x;
touch_pos_delta_z = i.deltaPosition.y;
touch_time_delta = i.deltaTime;
touch_vel_x_delta = touch_pos_delta_x / touch_time_delta;
touch_vel_z_delta = touch_pos_delta_x / touch_time_delta;
break;
case TouchPhase.Ended:
touch_pos_x_final = touch.x;
//xTouchInit = touch_pos_x_init.ToString ();
touch_pos_y_final = touch.y;
//yTouchInit = touch_pos_y_init.ToString ();
touch_pos_z_final = transform.position.z - Camera.main.transform.position.z;
Vector3 touchPosfinal = new Vector3 (touch_pos_x_final, touch_pos_y_final, touch_pos_z_final);
// touch_vel_x_delta = Vector3.zero;
// touch_vel_x_delta = Camera.main.ScreenToWorldPoint(touchPosfinal);
Debug.Log ("SpeedX(With Touch): " + speedXValue.text + " " + "SpeedZ(With Touch): " + speedZValue.text);
break;
}
}
}
speedX = Input.acceleration.z;
Debug.Log("SpeedX: " + speedX);
speedZ = Input.acceleration.x;
Debug.Log("SpeedZ: " + speedZ);
float maxTouchDelta = 100f;
float touchFractionX = touch_vel_x_delta / maxTouchDelta;
float touchFractionZ = touch_vel_z_delta / maxTouchDelta;
Debug.Log("touch Fraction X: " + touchFractionX);
Debug.Log("touch Fraction Z: " + touchFractionZ);
speedX += touchFractionX;
speedZ += touchFractionZ;
Debug.Log("Speed X: " + speedX);
Debug.Log("Speed Z: " + speedZ);
transform.Translate(speedX, 0f, speedZ);
transform.Rotate(0, 0, 20f * Time.deltaTime);
Speedometer(speedX, speedZ);
}
void OnCollisionEnter (Collision collision){
if (collision.gameObject.tag != null) {
string pinTag = collision.gameObject.tag;
switch (pinTag.ToString ()) {
case "Pin1":
hit++;
break;
case "Pin2":
hit++;
break;
case "Pin3":
hit++;
break;
case "Pin4":
hit++;
break;
case "Pin5":
hit++;
break;
case "Pin6":
hit++;
break;
case "Pin7":
hit++;
break;
case "Pin8":
hit++;
break;
case "Pin9":
hit++;
break;
case "Pin10":
hit++;
break;
}
hitScore.text = hit.ToString ();
}
}
void OnCollisionExit (Collision collision){
if (collision.gameObject.tag != null) {
string pinTag = collision.gameObject.tag;
switch (pinTag) {
case "Pin1":
break;
case "Pin2":
break;
case "Pin3":
break;
case "Pin4":
break;
case "Pin5":
break;
case "Pin6":
break;
case "Pin7":
break;
case "Pin8":
break;
case "Pin9":
break;
case "Pin10":
break;
}
}
}
void FixedUpdate (){
//assuming portrait mode and home button is to the right
Debug.Log ("SpeedX(No Touch): " + speedXValue.text + " " + "SpeedZ(No Touch): " + speedZValue.text);
// rbball.useGravity = true;
xAngle = Vector3.right.x * Time.deltaTime;
yAngle = 0.0f;
zAngle = Vector3.up.z * Time.deltaTime;
transform.Rotate (xAngle, yAngle, zAngle, Space.Self);
if (rfball.IsSleeping ()) {
rfball.WakeUp();
// Vector3 movement = new Vector3 (-(touch_vel_x_delta.x - worldPositionsInit.x),0.0f, (touch_vel_x_delta.y - worldPositionsInit.y));
//rfball.AddForce(movement * 150.0f);
rfball.useGravity = true;
xAngle = Vector3.right.x * Time.deltaTime;
yAngle = 0.0f;
zAngle = Vector3.up.z * Time.deltaTime;
transform.Rotate (xAngle, yAngle, zAngle, Space.Self);
if (speedX >= (0.9f * speedMax) || speedZ >= (0.9f * speedMax)){
// Apply special effects for bowling ball here, i.e. sparks.
//Vector3 sbEmitVel = new Vector3(2.5f, 2.5f, 2.5f);
//ParticleEmitter staticBall = GetComponent<ParticleEmitter>();
//staticBall.Emit(rfball.position, sbEmitVel, 0.2f, 15f, Color.cyan);
if (Input.acceleration.y > 0.0f){
// Apply explosionEffects on rigidbody bowling ball
float timePowerUp = 15.0f;
// Display time of power up on GUI decreasing
while (timePowerUp > 0.0f){
//Vector3 warpPos = new Vector3(rbball.position.x + 1.0f, 0.0f, rbball.position.z + 1.0f)
rfball.MovePosition(Vector3.forward);
upTime.text = timePowerUp.ToString();
//staticBall.Emit(rfball.position, sbEmitVel, 0.2f, timePowerUp, Color.cyan);
timePowerUp--;
}
}
}
} else {
rfball.Sleep();
}
}
public void Speedometer(float speedX, float speedZ)
{
float averageSpeed = 0.5f * (speedX + speedZ);
float maxSpeed = 250.0f;
float speedPercent = Mathf.Abs(averageSpeed / maxSpeed) * 100f;
Debug.Log("The speed ratio is: " + speedPercent);
if (speedPercent > 0f && speedPercent <= 0.1f)
{
speedometerSlider.value = speedPercent;
}
else if (speedPercent > 0.1f && speedPercent <= 0.2f)
{
speedometerSlider.value = speedPercent;
}
else if (speedPercent > 0.2f && speedPercent <= 0.3f)
{
speedometerSlider.value = speedPercent;
}
else if (speedPercent > 0.3f && speedPercent <= 0.4f)
{
speedometerSlider.value = speedPercent;
}
else if (speedPercent > 0.4f && speedPercent <= 0.5f)
{
speedometerSlider.value = speedPercent;
}
else if (speedPercent > 0.5f && speedPercent <= 0.6f)
{
speedometerSlider.value = speedPercent;
}
else if (speedPercent > 0.6f && speedPercent <= 0.7f)
{
speedometerSlider.value = speedPercent;
}
else if (speedPercent > 0.7f && speedPercent <= 0.8f)
{
speedometerSlider.value = speedPercent;
}
else if (speedPercent > 0.8f && speedPercent <= 0.9f)
{
speedometerSlider.value = speedPercent;
if (!psFlames.isPlaying)
psFlames.Play();
}
else if (speedPercent > 0.9f && speedPercent <= 1.0f)
{
speedometerSlider.value = speedPercent;
if (!psFlames.isPlaying)
psFlames.Play();
}
else
{
speedometerSlider.value = 1.0f;
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class fireBurnScript : MonoBehaviour {
int playerLife;
GameObject myCanvas;
ParticleSystem fireFlame;
List<ParticleCollisionEvent> pceFire;
// Use this for initialization
void Start () {
myCanvas = GameObject.Find("Canvas").gameObject;
fireFlame = GameObject.Find("Fire Flame").gameObject.GetComponent<ParticleSystem>();
pceFire = new List<ParticleCollisionEvent>();
}
void OnParticleCollision(GameObject gameObject)
{
ParticlePhysicsExtensions.GetCollisionEvents(GetComponent<ParticleSystem>(), gameObject, pceFire);
for (int i = 0; i < pceFire.Count; i++)
{
if (pceFire[i].colliderComponent.GetComponent<Collider>().gameObject.layer == 8)
{
if (!fireFlame.isPlaying)
{
Vector3 fireImpactPoint = pceFire[i].intersection;
fireFlame.transform.position = fireImpactPoint;
fireFlame.Play(true);
if (fireFlame.isPlaying)
fireDamage();
}
}
}
}
public void fireDamage()
{
int result;
if (int.TryParse(myCanvas.transform.GetChild(1).GetChild(1).gameObject.GetComponent<Text>().text, out result))
{
Debug.Log("The life count: " + result);
playerLife = result;
playerLife -= 2;
myCanvas.transform.GetChild(1).GetChild(1).gameObject.GetComponent<Text>().text = playerLife.ToString();
}
}
}
<file_sep># Bowling-Universe
Free Roaming Bowling game that is not limited to the bowling alley
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CameraMovement : MonoBehaviour {
public GameObject bBall;
private Vector3 bBallOffset;
public GameObject lBall;
private Vector3 lBallOffset;
public GameObject wBall;
private Vector3 wBallOffset;
public GameObject fBall;
private Vector3 fBallOffset;
public GameObject aBall;
private Vector3 aBallOffset;
public GameObject BallSelector;
ToggleGroup bToggleGroup;
// Use this for initialization
void Start () {
bBallOffset = transform.position - bBall.transform.position;
aBallOffset = transform.position - aBall.transform.position;
lBallOffset = transform.position - lBall.transform.position;
fBallOffset = transform.position - fBall.transform.position;
wBallOffset = transform.position - wBall.transform.position;
bToggleGroup = BallSelector.GetComponent<ToggleGroup>();
}
// Update is called once per frame
void LateUpdate () {
IEnumerable<Toggle> aToggles = bToggleGroup.ActiveToggles();
IEnumerator<Toggle> togEnumerator = aToggles.GetEnumerator();
while (togEnumerator.MoveNext())
{
if (togEnumerator.Current.isOn)
{
if(togEnumerator.Current.name.Equals("Land Ball Toggle"))
transform.position = lBall.transform.position + lBallOffset;
else if (togEnumerator.Current.name.Equals("Water Ball Toggle"))
transform.position = wBall.transform.position + wBallOffset;
else if (togEnumerator.Current.name.Equals("Fire Ball Toggle"))
transform.position = fBall.transform.position + fBallOffset;
else if (togEnumerator.Current.name.Equals("Air Ball Toggle"))
transform.position = aBall.transform.position + aBallOffset;
else
transform.position = bBall.transform.position + bBallOffset;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class icefreezescript : MonoBehaviour {
int playerLife;
GameObject myCanvas;
ParticleSystem iceBlock;
List<ParticleCollisionEvent> pceIce;
// Use this for initialization
void Start () {
myCanvas = GameObject.Find("Canvas").gameObject;
iceBlock = GameObject.Find("Ice Smoke").gameObject.GetComponent<ParticleSystem>();
pceIce = new List<ParticleCollisionEvent>();
}
void OnParticleCollision (GameObject gameObject) {
ParticlePhysicsExtensions.GetCollisionEvents(GetComponent<ParticleSystem>(), gameObject, pceIce);
for (int i = 0; i < pceIce.Count; i++)
{
if(pceIce[i].colliderComponent.GetComponent<Collider>().gameObject.layer == 8)
{
if (!iceBlock.isPlaying)
{
Vector3 iceImpactPoint = pceIce[i].intersection;
iceBlock.transform.position = iceImpactPoint;
iceBlock.Play(true);
if (iceBlock.isPlaying)
iceDamage();
}
}
}
}
public void iceDamage()
{
int result;
if (int.TryParse(myCanvas.transform.GetChild(1).GetChild(1).gameObject.GetComponent<Text>().text, out result))
{
Debug.Log("The life count: " + result);
playerLife = result;
playerLife -= 1;
myCanvas.transform.GetChild(1).GetChild(1).gameObject.GetComponent<Text>().text = playerLife.ToString();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LavaMonsterSpawn : MonoBehaviour {
public GameObject lavaMonster;
GameObject[] lMonsters;
Transform spawnPt2;
Transform cave3;
Transform cave6;
// Use this for initialization
void Start () {
lMonsters = new GameObject[4];
spawnPt2 = GameObject.Find("Lava Monster Spawn 2 start").transform;
cave3 = GameObject.Find("Terrains").transform.GetChild(2).GetChild(2).transform;
cave6 = GameObject.Find("Terrains").transform.GetChild(3).GetChild(5).transform;
for (int i = 0; i < lMonsters.Length; i++)
{
GameObject lMonster = Instantiate(lavaMonster) as GameObject;
lMonster.transform.localScale = new Vector3(20f, 20f, 20f);
lMonsters[i] = lMonster;
}
lMonsters[0].name = "Lava Monster 1";
lMonsters[0].tag = "Lava Monsters";
lMonsters[0].transform.position = transform.position;
lMonsters[0].transform.rotation = transform.rotation;
lMonsters[1].name = "Lava Monster 2";
lMonsters[1].tag = "Lava Monsters";
lMonsters[1].transform.position = spawnPt2.position;
lMonsters[1].transform.rotation = spawnPt2.rotation;
lMonsters[2].name = "Lava Monster 3";
lMonsters[2].tag = "Lava Monsters";
lMonsters[2].transform.position = cave3.position;
lMonsters[3].name = "Lava Monster 4";
lMonsters[3].tag = "Lava Monsters";
lMonsters[3].transform.position = cave6.position;
}
// Update is called once per frame
void Update () {
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using com.shephertz.app42.paas.sdk.csharp;
using com.shephertz.app42.paas.sdk.csharp.game;
using UnityEngine.UI;
using System.Globalization;
using System;
public class teleportationPSscript : MonoBehaviour {
List<ParticleCollisionEvent> collisionEvents;
ParticleSystem psPortal;
bool success;
double result;
string bowling_pins_count_text;
string[] scenes;
string apiKey;
string secretKey;
// Use this for initialization
void Start() {
psPortal = GetComponent<ParticleSystem>();
collisionEvents = new List<ParticleCollisionEvent>();
success = false;
scenes = new string[] { "UnderWater_Level_1_Easy", "UnderWater_FireBall_Stage" };
apiKey = "<KEY>";
secretKey = "db3e2306c389a1cd31c21a6d4c57c66da372af47b8a1dd360147c0f31e03cf28";
getGame("BowlingUniverse", "Bowling adventure game");
}
private void getGame(string gameName, string description)
{
App42Log.SetDebug(true);
App42API.Initialize(apiKey, secretKey);
GameService gameService = App42API.BuildGameService();
gameService.GetGameByName(gameName, new UnityGetGameCallBack());
}
private void OnParticleCollision(GameObject collider)
{
int numCollisionEvents = psPortal.GetCollisionEvents(collider, collisionEvents);
for (int i = 0; i < numCollisionEvents; i++)
{
Component colliderGO = collisionEvents[i].colliderComponent;
Collider colliderBall = colliderGO.GetComponent<Collider>();
string sceneName = "";
if (colliderBall.transform.name == "Bowling Ball Reg")
{
string ballID = "Gravity Ball";
bowling_pins_count_text = GameObject.Find("Canvas").transform.GetChild(1).GetChild(3).GetComponent<Text>().text;
if (double.TryParse(bowling_pins_count_text, out result))
{
sceneName = GetSceneName();
if (DataCloudSaved(ballID, result, sceneName))
{
Debug.Log(ballID + " data has been saved to cloud!!!");
}
else
{
Debug.Log(ballID + " data has not been saved to cloud!!!");
}
}
Debug.Log("Scanning ... " + "Ball Identified ... " + ballID);
}
else if (colliderBall.transform.name == "Land Ball")
{
string ballID = "<NAME> Ball";
bowling_pins_count_text = GameObject.Find("Canvas").transform.GetChild(1).GetChild(3).GetComponent<Text>().text;
if (double.TryParse(bowling_pins_count_text, out result))
{
sceneName = GetSceneName();
if (DataCloudSaved(ballID, result, sceneName))
{
Debug.Log(ballID + " data has been saved to cloud!!!");
}
else
{
Debug.Log(ballID + " data has not been saved to cloud!!!");
}
}
Debug.Log("Scanning ... " + "Ball Identified ... " + ballID);
}
else if (colliderBall.transform.name == "Fire Ball")
{
string ballID = "<NAME>";
bowling_pins_count_text = GameObject.Find("Canvas").transform.GetChild(1).GetChild(3).GetComponent<Text>().text;
if (double.TryParse(bowling_pins_count_text, out result))
{
sceneName = GetSceneName();
if (DataCloudSaved(ballID, result, sceneName))
{
Debug.Log(ballID + " data has been saved to cloud!!!");
}
else
{
Debug.Log(ballID + " data has not been saved to cloud!!!");
}
}
Debug.Log("Scanning ... " + "Ball Identified ... " + ballID);
loadNewStage(colliderBall.gameObject, scenes[1]);
}
else if (colliderBall.transform.name == "Air Ball")
{
string ballID = "Sky Ball";
bowling_pins_count_text = GameObject.Find("Canvas").transform.GetChild(1).GetChild(3).GetComponent<Text>().text;
if (double.TryParse(bowling_pins_count_text, out result))
{
sceneName = GetSceneName();
if (DataCloudSaved(ballID, result, sceneName))
{
Debug.Log(ballID + " data has been saved to cloud!!!");
}
else
{
Debug.Log(ballID + " data has not been saved to cloud!!!");
}
}
Debug.Log("Scanning ... " + "Ball Identified ... " + ballID);
}
else if (colliderBall.transform.name == "Water Ball")
{
string ballID = "<NAME>";
bowling_pins_count_text = GameObject.Find("Canvas").transform.GetChild(1).GetChild(3).GetComponent<Text>().text;
if (double.TryParse(bowling_pins_count_text, out result))
{
sceneName = GetSceneName();
if (DataCloudSaved(ballID, result, sceneName))
{
Debug.Log(ballID + " data has been saved to cloud!!!");
}
else
{
Debug.Log(ballID + " data has not been saved to cloud!!!");
}
}
Debug.Log("Scanning ... " + "Ball Identified ... " + ballID);
}
else
Debug.Log("Scanning ... " + "Ball Not Identified ... ");
}
}
private void loadNewStage(GameObject ball, string scene)
{
SceneManager.LoadScene(scene, LoadSceneMode.Single);
SceneManager.MoveGameObjectToScene(ball.gameObject, SceneManager.GetSceneByName(scene));
// DontDestroyOnLoad(ball.gameObject);
// Transform fireSpotLanding = GameObject.Find("FireBall Stage UnderWater Portal").transform.GetChild(4).transform;
ball.transform.position = new Vector3(455.85f, 119.99f, 98.94f);
}
private bool DataCloudSaved(string ballID, double result, string sceneName)
{
bool success = false;
string gameName = "BowlingUniverse";
string scene = sceneName;
double pins = result;
// Calls to save data to cloud (APPHQ)
App42Log.SetDebug(true);
App42API.Initialize(apiKey, secretKey);
ScoreBoardService scoreBoardService = App42API.BuildScoreBoardService();
scoreBoardService.SaveUserScore(gameName, scene, pins, new UnitySaveCallBack());
success = true;
return success;
}
public string GetSceneName()
{
Scene current_scene;
string scene = "";
current_scene = SceneManager.GetActiveScene();
scene = current_scene.name;
return scene;
}
public class UnityGetGameCallBack : App42CallBack
{
void App42CallBack.OnSuccess(object response)
{
Game game = (Game)response;
App42Log.Console("gameName is " + game.GetName());
}
void App42CallBack.OnException(Exception e)
{
App42Log.Console("Exception : " + e);
}
}
public class UnitySaveCallBack : App42CallBack
{
public void OnSuccess(object response)
{
Game game = (Game)response;
App42Log.Console("gameName is " + game.GetName());
for (int i = 0; i < game.GetScoreList().Count; i++)
{
App42Log.Console("userName is : " + game.GetScoreList()[i].GetUserName());
App42Log.Console("score is : " + game.GetScoreList()[i].GetValue());
App42Log.Console("scoreId is : " + game.GetScoreList()[i].GetScoreId());
}
}
public void OnException(System.Exception e)
{
App42Log.Console("Exception : " + e);
}
}
}
| c54d19901902a9260667b7303c5b800de214bbe4 | [
"Markdown",
"C#"
]
| 20 | C# | IrfanZ0/Bowling-Universe | f9530062f6ca981472c6759bbce3b7768da44edc | 7e0de6e76031547e56573121d69ba5fc073aee64 |
refs/heads/master | <file_sep>package crawler;
import com.google.common.base.Joiner;
import javax.persistence.AttributeConverter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListStringConverter implements AttributeConverter<List<String>, String> {
@Override
public String convertToDatabaseColumn(List<String> listStr) {
if (listStr == null || listStr.isEmpty()) return null ;
return Joiner.on(",")
.skipNulls()
.join(listStr);
}
@Override
public List<String> convertToEntityAttribute(String dbData) {
if ( dbData == null )
return new ArrayList<>() ;
String[] sizesInShort = dbData.split(",") ;
return Arrays.asList(sizesInShort) ;
}
}
<file_sep>package crawler.mat.crawling;
import crawler.GenericProduct;
import crawler.mat.repository.DailyProductDao;
import crawler.mat.repository.ProductDao;
import crawler.mat.model.DailyProduct;
import crawler.mat.model.Product;
import crawler.mat.page.BrandListPage;
import crawler.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class MatCrawling {
@Autowired
ProductDao productDao ;
@Autowired
DailyProductDao dailyProductDao ;
@Autowired
Analysis analysis ;
@Autowired
CrawingProducts crawingProducts ;
@Autowired
CrawingBrands crawingBrands ;
/**
* store/load data from db
*
* @throws Exception
*/
public void run() throws Exception {
// load last crawled products
List<Product> lastProducts = productDao.loadAll() ;
// crawling
BrandListPage brands = crawingBrands.crawle() ;
crawingProducts.crawle(brands) ;
List<Product> products = crawingProducts.getCrawledProducts() ;
if (!lastProducts.isEmpty()) {
// analysis
List<GenericProduct> soldoutProducts = analysis.analyze(products, lastProducts) ;
for ( GenericProduct genericProduct : soldoutProducts) {
products.add((Product)genericProduct) ;
}
}
productDao.save(products);
dailyProductDao.save(makeDailyProductFromProduct(products));
}
public List<DailyProduct> makeDailyProductFromProduct(List<Product> products) {
List<DailyProduct> dailyProducts = new ArrayList<>(products.size()) ;
Date createdAt = new Date() ;
for (Product product : products) {
DailyProduct dailyProduct = new DailyProduct() ;
dailyProduct.code = product.code ;
dailyProduct.brand = product.brand ;
dailyProduct.description = product.description;
dailyProduct.categories = product.categories ;
dailyProduct.price = product.price ;
dailyProduct.sizes = product.sizes ;
dailyProduct.broken_Size = product.product_Broken_Size ;
dailyProduct.productUrl = product.productUrl ;
dailyProduct.created_at = createdAt ;
dailyProducts.add(dailyProduct) ;
}
return dailyProducts ;
}
}
<file_sep>package crawler.mat;
import crawler.config.AppConfig;
import crawler.mat.crawling.MatCrawling;
import crawler.mat.model.Product;
import crawler.TableNameUtils;
import crawler.mat.repository.ProductRepository;
import crawler.Crawling;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
@TestPropertySource("classpath:application-test.properties")
public class DBTest {
@Autowired
ProductRepository productRepository ;
@Autowired
MatCrawling crawling;
@BeforeClass
public static void setup() {
TableNameUtils.setTableNamePostfix("cn");
}
@Test
@Ignore
public void repositoryTest() {
Product product = prepareProduct() ;
productRepository.saveAll(Arrays.asList(product, product)) ;
List<Product> products = productRepository.findAll() ;
Assert.assertEquals(products.size(), 1);
}
@Test
@Ignore
public void crawlingTest() throws Exception {
crawling.run();
}
private Product prepareProduct() {
Product product = new Product() ;
product.id = 1L ;
product.code = "1234" ;
product.brand = "brand1";
product.description = "detail2";
product.price = 1234.5;
product.sizes = Arrays.asList("12", "34", "56");
product.productUrl = "/bin/product/1234";
product.product_Live = "Live" ;
product.product_Live_Date = new Date();
product.product_Soldout_Date = new Date() ;
product.product_Broken_Size = Arrays.asList("97", "88");
product.product_Last_Broken_Size = Arrays.asList("97");
product.product_Broken_Size_Date = new Date();
product.sale_off_rate = 1025.333 ;
product.last_price = 1000.0 ;
product.sale_off_rate_date = new Date();
product.product_restock = Arrays.asList("56");
product.product_restock_Date = new Date();
return product ;
}
}
<file_sep>package crawler.net.page;
import pl.droidsonroids.jspoon.annotation.Selector;
import java.util.List;
public class NetBrandPage {
public static final String url = "https://www.net-a-porter.com" ;
//@Selector(value = ".sf-nav__bar.sf-nav__section .sf-nav__section.sf-nav__long-list.sf-nav__with-all li:not(:first-child):not(:last-child) a", attr = "href")
@Selector(value = "body > div.sf-wrapper > div > nav > ul > li:nth-child(4) > div > div > div.sf-nav__categories > div.sf-nav__section.sf-nav__long-list.sf-nav__with-all > ul :not(:first-child):not(:last-child) a:not([href*=Lingerie])", attr = "href")
public List<String> clothing ; // has size
@Selector(value = "body > div.sf-wrapper > div > nav > ul > li:nth-child(5) > div > div > div.sf-nav__categories > div.sf-nav__section.sf-nav__category-list > ul li:not(:first-child) a", attr = "href")
public List<String> shoes ; // has size
@Selector(value = "body > div.sf-wrapper > div > nav > ul > li:nth-child(6) > div > div > div.sf-nav__categories > div.sf-nav__section.sf-nav__category-list > ul li:not(:first-child) a", attr = "href")
public List<String> bags ; // no size
@Selector(value = "body > div.sf-wrapper > div > nav > ul > li:nth-child(7) > div > div > div.sf-nav__categories > div.sf-nav__section.sf-nav__category-list > ul li:not(:first-child) a", attr = "href")
public List<String> accessories ; // no size
@Selector(value = "body > div.sf-wrapper > div > nav > ul > li:nth-child(8) > div > div > div.sf-nav__categories > div.sf-nav__section.sf-nav__category-list > ul li:not(:first-child) a", attr = "href")
public List<String> jewellery ; // no size
@Selector(value = "body > div.sf-wrapper > div > nav > ul > li:nth-child(9) > div > div > div.sf-nav__categories > div.sf-nav__section.sf-nav__category-list > ul li:not(:first-child) a", attr = "href")
public List<String> lingerie ; // no size
@Selector(value = "body > div.sf-wrapper > div > nav > ul > li:nth-child(10) > div > div > div.sf-nav__categories > div.sf-nav__section.sf-nav__category-list > ul li:not(:first-child) a", attr = "href")
public List<String> beauty ; // no size
@Override
public String toString() {
return "NetBrandPage{" +
"clothing=" + clothing +
", \nshoes=" + shoes +
", \nbags=" + bags +
", \naccessories=" + accessories +
", \njewellery=" + jewellery +
", \nlingerie=" + lingerie +
", \nbeauty=" + beauty +
'}';
}
}
<file_sep>REVOKE ALL PRIVILEGES ON crawler.* FROM 'crawler'@'localhost';
REVOKE ALL PRIVILEGES ON crawler.* FROM 'crawler'@'%';
DROP USER 'crawler'@'localhost';
DROP USER 'crawler'@'%';
DROP DATABASE crawler;
<file_sep>package crawler.net.crawling;
import crawler.net.page.NetBrandPage;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import pl.droidsonroids.jspoon.HtmlAdapter;
import pl.droidsonroids.jspoon.Jspoon;
import java.io.IOException;
@Component
public class NetCrawingBrands {
private Jspoon jspoon = Jspoon.create();
private HtmlAdapter<NetBrandPage> htmlPageAdapter = jspoon.adapter(NetBrandPage.class);
final static Logger logger = LoggerFactory.getLogger(NetCrawingBrands.class);
public NetBrandPage crawle() throws IOException {
Connection.Response response = null;
response = Jsoup.connect(NetBrandPage.url)
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.timeout(60000)
.execute();
int statusCode = response.statusCode();
if ( statusCode != 200 ) {
logger.error("NetCrawingBrands: Status Code: " + statusCode); ;
return new NetBrandPage() ;
} else {
String htmlBodyContent = response.body();
NetBrandPage brands = htmlPageAdapter.fromHtml(htmlBodyContent);
return brands;
}
}
}
<file_sep>use crawler;
CREATE TABLE crawler_data_net_cn (
id bigint(32) NOT NULL AUTO_INCREMENT,
code VARCHAR(30) COMMENT '',
brand VARCHAR(255),
description VARCHAR(255),
price decimal(10,2),
sizes VARCHAR(255),
categories VARCHAR(255),
product_url VARCHAR(255),
Product_Live VARCHAR(30),
Product_Live_Date Date,
Product_Soldout_Date Date,
Product_Broken_Size VARCHAR(255),
Product_Last_Broken_Size VARCHAR(255),
Product_Broken_Size_Date Date,
sale_off_rate double,
last_price decimal(10,2),
sale_off_rate_date Date,
Product_restock VARCHAR(255),
Product_restock_Date Date,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE crawler_data_net_hk (
id bigint(32) NOT NULL AUTO_INCREMENT,
code VARCHAR(30) COMMENT '',
brand VARCHAR(255),
description VARCHAR(255),
price decimal(10,2),
sizes VARCHAR(255),
categories VARCHAR(255),
product_url VARCHAR(255),
Product_Live VARCHAR(30),
Product_Live_Date Date,
Product_Soldout_Date Date,
Product_Broken_Size VARCHAR(255),
Product_Last_Broken_Size VARCHAR(255),
Product_Broken_Size_Date Date,
sale_off_rate double,
last_price decimal(10,2),
sale_off_rate_date Date,
Product_restock VARCHAR(255),
Product_restock_Date Date,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE crawler_data_net_us (
id bigint(32) NOT NULL AUTO_INCREMENT,
code VARCHAR(30) COMMENT '',
brand VARCHAR(255),
description VARCHAR(255),
price decimal(10,2),
sizes VARCHAR(255),
categories VARCHAR(255),
product_url VARCHAR(255),
Product_Live VARCHAR(30),
Product_Live_Date Date,
Product_Soldout_Date Date,
Product_Broken_Size VARCHAR(255),
Product_Last_Broken_Size VARCHAR(255),
Product_Broken_Size_Date Date,
sale_off_rate double,
last_price decimal(10,2),
sale_off_rate_date Date,
Product_restock VARCHAR(255),
Product_restock_Date Date,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
<file_sep>package crawler.net.repository;
import crawler.net.model.ProductNet;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface ProductNetRepository extends JpaRepository<ProductNet, Integer> {
}
<file_sep>package crawler.net.crawling;
import crawler.net.page.NetProductDetailPage;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import pl.droidsonroids.jspoon.HtmlAdapter;
import pl.droidsonroids.jspoon.Jspoon;
import java.io.IOException;
@Component
@Scope("prototype")
public class NetCrawingProductSizes {
final static Logger logger = LoggerFactory.getLogger(NetCrawingProductSizes.class);
public static final int DELAY = 5 ;
public static final int MOD = 4 ;
public static final int ONE_SECOND = 1000 ;
private Jspoon jspoon = Jspoon.create();
private HtmlAdapter<NetProductDetailPage> htmlPageAdapter = jspoon.adapter(NetProductDetailPage.class);
public NetProductDetailPage crawle(String url, String referer) throws IOException {
//logger.info("NetCrawingProductSizes:referrer:" + referer);
Connection.Response response = null;
response = Jsoup.connect(url)
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.referrer(referer)
.followRedirects(true)
.timeout(60000)
.execute();
int statusCode = response.statusCode();
if ( statusCode != 200 ) {
logger.error("NetCrawingProductSizes:Status Code: " + statusCode + " at page " + url); ;
return new NetProductDetailPage() ;
}
String htmlBodyContent = response.body() ;
NetProductDetailPage page = htmlPageAdapter.fromHtml(htmlBodyContent);
return page ;
}
}
<file_sep>package crawler;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Utils {
private final static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static Double toDouble(String s) {
if (!Character.isDigit(s.charAt(0)))
s = s.substring(1) ;
s = s.replace(",", "") ;
return Double.parseDouble(s) ;
}
public static Date dateFrom(String s ) throws ParseException {
return dateFormat.parse(s) ;
}
public static String toDateString(Date d ) throws ParseException {
return dateFormat.format(d) ;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>crawler-ma</groupId>
<artifactId>crawler-ma</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.0.Final</version>
</dependency>
<dependency>
<groupId>edu.uci.ics</groupId>
<artifactId>crawler4j</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
<dependency>
<groupId>pl.droidsonroids</groupId>
<artifactId>jspoon</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.univocity</groupId>
<artifactId>univocity-parsers</artifactId>
<version>2.5.9</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.6-jre</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.6.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>crawler-ma</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>
crawler.Main
</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project><file_sep>truncate table crawler_daily_data_net_cn;
truncate table crawler_daily_data_net_hk;
truncate table crawler_daily_data_net_us;<file_sep>package crawler.net;
import crawler.config.AppConfig;
import crawler.net.model.ProductNet;
import crawler.net.page.NetProductListPage;
import crawler.net.crawling.NetCrawingProducts;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
@TestPropertySource("classpath:application-test.properties")
public class NetProdcutListTest {
@Autowired
NetCrawingProducts netCrawingProducts ;
@Test
public void crawleOnePage() throws IOException {
String url = "https://www.net-a-porter.com/cn/en/d/Shop/Clothing/../Clothing/Beachwear?cm_sp=topnav-_-clothing-_-beachwear&pn=1&npp=60&image_view=product&dScroll=0" ;
NetProductListPage productPage = netCrawingProducts.doCrawle(url, "https://www.net-a-porter.com") ;
System.out.println(productPage) ;
Assert.assertEquals(productPage.currentPage, productPage.lastPage);
}
@Test
public void crowleOneBrandTest() throws Exception {
String brand = "/cn/en/Shop/Clothing/Jackets?pn=1&npp=60&image_view=product&navlevel3=Blazers&cm_sp=topnav-_-clothing-_-blazers" ;
netCrawingProducts.crawle(brand) ;
List<ProductNet> products = netCrawingProducts.getCrawledProducts() ;
System.out.println(products) ;
Assert.assertEquals(695, products.size());
}
@Test
public void urlTest() throws URISyntaxException, MalformedURLException {
String urlStr = "https://www.net-a-porter.com/cn/en/d/Shop/Clothing/../Clothing/Beachwear?cm_sp=topnav-_-clothing-_-beachwear&pn=1&npp=60&image_view=product&dScroll=0" ;
URL url = new URI(urlStr).normalize().toURL();
System.out.println(url.toExternalForm());
}
}
<file_sep>package crawler.mat.repository;
import crawler.mat.model.DailyProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class DailyProductDao {
@Autowired
DailyProductRepository dailyProductRepository ;
public void save(List<DailyProduct> products) {
dailyProductRepository.saveAll(products) ;
}
}<file_sep>CREATE DATABASE crawler;
CREATE USER 'crawler'@'localhost' IDENTIFIED BY '<PASSWORD>';
CREATE USER 'crawler'@'%' IDENTIFIED BY '<PASSWORD>';
GRANT ALL PRIVILEGES ON crawler.* TO 'crawler'@'localhost';
GRANT ALL PRIVILEGES ON crawler.* TO 'crawler'@'%';
use crawler;
CREATE TABLE crawler_data_cn (
id bigint(32) NOT NULL AUTO_INCREMENT,
code VARCHAR(30) COMMENT '',
brand VARCHAR(255),
description VARCHAR(255),
price decimal(10,2),
sizes VARCHAR(255),
categories VARCHAR(255),
product_url VARCHAR(255),
Product_Live VARCHAR(30),
Product_Live_Date Date,
Product_Soldout_Date Date,
Product_Broken_Size VARCHAR(255),
Product_Last_Broken_Size VARCHAR(255),
Product_Broken_Size_Date Date,
sale_off_rate double,
last_price decimal(10,2),
sale_off_rate_date Date,
Product_restock VARCHAR(255),
Product_restock_Date Date,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE crawler_data_hk (
id bigint(32) NOT NULL AUTO_INCREMENT,
code VARCHAR(30) COMMENT '',
brand VARCHAR(255),
description VARCHAR(255),
price decimal(10,2),
sizes VARCHAR(255),
categories VARCHAR(255),
product_url VARCHAR(255),
Product_Live VARCHAR(30),
Product_Live_Date Date,
Product_Soldout_Date Date,
Product_Broken_Size VARCHAR(255),
Product_Last_Broken_Size VARCHAR(255),
Product_Broken_Size_Date Date,
sale_off_rate double,
last_price decimal(10,2),
sale_off_rate_date Date,
Product_restock VARCHAR(255),
Product_restock_Date Date,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE crawler_data_us (
id bigint(32) NOT NULL AUTO_INCREMENT,
code VARCHAR(30) COMMENT '',
brand VARCHAR(255),
description VARCHAR(255),
price decimal(10,2),
sizes VARCHAR(255),
categories VARCHAR(255),
product_url VARCHAR(255),
Product_Live VARCHAR(30),
Product_Live_Date Date,
Product_Soldout_Date Date,
Product_Broken_Size VARCHAR(255),
Product_Last_Broken_Size VARCHAR(255),
Product_Broken_Size_Date Date,
sale_off_rate double,
last_price decimal(10,2),
sale_off_rate_date Date,
Product_restock VARCHAR(255),
Product_restock_Date Date,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE crawler_daily_data_cn (
id bigint(32) NOT NULL AUTO_INCREMENT,
code VARCHAR(30) COMMENT '',
brand VARCHAR(255),
description VARCHAR(255),
price decimal(10,2),
sizes VARCHAR(255),
broken_Size VARCHAR(255),
categories VARCHAR(255),
product_url VARCHAR(255),
created_at Date,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE crawler_daily_data_hk (
id bigint(32) NOT NULL AUTO_INCREMENT,
code VARCHAR(30) COMMENT '',
brand VARCHAR(255),
description VARCHAR(255),
price decimal(10,2),
sizes VARCHAR(255),
broken_Size VARCHAR(255),
categories VARCHAR(255),
product_url VARCHAR(255),
created_at Date,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE crawler_daily_data_us (
id bigint(32) NOT NULL AUTO_INCREMENT,
code VARCHAR(30) COMMENT '',
brand VARCHAR(255),
description VARCHAR(255),
price decimal(10,2),
sizes VARCHAR(255),
broken_Size VARCHAR(255),
categories VARCHAR(255),
product_url VARCHAR(255),
created_at Date,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
<file_sep>package crawler.mat.repository;
import java.util.List;
import crawler.mat.model.Product;
import crawler.mat.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* If the goal is to modify an entity, you don't need any update method. You get the object from the database, modify it, and JPA saves it automatically:
* User u = repository.findOne(id);
* u.setFirstName("new first name");
* u.setLastName("new last name");
*
* If you have a detached entity and want to merge it, then use the save() method of CrudRepository:
* User attachedUser = repository.save(detachedUser);
*/
@Component
public class ProductDao {
@Autowired
ProductRepository productRepository ;
public void save(List<Product> products) {
productRepository.saveAll(products) ;
}
public List<Product> loadAll() {
return productRepository.findAll() ;
}
public void deleteAllProducts() {
productRepository.deleteAll();
}
}<file_sep>package crawler.mat;
import crawler.Main;
import crawler.mat.model.Product;
import crawler.mat.page.ProductListPage;
import crawler.mat.crawling.CrawingProducts;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
public class ProductCrawlerTest {
final static Logger logger = LoggerFactory.getLogger(Main.class);
@Test
public void crowleOnePageTest() {
// load last crawled products
String url = "https://www.matchesfashion.com/intl/womens/shop/clothing/activewear" ;
CrawingProducts crawingProducts = new CrawingProducts() ;
try {
ProductListPage productPage = crawingProducts.doCrawle(url, "https://www.matchesfashion.com/intl/womens/shop") ;
System.out.println(productPage) ;
Assert.assertEquals(productPage.nextPage, "/intl/womens/shop/clothing/activewear?page=2&noOfRecordsPerPage=60&sort=");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void crowleOneBrandTest() throws Exception {
String brand = "/intl/womens/shop/clothing/jackets" ;
CrawingProducts crawingProducts = new CrawingProducts() ;
crawingProducts.crawle(brand) ;
List<Product> products = crawingProducts.getCrawledProducts() ;
System.out.println(products) ;
Assert.assertEquals(695, products.size());
}
}
<file_sep>package crawler;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ZonePhysicalNamingStrategy implements PhysicalNamingStrategy {
final static Logger logger = LoggerFactory.getLogger(ZonePhysicalNamingStrategy.class);
@Override
public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment) {
return name;
}
@Override
public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment) {
return name;
}
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
String tableNamePostfix = TableNameUtils.getTableNamePostfix() ;
logger.info("*CanonicalName*:" + name.getCanonicalName());
String tableName = null ;
switch (name.getCanonicalName()) {
case "product":
tableName = "crawler_data_" + tableNamePostfix ;
break;
case "dailyproduct":
tableName = "crawler_daily_data_" + tableNamePostfix ;
break;
case "productnet":
tableName = "crawler_data_net_" + tableNamePostfix ;
break;
}
logger.info("*tableName*:" + tableName);
Identifier identifier = Identifier.toIdentifier(tableName) ;
return identifier;
}
@Override
public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) {
return name;
}
@Override
public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment) {
return name;
}
}<file_sep>package crawler.net.page;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import pl.droidsonroids.jspoon.annotation.Selector;
import java.util.List;
//@Selector(value="#select")
public class NetProductDetailPage {
/** size */
@Selector(value="#product-form > div.sizing-container > select-dropdown", attr="options")
public String options ; // NO_VALUE, JSON string
@Selector(value = "div.sold-out-description > div > span")
public String soldOut ; // NO_VALUE, Item Sold Out
public NetProductDetailPage() {
}
@Override
public String toString() {
return "NetProductDetailPage{" +
"options='" + options + '\'' +
", soldOut='" + soldOut + '\'' +
'}';
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class OptionJson {
public String id ;
public String stockLevel ; // Low_Stock, In_Stock, Out_of_Stock
public String displaySize ;
@Override
public String toString() {
return "OptionJson{" +
"id='" + id + '\'' +
", stockLevel='" + stockLevel + '\'' +
", displaySize='" + displaySize + '\'' +
'}';
}
}
}
| 93d9d1be4a36d031b78fddead205a5d280c97f3a | [
"Java",
"Maven POM",
"SQL"
]
| 19 | Java | guofengzh/jsoup-crawler | a184a665993956d326a15af814afcc6efd303f82 | f01287ace65b4cc40dce0dacf257a734aa7ee657 |
refs/heads/master | <repo_name>Adaptablepenny/RPG2<file_sep>/Assets/Scripts/Combat/CombatTarget.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Core;
using RPG.Attributes;
using RPG.Controller;
namespace RPG.Combat
{
[RequireComponent(typeof(Health))]
public class CombatTarget : MonoBehaviour, IRayCastable
{
public CursorType GetCursorType()
{
return CursorType.Combat;
}
//As of now, just here to define enemy targets
public bool HandleRaycast(PlayerController callingController)
{
if (!callingController.GetComponent<Fighter>().CanAttack(gameObject))// if the target does not have the combat target component move on to the next one on the list
{
return false;
}
if (Input.GetMouseButton(0))// if the target has the combat target component, attack it.
{
callingController.GetComponent<Fighter>().Attack(gameObject);
}
return true;
}
}
}
<file_sep>/Assets/Scripts/Stats/LevelDisplay.cs
using RPG.Stats;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace RPG.Attributes
{
public class LevelDisplay : MonoBehaviour
{
BaseStats stats;
private void Awake()
{
stats = GameObject.FindWithTag("Player").GetComponent<BaseStats>();
}
// Update is called once per frame
void Update()
{
GetComponent<Text>().text = stats.GetLevel().ToString();
}
}
}
<file_sep>/Assets/Scripts/Movement/Mover.cs
using RPG.Core;
using UnityEngine;
using UnityEngine.AI;
using RPG.Saving;
using RPG.Attributes;
namespace RPG.Movement
{
public class Mover : MonoBehaviour, IAction, ISaveable
{
NavMeshAgent agent;
Health health;
[SerializeField] Transform target;
[SerializeField] float maxSpeed = 6f;
// Start is called before the first frame update
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
health = GetComponent<Health>();
}
void Start()
{
}
// Update is called once per frame
void Update()
{
agent.enabled = !health.IsDead();
UpdateAnimator();
}
public void StartMoveAction (Vector3 destination, float speedFraction)
{
GetComponent<ActionScheduler>().StartAction(this);//Although states start it actually cancels the previous action to move on to the next
MoveTo(destination, speedFraction);
}
public void MoveTo(Vector3 destination, float speedFraction) //Moves player to where they clicked
{
agent.destination = destination;
agent.speed = maxSpeed * Mathf.Clamp01(speedFraction);
agent.isStopped = false;
}
public void Cancel()//stops the character from moving
{
agent.isStopped = true;
}
private void UpdateAnimator()
{
Vector3 vel = GetComponent<NavMeshAgent>().velocity; //gets the velocity from the nav mesh agent
Vector3 localvel = transform.InverseTransformDirection(vel);//converts the velocity from world space to local space
float speed = localvel.z;//gets the z velocity and stores it in the speed variable
GetComponent<Animator>().SetFloat("ForwardSpeed", speed); //Applies the speed to the ForwardSpeed parameter in the blend tree
}
public object CaptureState()
{
return new SerializableVector3(transform.position);
}
public void RestoreState(object state)
{
SerializableVector3 position = (SerializableVector3)state;
GetComponent<NavMeshAgent>().enabled = false;
transform.position = position.ToVector();
GetComponent<NavMeshAgent>().enabled = true;
}
}
}
<file_sep>/Assets/Scripts/Combat/Fighter.cs
using RPG.Core;
using RPG.Movement;
using RPG.Saving;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Attributes;
using RPG.Stats;
using GameDevTV.Utils;
using System;
namespace RPG.Combat
{
public class Fighter : MonoBehaviour, IAction, ISaveable, IModifierProvider
{
[SerializeField] Transform rightHandTransform = null;
[SerializeField] Transform leftHandTransform = null;
[SerializeField] float timeBetweenAttacks = 1f;
[SerializeField] WeaponConfig defaultWeapon = null;
Health target;
float timeSinceLastAttack = Mathf.Infinity;
WeaponConfig currentWeaponConfig;
LazyValue<Weapon> currentWeapon;
private void Awake()
{
currentWeaponConfig = defaultWeapon;
currentWeapon = new LazyValue<Weapon>(SetupDefaultWeapon);
}
private void Start()
{
currentWeapon.ForceInit();
}
private Weapon SetupDefaultWeapon()
{
return AttachWeapon(defaultWeapon);
}
private void Update()
{
timeSinceLastAttack += Time.deltaTime;
if (target == null) return;//if no target dont do anything below
if (target.IsDead()) return;
if (!GetInRange())// if there is a target and you are not in range, move into range
{
GetComponent<Mover>().MoveTo(target.transform.position, 1f);
}
else// once in range stop
{
GetComponent<Mover>().Cancel();
AttackBehaviour();
}
}
private void AttackBehaviour()
{
transform.LookAt(target.transform);
if (timeSinceLastAttack > timeBetweenAttacks)//Cooldown timer between attacks
{
//This will trigger Hit() event
TriggerAttack();
timeSinceLastAttack = 0;
}
}
private void TriggerAttack()//triggers animations by reseting the cancel attack trigger, and setting the attack trigger
{
GetComponent<Animator>().ResetTrigger("CancelAttack");
GetComponent<Animator>().SetTrigger("Attack");
}
public bool CanAttack(GameObject combatTarget)//Checks to see if the target is attackable
{
if(combatTarget == null ) { return false; }
Health targetToTest = combatTarget.GetComponent<Health>();
return targetToTest != null && !targetToTest.IsDead();
}
void Hit()//Animation Event
{
if (target == null) return;
float damage = GetComponent<BaseStats>().GetStat(Stat.Damage);
if(currentWeapon.value != null)
{
currentWeapon.value.OnHit();
}
if (currentWeaponConfig.HasProjectile())
{
currentWeaponConfig.LaunchProjectile(rightHandTransform, leftHandTransform, target, gameObject, damage);
}
else
{
target.TakeDamage(gameObject, damage);
}
}
void Shoot()
{
Hit();
}
private bool GetInRange()//Gets the distance between the player and the target and checks to see if it is within the range
{
return Vector3.Distance(transform.position, target.transform.position) <= currentWeaponConfig.GetRange();
}
public void Attack(GameObject combatTarget)//Declares the target as the selected combat target
{
GetComponent<ActionScheduler>().StartAction(this);//Although states start it actually cancels the previous action to move on to the next
target = combatTarget.GetComponent<Health>();
}
public void Cancel()//clears the target and stops attacking
{
StopAttack();
target = null;
GetComponent<Mover>().Cancel();
}
private void StopAttack()//triggers animations by reseting the attack trigger, and setting the cancel attack trigger
{
GetComponent<Animator>().ResetTrigger("Attack");
GetComponent<Animator>().SetTrigger("CancelAttack");
}
public void EquipWeapon(WeaponConfig weapon)
{
currentWeaponConfig = weapon;
currentWeapon.value = AttachWeapon(weapon);
}
private Weapon AttachWeapon(WeaponConfig weapon)
{
Animator animator = GetComponent<Animator>();
return weapon.Spawn(rightHandTransform, leftHandTransform, animator);
}
public object CaptureState()
{
return currentWeaponConfig.name;
}
public void RestoreState(object state)
{
string weaponName = (string)state;
currentWeaponConfig = UnityEngine.Resources.Load<WeaponConfig>(weaponName);
EquipWeapon(currentWeaponConfig);
}
public Health GetTarget()
{
return target;
}
public IEnumerable<float> GetAdditiveModifiers(Stat stat)
{
if (stat == Stat.Damage)
{
yield return currentWeaponConfig.GetDamage();
}
}
public IEnumerable<float> GetPercentageModifier(Stat stat)
{
if (stat == Stat.Damage)
{
yield return currentWeaponConfig.GetPercentageBonus();
}
}
}
}
<file_sep>/Assets/Scripts/Controller/AIController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Combat;
using RPG.Core;
using RPG.Movement;
using System;
using RPG.Attributes;
using GameDevTV.Utils;
namespace RPG.Controller
{
public class AIController : MonoBehaviour
{
[SerializeField] float chaseDistance = 10f;
[SerializeField] float suspicionTime = 3f;
[SerializeField] PatrolPath patrolPath;
[SerializeField] float waypointTolerance = 1f;
[SerializeField] float waypointDwellTime = 2f;
[Range(0,1)]
[SerializeField] float speedFraction = 0.2f;
Fighter fight;
GameObject player;
Health health;
float timeSinceLastWaypoint = Mathf.Infinity;
float timeSinceLastSawPlayer = Mathf.Infinity;
//Vector3 guardPosition;
int currentWaypointIndex = 0;
LazyValue<Vector3> guardPosition;
private void Awake()
{
player = GameObject.FindWithTag("Player");
fight = GetComponent<Fighter>();
health = GetComponent<Health>();
guardPosition = new LazyValue<Vector3>(GetGuardPosition);
}
private void Start()
{
guardPosition.ForceInit();
}
private Vector3 GetGuardPosition()
{
return transform.position;
}
private void Update()
{
if (health.IsDead()) return;// checks to see if the AI is dead
if (DistanceToPlayer() && fight.CanAttack(player))
{
AttackBehaviour();
}
else if (suspicionTime > timeSinceLastSawPlayer)
{
SuspicionBehaviour();
}
else
{
PatrolBehaviour();
}
UpdateTimers();
}
private void UpdateTimers()
{
timeSinceLastSawPlayer += Time.deltaTime;
timeSinceLastWaypoint += Time.deltaTime;
}
private void PatrolBehaviour()
{
Vector3 nextPos = guardPosition.value;
//Decrease speed to patrol
if (patrolPath != null)
{
if(AtWaypoint())
{
timeSinceLastWaypoint = 0;
CycleWaypoint();
}
nextPos = GetCurrentWaypoint();
}
if(waypointDwellTime < timeSinceLastWaypoint)
{
GetComponent<Mover>().StartMoveAction(nextPos, speedFraction);
}
}
private Vector3 GetCurrentWaypoint()
{
return patrolPath.GetWaypoint(currentWaypointIndex);
}
private void CycleWaypoint()
{
currentWaypointIndex = patrolPath.GetNextIndex(currentWaypointIndex);
}
private bool AtWaypoint()
{
float distanceToWaypoint = Vector3.Distance(transform.position, GetCurrentWaypoint());
return distanceToWaypoint < waypointTolerance;
}
private void SuspicionBehaviour()
{
GetComponent<ActionScheduler>().CancelCurrentAction();
}
private void AttackBehaviour()
{
//Increase speed to chase
fight.Attack(player);
timeSinceLastSawPlayer = 0;
}
private bool DistanceToPlayer()//calculates distance between AI and target (player)
{
float distanceToPlayer = Vector3.Distance(transform.position, player.transform.position);
return distanceToPlayer < chaseDistance;
}
//Called by Unity
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, chaseDistance);
}
}
}
<file_sep>/Assets/Scripts/Cinematic/CinematicsControlRemover.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
using RPG.Core;
using RPG.Controller;
namespace RPG.Cinematics
{
public class CinematicsControlRemover : MonoBehaviour
{
GameObject player;
private void Awake()
{
player = GameObject.FindWithTag("Player");
}
private void Start()
{
}
private void OnEnable()
{
GetComponent<PlayableDirector>().played += DisableControl;//event methods add functions to their list and execute them as soon as the event occurs
GetComponent<PlayableDirector>().stopped += EnableControl;//event methods add functions to their list and execute them as soon as the event occurs
//In the scenario above, the DisableControl() is added to the list of functions that are executed when the method .played is called
//Same thing goes for the .stopped
}
private void OnDisable()
{
GetComponent<PlayableDirector>().played -= DisableControl;//event methods add functions to their list and execute them as soon as the event occurs
GetComponent<PlayableDirector>().stopped -= EnableControl;//event methods add functions to their list and execute them as soon as the event occurs
//In the scenario above, the DisableControl() is added to the list of functions that are executed when the method .played is called
//Same thing goes for the .stopped
}
void DisableControl(PlayableDirector pd)
{
player.GetComponent<ActionScheduler>().CancelCurrentAction();
player.GetComponent<PlayerController>().enabled = false;
}
void EnableControl(PlayableDirector pd)
{
player.GetComponent<PlayerController>().enabled = true;
}
}
} | b1a597744c236fda82600c8e321fdd13cf97326b | [
"C#"
]
| 6 | C# | Adaptablepenny/RPG2 | 2ab23da5c1249b31d43fb165c6e7ac7827ea5754 | 7a87406d5e88ff160bb1231eabdcacebad460490 |
refs/heads/master | <repo_name>Azrrul/Tiket_Bioskop<file_sep>/src/form/Loginadmin.java
package form;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import transaksi.transaksi;
class adminlog{
String usernameadmin = "azrul",passwordadmin = "<PASSWORD>";
}
class userlog{
String userp = "pelanggan", passwp = "<PASSWORD>";
}
public class Loginadmin extends javax.swing.JFrame {
private transaksi trans;
adminlog adm = new adminlog();
userlog user = new userlog();
/**
* Creates new form login
*/
public Loginadmin() throws SQLException {
initComponents();
this.trans = new transaksi();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
login = new javax.swing.JToggleButton();
password = new <PASSWORD>();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
pembeli = new javax.swing.JLabel();
awal2 = new javax.swing.JLabel();
idreg1 = new javax.swing.JTextField();
back = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jPanel1.setLayout(null);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/cinema-illustration-11129.jpg"))); // NOI18N
jPanel1.add(jLabel1);
jLabel1.setBounds(0, 0, 600, 600);
jPanel2.setBackground(new java.awt.Color(0, 102, 102));
login.setBackground(new java.awt.Color(51, 51, 51));
login.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
login.setForeground(new java.awt.Color(255, 255, 255));
login.setText("LOGIN");
login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("ID");
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("PASSWORD");
pembeli.setFont(new java.awt.Font("Times New Roman", 1, 20)); // NOI18N
pembeli.setForeground(new java.awt.Color(255, 255, 255));
pembeli.setText("Kembali Ke Pembeli");
pembeli.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
pembeliMousePressed(evt);
}
});
awal2.setFont(new java.awt.Font("Times New Roman", 1, 20)); // NOI18N
awal2.setForeground(new java.awt.Color(255, 255, 255));
awal2.setText("Kembali Ke Awal");
awal2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
awal2MousePressed(evt);
}
});
idreg1.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N
idreg1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
idreg1ActionPerformed(evt);
}
});
back.setFont(new java.awt.Font("Times New Roman", 1, 20)); // NOI18N
back.setText("Kembali");
back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(35, 35, 35)))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(idreg1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(awal2, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pembeli)
.addGap(40, 40, 40)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(72, 72, 72))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(back, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(back, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(159, 159, 159)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(idreg1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(46, 46, 46)
.addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(112, 112, 112)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(pembeli)
.addComponent(awal2))
.addContainerGap())
);
jPanel1.add(jPanel2);
jPanel2.setBounds(600, 0, 450, 600);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 1053, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 602, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void idreg1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idreg1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_idreg1ActionPerformed
private void loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginActionPerformed
// TODO add your handling code here:
try {
if(idreg1.getText().equals(adm.usernameadmin) && password.getText().equals(adm.<PASSWORD>)){
new Movies().show();
new Loginadmin().setVisible(false);
}
}catch(SQLException err){
System.out.println(err);
}
setVisible(false);
}//GEN-LAST:event_loginActionPerformed
private void backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backActionPerformed
// TODO add your handling code here:
new MenuPembeli().setVisible(true);
}//GEN-LAST:event_backActionPerformed
private void pembeliMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pembeliMousePressed
// TODO add your handling code here:
new MenuPembeli().setVisible(true);
setVisible(false);
}//GEN-LAST:event_pembeliMousePressed
private void awal2MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_awal2MousePressed
// TODO add your handling code here:
new awal().setVisible(true);
setVisible(false);
}//GEN-LAST:event_awal2MousePressed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Loginadmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Loginadmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Loginadmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Loginadmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new Loginadmin().setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(Loginadmin.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel awal2;
private javax.swing.JButton back;
private javax.swing.JTextField idreg1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JToggleButton login;
private javax.swing.JPasswordField password;
private javax.swing.JLabel pembeli;
// End of variables declaration//GEN-END:variables
}
<file_sep>/nbproject/private/private.properties
compile.on.save=true
user.properties.file=C:\\Users\\didik\\AppData\\Roaming\\NetBeans\\8.2rc\\build.properties
<file_sep>/src/Fungsi/RegistrasiUser.java
package Fungsi;
import sun.security.pkcs11.P11TlsKeyMaterialGenerator;
public class RegistrasiUser extends inti{
public String nama, alamat, notelp,password;//idregistrasi;
public Integer idregistrasi;
Pembeli pel;
public Pembeli getPel() {
return pel;
}
public void setPel(Pembeli pel) {
this.pel = pel;
}
public void set_Id_Reg(Integer Id_Reg){
super.Id_Reg = Id_Reg;
}
public void set_nama(String nama){
this.nama = nama;
}
public Integer getIdregistrasi() {
return idregistrasi;
}
public void setIdregistrasi(Integer idregistrasi) {
this.idregistrasi = idregistrasi;
}
public void set_alamat(String alamat){
this.alamat = alamat;
}
public void set_notelp(String notelp){
this.notelp = notelp;
}
public Integer get_Id_Reg(){
return Id_Reg;
}
public String get_nama(){
return nama;
}
public String get_notelp(){
return notelp;
}
public String get_alamat(){
return alamat;
}
}
<file_sep>/projek.sql
--------------------------------------------------------
-- File created - Jumat-Juli-03-2020
--------------------------------------------------------
--------------------------------------------------------
-- DDL for Table FILM_07074
--------------------------------------------------------
CREATE TABLE "AZRUL7_07074"."FILM_07074"
( "KODE_FILM" VARCHAR2(20 BYTE),
"NAMA_FILM" VARCHAR2(20 BYTE),
"GENRE" VARCHAR2(20 BYTE),
"RATING" VARCHAR2(10 BYTE),
"HARGA" NUMBER(20,0)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Table JADWAL_07074
--------------------------------------------------------
CREATE TABLE "AZRUL7_07074"."JADWAL_07074"
( "KODE_TAYANG" VARCHAR2(20 BYTE),
"JAM_TAYANG" VARCHAR2(20 BYTE),
"RUANG" VARCHAR2(10 BYTE),
"TANGGAL_TAYANG" DATE,
"KODE_FILM" VARCHAR2(20 BYTE)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Table PEMBELI_07074
--------------------------------------------------------
CREATE TABLE "AZRUL7_07074"."PEMBELI_07074"
( "ID" NUMBER(*,0),
"PASSWORD" VARCHAR2(20 BYTE),
"ID_REG" NUMBER(*,0)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Table REGISTER_07074
--------------------------------------------------------
CREATE TABLE "AZRUL7_07074"."REGISTER_07074"
( "ID_REG" NUMBER(*,0),
"NAMA" VARCHAR2(20 BYTE),
"ALAMAT" VARCHAR2(100 BYTE),
"NO_TELP" NUMBER(*,0),
"ID" NUMBER(*,0)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Table SET_07074
--------------------------------------------------------
CREATE TABLE "AZRUL7_07074"."SET_07074"
( "KODE_TIKET" NUMBER(*,0),
"KODE_TAYANG" VARCHAR2(20 BYTE)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Table TIKET_07074
--------------------------------------------------------
CREATE TABLE "AZRUL7_07074"."TIKET_07074"
( "KODE_TIKET" NUMBER(*,0),
"BANGKU" VARCHAR2(20 BYTE),
"JUMLAH" NUMBER(20,0),
"TOTAL" NUMBER(20,0),
"ID" NUMBER(*,0)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
REM INSERTING into AZRUL7_07074.FILM_07074
SET DEFINE OFF;
Insert into AZRUL7_07074.FILM_07074 (KODE_FILM,NAMA_FILM,GENRE,RATING,HARGA) values ('null','loli','ROMANCE','y','1500');
Insert into AZRUL7_07074.FILM_07074 (KODE_FILM,NAMA_FILM,GENRE,RATING,HARGA) values ('A01','doraemon','komedi','g','50000');
Insert into AZRUL7_07074.FILM_07074 (KODE_FILM,NAMA_FILM,GENRE,RATING,HARGA) values ('A02','sinchan','sci-fi','g','5');
Insert into AZRUL7_07074.FILM_07074 (KODE_FILM,NAMA_FILM,GENRE,RATING,HARGA) values ('A03','hamtaro','animasi','g','30000');
Insert into AZRUL7_07074.FILM_07074 (KODE_FILM,NAMA_FILM,GENRE,RATING,HARGA) values ('A04','TheNun','horror','pg','45000');
Insert into AZRUL7_07074.FILM_07074 (KODE_FILM,NAMA_FILM,GENRE,RATING,HARGA) values ('A05','alita','action','r','27000');
REM INSERTING into AZRUL7_07074.JADWAL_07074
SET DEFINE OFF;
Insert into AZRUL7_07074.JADWAL_07074 (KODE_TAYANG,JAM_TAYANG,RUANG,TANGGAL_TAYANG,KODE_FILM) values ('#Z11','10.00','A',to_date('01-02-2001','DD-MM-RRRR'),'A01');
Insert into AZRUL7_07074.JADWAL_07074 (KODE_TAYANG,JAM_TAYANG,RUANG,TANGGAL_TAYANG,KODE_FILM) values ('#Z22','11.00','B',to_date('02-03-2003','DD-MM-RRRR'),'A02');
Insert into AZRUL7_07074.JADWAL_07074 (KODE_TAYANG,JAM_TAYANG,RUANG,TANGGAL_TAYANG,KODE_FILM) values ('#Z33','12.00','C',to_date('11-12-2003','DD-MM-RRRR'),'A03');
Insert into AZRUL7_07074.JADWAL_07074 (KODE_TAYANG,JAM_TAYANG,RUANG,TANGGAL_TAYANG,KODE_FILM) values ('#Z44','13.30','D',to_date('12-01-2004','DD-MM-RRRR'),'A04');
Insert into AZRUL7_07074.JADWAL_07074 (KODE_TAYANG,JAM_TAYANG,RUANG,TANGGAL_TAYANG,KODE_FILM) values ('#Z55','14.30','E',to_date('15-04-2005','DD-MM-RRRR'),'A05');
REM INSERTING into AZRUL7_07074.PEMBELI_07074
SET DEFINE OFF;
Insert into AZRUL7_07074.PEMBELI_07074 (ID,PASSWORD,ID_REG) values ('1','<PASSWORD>','1');
Insert into AZRUL7_07074.PEMBELI_07074 (ID,PASSWORD,ID_REG) values ('2','<PASSWORD>','2');
Insert into AZRUL7_07074.PEMBELI_07074 (ID,PASSWORD,ID_REG) values ('3','<PASSWORD>','3');
Insert into AZRUL7_07074.PEMBELI_07074 (ID,PASSWORD,ID_REG) values ('4','<PASSWORD>','4');
Insert into AZRUL7_07074.PEMBELI_07074 (ID,PASSWORD,ID_REG) values ('5','venus','5');
REM INSERTING into AZRUL7_07074.REGISTER_07074
SET DEFINE OFF;
Insert into AZRUL7_07074.REGISTER_07074 (ID_REG,NAMA,ALAMAT,NO_TELP,ID) values ('1','elannor','antaris','1122334455','1');
Insert into AZRUL7_07074.REGISTER_07074 (ID_REG,NAMA,ALAMAT,NO_TELP,ID) values ('2','eva','carano','1223344551','2');
Insert into AZRUL7_07074.REGISTER_07074 (ID_REG,NAMA,ALAMAT,NO_TELP,ID) values ('3','toro','jungle','2233445511','3');
Insert into AZRUL7_07074.REGISTER_07074 (ID_REG,NAMA,ALAMAT,NO_TELP,ID) values ('4','crest','ocean','2334455112','4');
Insert into AZRUL7_07074.REGISTER_07074 (ID_REG,NAMA,ALAMAT,NO_TELP,ID) values ('5','violet','norman','3344551122','5');
Insert into AZRUL7_07074.REGISTER_07074 (ID_REG,NAMA,ALAMAT,NO_TELP,ID) values ('6','roui','sky','4455112233','6');
REM INSERTING into AZRUL7_07074.SET_07074
SET DEFINE OFF;
Insert into AZRUL7_07074.SET_07074 (KODE_TIKET,KODE_TAYANG) values ('111','#Z11');
Insert into AZRUL7_07074.SET_07074 (KODE_TIKET,KODE_TAYANG) values ('222','#Z22');
Insert into AZRUL7_07074.SET_07074 (KODE_TIKET,KODE_TAYANG) values ('333','#Z33');
Insert into AZRUL7_07074.SET_07074 (KODE_TIKET,KODE_TAYANG) values ('444','#Z44');
Insert into AZRUL7_07074.SET_07074 (KODE_TIKET,KODE_TAYANG) values ('555','#Z55');
REM INSERTING into AZRUL7_07074.TIKET_07074
SET DEFINE OFF;
Insert into AZRUL7_07074.TIKET_07074 (KODE_TIKET,BANGKU,JUMLAH,TOTAL,ID) values ('111','A','2','25000','1');
Insert into AZRUL7_07074.TIKET_07074 (KODE_TIKET,BANGKU,JUMLAH,TOTAL,ID) values ('222','B','3','35000','2');
Insert into AZRUL7_07074.TIKET_07074 (KODE_TIKET,BANGKU,JUMLAH,TOTAL,ID) values ('333','C','5','55000','3');
Insert into AZRUL7_07074.TIKET_07074 (KODE_TIKET,BANGKU,JUMLAH,TOTAL,ID) values ('444','D','6','75000','4');
Insert into AZRUL7_07074.TIKET_07074 (KODE_TIKET,BANGKU,JUMLAH,TOTAL,ID) values ('555','E','9','95000','5');
--------------------------------------------------------
-- DDL for Index PK_FILM
--------------------------------------------------------
CREATE UNIQUE INDEX "AZRUL7_07074"."PK_FILM" ON "AZRUL7_07074"."FILM_07074" ("KODE_FILM")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Index PK_JADWAL
--------------------------------------------------------
CREATE UNIQUE INDEX "AZRUL7_07074"."PK_JADWAL" ON "AZRUL7_07074"."JADWAL_07074" ("KODE_TAYANG")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Index PK_PEMBELI
--------------------------------------------------------
CREATE UNIQUE INDEX "AZRUL7_07074"."PK_PEMBELI" ON "AZRUL7_07074"."PEMBELI_07074" ("ID")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Index PK_REGISTER
--------------------------------------------------------
CREATE UNIQUE INDEX "AZRUL7_07074"."PK_REGISTER" ON "AZRUL7_07074"."REGISTER_07074" ("ID_REG")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Index PK_TIKET
--------------------------------------------------------
CREATE UNIQUE INDEX "AZRUL7_07074"."PK_TIKET" ON "AZRUL7_07074"."TIKET_07074" ("KODE_TIKET")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- DDL for Index SYS_C007247
--------------------------------------------------------
CREATE UNIQUE INDEX "AZRUL7_07074"."SYS_C007247" ON "AZRUL7_07074"."TIKET_07074" ("BANGKU")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ;
--------------------------------------------------------
-- Constraints for Table FILM_07074
--------------------------------------------------------
ALTER TABLE "AZRUL7_07074"."FILM_07074" ADD CONSTRAINT "PK_FILM" PRIMARY KEY ("KODE_FILM")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ENABLE;
ALTER TABLE "AZRUL7_07074"."FILM_07074" MODIFY ("KODE_FILM" NOT NULL ENABLE);
--------------------------------------------------------
-- Constraints for Table JADWAL_07074
--------------------------------------------------------
ALTER TABLE "AZRUL7_07074"."JADWAL_07074" ADD CONSTRAINT "PK_JADWAL" PRIMARY KEY ("KODE_TAYANG")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ENABLE;
ALTER TABLE "AZRUL7_07074"."JADWAL_07074" MODIFY ("KODE_TAYANG" NOT NULL ENABLE);
--------------------------------------------------------
-- Constraints for Table PEMBELI_07074
--------------------------------------------------------
ALTER TABLE "AZRUL7_07074"."PEMBELI_07074" ADD CONSTRAINT "PK_PEMBELI" PRIMARY KEY ("ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ENABLE;
ALTER TABLE "AZRUL7_07074"."PEMBELI_07074" MODIFY ("ID" NOT NULL ENABLE);
--------------------------------------------------------
-- Constraints for Table REGISTER_07074
--------------------------------------------------------
ALTER TABLE "AZRUL7_07074"."REGISTER_07074" ADD CONSTRAINT "PK_REGISTER" PRIMARY KEY ("ID_REG")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ENABLE;
ALTER TABLE "AZRUL7_07074"."REGISTER_07074" MODIFY ("ID_REG" NOT NULL ENABLE);
--------------------------------------------------------
-- Constraints for Table TIKET_07074
--------------------------------------------------------
ALTER TABLE "AZRUL7_07074"."TIKET_07074" ADD UNIQUE ("BANGKU")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ENABLE;
ALTER TABLE "AZRUL7_07074"."TIKET_07074" ADD CONSTRAINT "PK_TIKET" PRIMARY KEY ("KODE_TIKET")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "LAPORAN" ENABLE;
ALTER TABLE "AZRUL7_07074"."TIKET_07074" MODIFY ("KODE_TIKET" NOT NULL ENABLE);
--------------------------------------------------------
-- Ref Constraints for Table JADWAL_07074
--------------------------------------------------------
ALTER TABLE "AZRUL7_07074"."JADWAL_07074" ADD CONSTRAINT "FK_KODE_FILM" FOREIGN KEY ("KODE_FILM")
REFERENCES "AZRUL7_07074"."FILM_07074" ("KODE_FILM") ENABLE;
--------------------------------------------------------
-- Ref Constraints for Table PEMBELI_07074
--------------------------------------------------------
ALTER TABLE "AZRUL7_07074"."PEMBELI_07074" ADD CONSTRAINT "FK_ID_REG" FOREIGN KEY ("ID_REG")
REFERENCES "AZRUL7_07074"."REGISTER_07074" ("ID_REG") ENABLE;
--------------------------------------------------------
-- Ref Constraints for Table SET_07074
--------------------------------------------------------
ALTER TABLE "AZRUL7_07074"."SET_07074" ADD CONSTRAINT "FK_KODE_TAYANG" FOREIGN KEY ("KODE_TAYANG")
REFERENCES "AZRUL7_07074"."JADWAL_07074" ("KODE_TAYANG") ENABLE;
ALTER TABLE "AZRUL7_07074"."SET_07074" ADD CONSTRAINT "FK_KODE_TIKET" FOREIGN KEY ("KODE_TIKET")
REFERENCES "AZRUL7_07074"."TIKET_07074" ("KODE_TIKET") ENABLE;
--------------------------------------------------------
-- Ref Constraints for Table TIKET_07074
--------------------------------------------------------
ALTER TABLE "AZRUL7_07074"."TIKET_07074" ADD CONSTRAINT "FK_ID" FOREIGN KEY ("ID")
REFERENCES "AZRUL7_07074"."PEMBELI_07074" ("ID") ENABLE;
<file_sep>/src/Fungsi/JadwalFilm.java
package Fungsi;
import java.util.Date;
import oracle.sql.DATE;
public class JadwalFilm extends inti{
private film film;
private String jamtayang,ruang;
Date tanggaltayang;
public void setKodeTayang(Integer kodejadwal){
super.Kode_Tayang = Kode_Tayang;
}
public void setfilm(film film){
this.film=film;
}
public void setjamtayang(String jamtayang){
this.jamtayang = jamtayang;
}
public void settanggal(Date tanggaltayang){
this.tanggaltayang = tanggaltayang;
}
public void setruang(String ruang){
this.ruang = ruang;
}
public Integer getKodeTayang(){
return Kode_Tayang;
}
public film getfilm(){
return film;
}
public String getjam(){
return jamtayang;
}
public Date gettgl(){
return tanggaltayang;
}
public String getruang(){
return ruang;
}
}
<file_sep>/src/Fungsi/EditFilm.java
package Fungsi;
import javax.swing.table.DefaultTableModel;
import koneksi.koneksi;
import abstraksi.abstrak_film;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class EditFilm extends abstrak_film {
film[] film = new film[100];
int dx=0;
@Override
public void insert(int kode_film, String nama, String genre,String rating, int harga) {
}
@Override
public void del(int kode_film) {
}
@Override
public void update(int update, int kode_film, String nama, String genre, int harga) {
}
}
<file_sep>/tiket bioskop.sql
--------------------------------------------------------
-- File created - Friday-July-03-2020
--------------------------------------------------------
--------------------------------------------------------
-- DDL for Table FILM_07056
--------------------------------------------------------
CREATE TABLE "YUSUF_07056"."FILM_07056"
( "KODEFILM" VARCHAR2(6 BYTE),
"NAMAFILM" VARCHAR2(20 BYTE),
"GENRE" VARCHAR2(10 BYTE),
"RATING" VARCHAR2(6 BYTE),
"HARGA" NUMBER(7,0)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Table JADWAL_07056
--------------------------------------------------------
CREATE TABLE "YUSUF_07056"."JADWAL_07056"
( "KODEJADWAL" VARCHAR2(6 BYTE),
"KODEFILM" VARCHAR2(6 BYTE),
"TANGGALTAYANG" DATE,
"JAMTAYANG" VARCHAR2(5 BYTE),
"RUANG" VARCHAR2(9 BYTE)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Table PELANGGAN_07056
--------------------------------------------------------
CREATE TABLE "YUSUF_07056"."PELANGGAN_07056"
( "IDREGISTER" NUMBER(6,0),
"NOKTP" NUMBER(*,0),
"PASSWORD" VARCHAR2(8 BYTE)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Table REGISTER_07056
--------------------------------------------------------
CREATE TABLE "YUSUF_07056"."REGISTER_07056"
( "NOKTP" NUMBER(*,0),
"NAMAUSER" VARCHAR2(15 BYTE),
"ALAMAT" VARCHAR2(20 BYTE),
"NO_TELP" CHAR(13 BYTE),
"IDREGISTER" NUMBER(6,0)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Table SET_07056
--------------------------------------------------------
CREATE TABLE "YUSUF_07056"."SET_07056"
( "KODETIKET" NUMBER(4,0),
"KODEJADWAL" VARCHAR2(6 BYTE)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Table TIKET_07056
--------------------------------------------------------
CREATE TABLE "YUSUF_07056"."TIKET_07056"
( "KODETIKET" NUMBER(4,0),
"BANGKU" VARCHAR2(6 BYTE),
"JUMLAH" NUMBER(*,0),
"IDREGISTER" NUMBER(6,0),
"NPM07056_TOTAL" FLOAT(4)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
REM INSERTING into YUSUF_07056.FILM_07056
SET DEFINE OFF;
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('1','1','1','1',1);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('rendi','main','bekel','dewe',20000);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('2','2','2','2',2);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('afk','apex','tidak','bagus',2000);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('yudhi','epok2','ra','ero',10000);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('arsef','arsef','arsef','arsef',2000);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('dio','dio','dio','dio',30000);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('jojo','jojo','jojo','jojo',21000);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('ataya','ataya','ataya','ataya',1111);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('arno','karno','ke','pasar',20000);
Insert into YUSUF_07056.FILM_07056 (KODEFILM,NAMAFILM,GENRE,RATING,HARGA) values ('der','der','der','der',20000);
REM INSERTING into YUSUF_07056.JADWAL_07056
SET DEFINE OFF;
Insert into YUSUF_07056.JADWAL_07056 (KODEJADWAL,KODEFILM,TANGGALTAYANG,JAMTAYANG,RUANG) values ('111','1',to_date('11-NOV-19','DD-MON-RR'),'11:30','th2');
Insert into YUSUF_07056.JADWAL_07056 (KODEJADWAL,KODEFILM,TANGGALTAYANG,JAMTAYANG,RUANG) values ('123','yudhi',to_date('30-NOV-20','DD-MON-RR'),'11:11','th3');
Insert into YUSUF_07056.JADWAL_07056 (KODEJADWAL,KODEFILM,TANGGALTAYANG,JAMTAYANG,RUANG) values ('133','jojo',to_date('29-NOV-20','DD-MON-RR'),'11:11','th2');
REM INSERTING into YUSUF_07056.PELANGGAN_07056
SET DEFINE OFF;
Insert into YUSUF_07056.PELANGGAN_07056 (IDREGISTER,NOKTP,PASSWORD) values (2,2,'uuu');
Insert into YUSUF_07056.PELANGGAN_07056 (IDREGISTER,NOKTP,PASSWORD) values (3,3,'ddd');
Insert into YUSUF_07056.PELANGGAN_07056 (IDREGISTER,NOKTP,PASSWORD) values (1,1,'yyy');
REM INSERTING into YUSUF_07056.REGISTER_07056
SET DEFINE OFF;
Insert into YUSUF_07056.REGISTER_07056 (NOKTP,NAMAUSER,ALAMAT,NO_TELP,IDREGISTER) values (3,'dedy','gataw','3 ',3);
Insert into YUSUF_07056.REGISTER_07056 (NOKTP,NAMAUSER,ALAMAT,NO_TELP,IDREGISTER) values (2,'yuda','keling','2 ',2);
Insert into YUSUF_07056.REGISTER_07056 (NOKTP,NAMAUSER,ALAMAT,NO_TELP,IDREGISTER) values (1,'yusuf','semolo','111 ',1);
REM INSERTING into YUSUF_07056.SET_07056
SET DEFINE OFF;
REM INSERTING into YUSUF_07056.TIKET_07056
SET DEFINE OFF;
--------------------------------------------------------
-- DDL for Index PK_KODEFILM
--------------------------------------------------------
CREATE UNIQUE INDEX "YUSUF_07056"."PK_KODEFILM" ON "YUSUF_07056"."FILM_07056" ("KODEFILM")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Index SYS_C007027
--------------------------------------------------------
CREATE UNIQUE INDEX "YUSUF_07056"."SYS_C007027" ON "YUSUF_07056"."FILM_07056" ("NAMAFILM")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Index PK_KODEJADWAL
--------------------------------------------------------
CREATE UNIQUE INDEX "YUSUF_07056"."PK_KODEJADWAL" ON "YUSUF_07056"."JADWAL_07056" ("KODEJADWAL")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Index PK_IDREGISTER
--------------------------------------------------------
CREATE UNIQUE INDEX "YUSUF_07056"."PK_IDREGISTER" ON "YUSUF_07056"."PELANGGAN_07056" ("IDREGISTER")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Index PK_NOKTP
--------------------------------------------------------
CREATE UNIQUE INDEX "YUSUF_07056"."PK_NOKTP" ON "YUSUF_07056"."REGISTER_07056" ("NOKTP")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Index SYS_C007029
--------------------------------------------------------
CREATE UNIQUE INDEX "YUSUF_07056"."SYS_C007029" ON "YUSUF_07056"."REGISTER_07056" ("NO_TELP")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- DDL for Index PK_KODETIKET
--------------------------------------------------------
CREATE UNIQUE INDEX "YUSUF_07056"."PK_KODETIKET" ON "YUSUF_07056"."TIKET_07056" ("KODETIKET")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ;
--------------------------------------------------------
-- Constraints for Table FILM_07056
--------------------------------------------------------
ALTER TABLE "YUSUF_07056"."FILM_07056" ADD UNIQUE ("NAMAFILM")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ENABLE;
ALTER TABLE "YUSUF_07056"."FILM_07056" ADD CONSTRAINT "PK_KODEFILM" PRIMARY KEY ("KODEFILM")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ENABLE;
ALTER TABLE "YUSUF_07056"."FILM_07056" MODIFY ("KODEFILM" NOT NULL ENABLE);
--------------------------------------------------------
-- Constraints for Table JADWAL_07056
--------------------------------------------------------
ALTER TABLE "YUSUF_07056"."JADWAL_07056" ADD CONSTRAINT "PK_KODEJADWAL" PRIMARY KEY ("KODEJADWAL")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ENABLE;
ALTER TABLE "YUSUF_07056"."JADWAL_07056" MODIFY ("KODEJADWAL" NOT NULL ENABLE);
--------------------------------------------------------
-- Constraints for Table PELANGGAN_07056
--------------------------------------------------------
ALTER TABLE "YUSUF_07056"."PELANGGAN_07056" ADD CONSTRAINT "PK_IDREGISTER" PRIMARY KEY ("IDREGISTER")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ENABLE;
ALTER TABLE "YUSUF_07056"."PELANGGAN_07056" MODIFY ("IDREGISTER" NOT NULL ENABLE);
--------------------------------------------------------
-- Constraints for Table REGISTER_07056
--------------------------------------------------------
ALTER TABLE "YUSUF_07056"."REGISTER_07056" ADD UNIQUE ("NO_TELP")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ENABLE;
ALTER TABLE "YUSUF_07056"."REGISTER_07056" ADD CONSTRAINT "PK_NOKTP" PRIMARY KEY ("NOKTP")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ENABLE;
ALTER TABLE "YUSUF_07056"."REGISTER_07056" MODIFY ("NOKTP" NOT NULL ENABLE);
--------------------------------------------------------
-- Constraints for Table TIKET_07056
--------------------------------------------------------
ALTER TABLE "YUSUF_07056"."TIKET_07056" ADD CONSTRAINT "PK_KODETIKET" PRIMARY KEY ("KODETIKET")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "BIOSKOP_07056" ENABLE;
ALTER TABLE "YUSUF_07056"."TIKET_07056" MODIFY ("KODETIKET" NOT NULL ENABLE);
--------------------------------------------------------
-- Ref Constraints for Table JADWAL_07056
--------------------------------------------------------
ALTER TABLE "YUSUF_07056"."JADWAL_07056" ADD CONSTRAINT "FK_KODEFILM" FOREIGN KEY ("KODEFILM")
REFERENCES "YUSUF_07056"."FILM_07056" ("KODEFILM") ENABLE;
--------------------------------------------------------
-- Ref Constraints for Table PELANGGAN_07056
--------------------------------------------------------
ALTER TABLE "YUSUF_07056"."PELANGGAN_07056" ADD CONSTRAINT "FK_NOKTP" FOREIGN KEY ("NOKTP")
REFERENCES "YUSUF_07056"."REGISTER_07056" ("NOKTP") ENABLE;
--------------------------------------------------------
-- Ref Constraints for Table SET_07056
--------------------------------------------------------
ALTER TABLE "YUSUF_07056"."SET_07056" ADD CONSTRAINT "FK_KODEJADWAL" FOREIGN KEY ("KODEJADWAL")
REFERENCES "YUSUF_07056"."JADWAL_07056" ("KODEJADWAL") ENABLE;
ALTER TABLE "YUSUF_07056"."SET_07056" ADD CONSTRAINT "FK_KODETIKET" FOREIGN KEY ("KODETIKET")
REFERENCES "YUSUF_07056"."TIKET_07056" ("KODETIKET") ENABLE;
--------------------------------------------------------
-- Ref Constraints for Table TIKET_07056
--------------------------------------------------------
ALTER TABLE "YUSUF_07056"."TIKET_07056" ADD CONSTRAINT "FK_IDREGISTER" FOREIGN KEY ("IDREGISTER")
REFERENCES "YUSUF_07056"."PELANGGAN_07056" ("IDREGISTER") ENABLE;
<file_sep>/src/form/BeliTiket.java
package form;
import Fungsi.JadwalFilm;
import Fungsi.Setting;
import java.awt.Color;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;
import transaksi.transaksi;
import Fungsi.Pembeli;
import Fungsi.tiket;
public class BeliTiket extends javax.swing.JFrame {
transaksi transaksi;
private ArrayList<Setting> arrset;
private ArrayList<tiket> arrtkt;
private Integer hargatotal;
Pembeli pl;
registrasi re;
String kursi;
/**
* Creates new form pembelian_tiket
*/
public BeliTiket(String i, Integer x) throws SQLException {
initComponents();
tampil(i, x);
this.transaksi = new transaksi();
this.showTableJadwal();
this.hargatotal = 0;
this.arrset = new ArrayList<>();
this.arrtkt = new ArrayList<>();
this.showComboBoxJadwal();
}
BeliTiket() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
public void tampil(String i, Integer x){
namauser.setText(i);
idregi.setText(x.toString());
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
Z2 = new javax.swing.JToggleButton();
Z1 = new javax.swing.JToggleButton();
Z3 = new javax.swing.JToggleButton();
Z4 = new javax.swing.JToggleButton();
Z5 = new javax.swing.JToggleButton();
Z6 = new javax.swing.JToggleButton();
Y1 = new javax.swing.JToggleButton();
Y2 = new javax.swing.JToggleButton();
Y3 = new javax.swing.JToggleButton();
Y4 = new javax.swing.JToggleButton();
Y5 = new javax.swing.JToggleButton();
Y6 = new javax.swing.JToggleButton();
X1 = new javax.swing.JToggleButton();
X2 = new javax.swing.JToggleButton();
X3 = new javax.swing.JToggleButton();
X4 = new javax.swing.JToggleButton();
X5 = new javax.swing.JToggleButton();
X6 = new javax.swing.JToggleButton();
V1 = new javax.swing.JToggleButton();
V2 = new javax.swing.JToggleButton();
V3 = new javax.swing.JToggleButton();
V4 = new javax.swing.JToggleButton();
V5 = new javax.swing.JToggleButton();
V6 = new javax.swing.JToggleButton();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
combotkt = new javax.swing.JComboBox<>();
kodetiket = new javax.swing.JTextField();
jumlah = new javax.swing.JTextField();
kembali = new javax.swing.JLabel();
BELI = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
tbltkt = new javax.swing.JTable();
jMenuBar1.setForeground(new java.awt.Color(255, 255, 255));
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane2.setViewportView(jTable2);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(0, 153, 153));
jPanel1.setForeground(new java.awt.Color(255, 51, 51));
jLabel1.setFont(new java.awt.Font("Agency FB", 1, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("BIOSKOP");
namauser.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N
namauser.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jLabel2.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("FILM");
jLabel3.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("KODE TIKET");
jLabel4.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("JUMLAH");
jLabel5.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("BANGKU");
Z2.setBackground(new java.awt.Color(102, 102, 102));
Z2.setText("Z2");
Z2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Z2ActionPerformed(evt);
}
});
Z1.setBackground(new java.awt.Color(102, 102, 102));
Z1.setText("Z1");
Z1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Z1ActionPerformed(evt);
}
});
Z3.setBackground(new java.awt.Color(102, 102, 102));
Z3.setText("Z3");
Z3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Z3ActionPerformed(evt);
}
});
Z4.setBackground(new java.awt.Color(102, 102, 102));
Z4.setText("Z4");
Z4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Z4ActionPerformed(evt);
}
});
Z5.setBackground(new java.awt.Color(102, 102, 102));
Z5.setText("Z5");
Z5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Z5ActionPerformed(evt);
}
});
Z6.setBackground(new java.awt.Color(102, 102, 102));
Z6.setText("Z6");
Z6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Z6ActionPerformed(evt);
}
});
Y1.setBackground(new java.awt.Color(102, 102, 102));
Y1.setText("Y1");
Y1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Y1ActionPerformed(evt);
}
});
Y2.setBackground(new java.awt.Color(102, 102, 102));
Y2.setText("Y2");
Y2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Y2ActionPerformed(evt);
}
});
Y3.setBackground(new java.awt.Color(102, 102, 102));
Y3.setText("Y3");
Y3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Y3ActionPerformed(evt);
}
});
Y4.setBackground(new java.awt.Color(102, 102, 102));
Y4.setText("Y4");
Y4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Y4ActionPerformed(evt);
}
});
Y5.setBackground(new java.awt.Color(102, 102, 102));
Y5.setText("Y5");
Y5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Y5ActionPerformed(evt);
}
});
Y6.setBackground(new java.awt.Color(102, 102, 102));
Y6.setText("Y6");
Y6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Y6ActionPerformed(evt);
}
});
X1.setBackground(new java.awt.Color(102, 102, 102));
X1.setText("X1");
X1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
X1ActionPerformed(evt);
}
});
X2.setBackground(new java.awt.Color(102, 102, 102));
X2.setText("X2");
X2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
X2ActionPerformed(evt);
}
});
X3.setBackground(new java.awt.Color(102, 102, 102));
X3.setText("X3");
X3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
X3ActionPerformed(evt);
}
});
X4.setBackground(new java.awt.Color(102, 102, 102));
X4.setText("X4");
X4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
X4ActionPerformed(evt);
}
});
X5.setBackground(new java.awt.Color(102, 102, 102));
X5.setText("X5");
X5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
X5ActionPerformed(evt);
}
});
X6.setBackground(new java.awt.Color(102, 102, 102));
X6.setText("X6");
X6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
X6ActionPerformed(evt);
}
});
V1.setBackground(new java.awt.Color(102, 102, 102));
V1.setText("V1");
V1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
V1ActionPerformed(evt);
}
});
V2.setBackground(new java.awt.Color(102, 102, 102));
V2.setText("V2");
V2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
V2ActionPerformed(evt);
}
});
V3.setBackground(new java.awt.Color(102, 102, 102));
V3.setText("V3");
V3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
V3ActionPerformed(evt);
}
});
V4.setBackground(new java.awt.Color(102, 102, 102));
V4.setText("V4");
V4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
V4ActionPerformed(evt);
}
});
V5.setBackground(new java.awt.Color(102, 102, 102));
V5.setText("V5");
V5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
V5ActionPerformed(evt);
}
});
V6.setBackground(new java.awt.Color(102, 102, 102));
V6.setText("V6");
V6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
V6ActionPerformed(evt);
}
});
jPanel2.setBackground(new java.awt.Color(0, 0, 0));
jPanel2.setForeground(new java.awt.Color(102, 102, 102));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 10, Short.MAX_VALUE)
);
jPanel3.setBackground(new java.awt.Color(0, 0, 0));
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 15, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel4.setBackground(new java.awt.Color(0, 0, 0));
jPanel4.setForeground(new java.awt.Color(102, 102, 102));
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 17, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
combotkt.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
kembali.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
kembali.setForeground(new java.awt.Color(255, 255, 255));
kembali.setText("Kembali Ke Login");
kembali.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
kembaliMouseClicked(evt);
}
});
BELI.setBackground(new java.awt.Color(102, 102, 102));
BELI.setForeground(new java.awt.Color(255, 255, 255));
BELI.setText("BELI DAN CETAK");
BELI.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BELIActionPerformed(evt);
}
});
idregi.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jLabel6.setFont(new java.awt.Font("Agency FB", 1, 36)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setText("BIOSKOP");
tbltkt.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4", "Title 5"
}
));
jScrollPane3.setViewportView(tbltkt);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(namauser, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
.addComponent(idregi))
.addGap(14, 14, 14))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel2)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(combotkt, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(kodetiket, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jumlah, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(89, 89, 89)
.addComponent(jLabel5))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(kembali)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(Z1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Z2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Z3))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(V1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(V2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(V3))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(X1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(X2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(X3))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(Y1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Y2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Y3)))
.addGap(58, 58, 58)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(V4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(V5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(V6))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(X4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(X5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(X6))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(Y4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Y5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Y6))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(Z4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Z5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Z6))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(25, 25, 25))
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BELI)
.addGap(70, 70, 70)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(68, 68, 68))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(namauser, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(idregi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(kembali)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(34, 34, 34)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(combotkt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(kodetiket, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jumlah, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(V1)
.addComponent(V2)
.addComponent(V3)
.addComponent(V4)
.addComponent(V5)
.addComponent(V6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(X1)
.addComponent(X2)
.addComponent(X3)
.addComponent(X4)
.addComponent(X5)
.addComponent(X6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Y1)
.addComponent(Y2)
.addComponent(Y3)
.addComponent(Y4)
.addComponent(Y5)
.addComponent(Y6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Z2)
.addComponent(Z1)
.addComponent(Z3)
.addComponent(Z4)
.addComponent(Z5)
.addComponent(Z6)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jLabel5))))
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(BELI)
.addGap(0, 14, Short.MAX_VALUE))
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(24, 24, 24))))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
// public void showtablejad()throws SQLException{
// DefaultTableModel tbljdw = new DefaultTableModel(new String[]{
// "kode jadwal", "nama film", "jam tayang", "tanggal tayang", "ruang"
// },0);
// tbljdw.setRowCount(0);
// for (JadwalFilm jdw : this.transaksi.getDataJadwal()) {
// tbljdw.addRow(new String[]{
// jdw.getkodeljadwal().toString(),
// jdw.getfilm().genamafilm(),
// jdw.getjam(),
// jdw.gettgl().toString(),
// jdw.getruang()
// });
// this.tbltkt.setModel(tbljdw);
// }
// }
private void showTableJadwal() throws SQLException {
DefaultTableModel dtmJadwal = new DefaultTableModel(new String[]{
"kode jadwal", "nama film", "jam tayang", "tanggal tayang", "ruang"
}, 0);
dtmJadwal.setRowCount(0);
for (JadwalFilm jdw : this.transaksi.getDataJadwal()) {
dtmJadwal.addRow(new String[]{
jdw.getKodeTayang().toString(),
jdw.getfilm().getNama_Film(),
jdw.getjam(),
jdw.gettgl().toString(),
jdw.getruang()
});
}
this.tbltkt.setModel(dtmJadwal);
}
private void showComboBoxJadwal() throws SQLException {
DefaultComboBoxModel dcbmJadwal = new DefaultComboBoxModel();
for (JadwalFilm jd : this.transaksi.getDataJadwal()) {
dcbmJadwal.addElement(jd.getKodeTayang().toString() + "||" + jd.getfilm().getNama_Film());
}
this.combotkt.setModel(dcbmJadwal);
}
public void fungsihave(){
Setting sett = new Setting();
try {
sett.setjdwl(this.transaksi.getDataJadwal().get(combotkt.getSelectedIndex()));
this.arrset.add(sett);
} catch (SQLException ex) {
Logger.getLogger(BeliTiket.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void dataset()
{
try {
tiket tkt = new tiket();
Setting sett = new Setting();
sett.setjdwl(this.transaksi.getDataJadwal().get(combotkt.getSelectedIndex()));
this.hargatotal += (this.transaksi.getDataJadwal().get(combotkt.getSelectedIndex()).getfilm().getHarga()* Integer.parseInt(jumlah.getText()));
tkt.setTotal(this.hargatotal);
this.arrtkt.add(tkt);
} catch (SQLException ex) {
Logger.getLogger(transaksi.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void X3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_X3ActionPerformed
// TODO add your handling code here:
kursi = X3.getText();
}//GEN-LAST:event_X3ActionPerformed
private void kembaliMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_kembaliMouseClicked
try {
// TODO add your handling code here:
new LoginPembeli().setVisible(true);
setVisible(false);
} catch (SQLException ex) {
Logger.getLogger(BeliTiket.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_kembaliMouseClicked
public void jadwall(){
}
private void BELIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BELIActionPerformed
tiket trans = new tiket();
try {
// TODO add your handling code here:
this.dataset();
this.fungsihave();
trans.setPel(this.transaksi.get_regis().get(Integer.parseInt(idregi.getText())-1));
System.out.println(idregi.getText());
trans.setKode_Tiket(Integer.parseInt(kodetiket.getText()));
trans.setBanyak(Integer.parseInt(jumlah.getText()));
trans.setarrHave(arrset);
trans.setDuduk(kursi);
trans.setTotal(this.hargatotal);
this.arrtkt.add(trans);
this.transaksi.inserttrans(trans);
new printstruct(trans.getPel().getID()-1).show();
} catch (SQLException ex) {
Logger.getLogger(BeliTiket.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_BELIActionPerformed
private void Z1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Z1ActionPerformed
// TODO add your handling code here:
Z1.setBackground(new Color(204,0,0));
kursi = Z1.getText();
}//GEN-LAST:event_Z1ActionPerformed
private void Z2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Z2ActionPerformed
// TODO add your handling code here:
kursi = Z2.getText();
}//GEN-LAST:event_Z2ActionPerformed
private void Z3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Z3ActionPerformed
// TODO add your handling code here:
kursi = Z3.getText();
}//GEN-LAST:event_Z3ActionPerformed
private void Z4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Z4ActionPerformed
// TODO add your handling code here:
kursi = Z4.getText();
}//GEN-LAST:event_Z4ActionPerformed
private void Z5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Z5ActionPerformed
// TODO add your handling code here:
kursi = Z5.getText();
}//GEN-LAST:event_Z5ActionPerformed
private void Z6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Z6ActionPerformed
// TODO add your handling code here:
kursi = Z6.getText();
}//GEN-LAST:event_Z6ActionPerformed
private void Y1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Y1ActionPerformed
// TODO add your handling code here:
kursi = Y1.getText();
}//GEN-LAST:event_Y1ActionPerformed
private void Y2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Y2ActionPerformed
// TODO add your handling code here:
kursi = Y2.getText();
}//GEN-LAST:event_Y2ActionPerformed
private void Y3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Y3ActionPerformed
// TODO add your handling code here:
kursi = Y3.getText();
}//GEN-LAST:event_Y3ActionPerformed
private void Y4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Y4ActionPerformed
// TODO add your handling code here:
kursi = Y4.getText();
}//GEN-LAST:event_Y4ActionPerformed
private void Y5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Y5ActionPerformed
// TODO add your handling code here:
kursi = Y5.getText();
}//GEN-LAST:event_Y5ActionPerformed
private void Y6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Y6ActionPerformed
// TODO add your handling code here:
kursi = Y6.getText();
}//GEN-LAST:event_Y6ActionPerformed
private void X1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_X1ActionPerformed
// TODO add your handling code here:
kursi = X1.getText();
}//GEN-LAST:event_X1ActionPerformed
private void X2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_X2ActionPerformed
// TODO add your handling code here:
kursi = X2.getText();
}//GEN-LAST:event_X2ActionPerformed
private void X4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_X4ActionPerformed
// TODO add your handling code here:
kursi = X4.getText();
}//GEN-LAST:event_X4ActionPerformed
private void X5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_X5ActionPerformed
// TODO add your handling code here:
kursi = X5.getText();
}//GEN-LAST:event_X5ActionPerformed
private void X6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_X6ActionPerformed
// TODO add your handling code here:
kursi = X6.getText();
}//GEN-LAST:event_X6ActionPerformed
private void V1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_V1ActionPerformed
// TODO add your handling code here:
kursi = V1.getText();
}//GEN-LAST:event_V1ActionPerformed
private void V2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_V2ActionPerformed
// TODO add your handling code here:
kursi = V2.getText();
}//GEN-LAST:event_V2ActionPerformed
private void V3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_V3ActionPerformed
// TODO add your handling code here:
kursi = V3.getText();
}//GEN-LAST:event_V3ActionPerformed
private void V4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_V4ActionPerformed
// TODO add your handling code here:
kursi = V4.getText();
}//GEN-LAST:event_V4ActionPerformed
private void V5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_V5ActionPerformed
// TODO add your handling code here:
kursi = V5.getText();
}//GEN-LAST:event_V5ActionPerformed
private void V6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_V6ActionPerformed
// TODO add your handling code here:
kursi = V6.getText();
}//GEN-LAST:event_V6ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(BeliTiket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BeliTiket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BeliTiket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BeliTiket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new BeliTiket().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BELI;
private javax.swing.JToggleButton V1;
private javax.swing.JToggleButton V2;
private javax.swing.JToggleButton V3;
private javax.swing.JToggleButton V4;
private javax.swing.JToggleButton V5;
private javax.swing.JToggleButton V6;
private javax.swing.JToggleButton X1;
private javax.swing.JToggleButton X2;
private javax.swing.JToggleButton X3;
private javax.swing.JToggleButton X4;
private javax.swing.JToggleButton X5;
private javax.swing.JToggleButton X6;
private javax.swing.JToggleButton Y1;
private javax.swing.JToggleButton Y2;
private javax.swing.JToggleButton Y3;
private javax.swing.JToggleButton Y4;
private javax.swing.JToggleButton Y5;
private javax.swing.JToggleButton Y6;
private javax.swing.JToggleButton Z1;
private javax.swing.JToggleButton Z2;
private javax.swing.JToggleButton Z3;
private javax.swing.JToggleButton Z4;
private javax.swing.JToggleButton Z5;
private javax.swing.JToggleButton Z6;
private javax.swing.JComboBox<String> combotkt;
public static final javax.swing.JTextField idregi = new javax.swing.JTextField();
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jumlah;
private javax.swing.JLabel kembali;
private javax.swing.JTextField kodetiket;
public static final javax.swing.JTextField namauser = new javax.swing.JTextField();
private javax.swing.JTable tbltkt;
// End of variables declaration//GEN-END:variables
}
| d239396584a51e6b7e918a7e4bfb2c4c8952ce4a | [
"Java",
"SQL",
"INI"
]
| 8 | Java | Azrrul/Tiket_Bioskop | 7103ec1f2c0d67aec33e302bd27d859b3c86b2a6 | 177471982655ccacf7de6c9bd4304b5cab1bb557 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using WebApplicationEducation.Models;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
namespace WebApplicationEducation.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IConfiguration _config;
public HomeController(ILogger<HomeController> logger, IConfiguration config)
{
_logger = logger;
_config = config;
}
public IDbConnection Connection
{
get
{
return new SqlConnection(_config.GetConnectionString("DefaultConnection"));
}
}
public IActionResult Index()
{
var users = GetAllUsers();
return View(users);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
private List<User> GetAllUsers()
{
List<User> result;
using (IDbConnection db = Connection)
{
result = db.Query<User>("SELECT * FROM Users").ToList();
}
return result;
}
}
}
| cb13a55eeda11a6dfc08633783115557b47a05c3 | [
"C#"
]
| 1 | C# | Azizjan-leo/MatthewEducation | a52a4dc4a8f56fa531b52ccba2a796728ddb845a | bbad17526b87bb828379dc2183e2ee25028c26d3 |
refs/heads/master | <repo_name>Billliu1993/ExData_Plotting1<file_sep>/plot3.R
## The raw data file has been save to the current working directory
## Load the data into R
DT <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", na.strings = "?")
## Subset the data from 2007-02-01 to 2007-02-02
DT2 <- rbind(DT[DT$Date == "1/2/2007",], DT[DT$Date == "2/2/2007",])
## Checking DT2
## str(DT2)
## 'data.frame': 2880 obs. of 9 variables:
## $ Date : Factor w/ 1442 levels "1/1/2007","1/1/2008",..: 16 16 16 16 16 16 16 16 16 16 ...
## $ Time : Factor w/ 1440 levels "00:00:00","00:01:00",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ Global_active_power : num 0.326 0.326 0.324 0.324 0.322 0.32 0.32 0.32 0.32 0.236 ...
## $ Global_reactive_power: num 0.128 0.13 0.132 0.134 0.13 0.126 0.126 0.126 0.128 0 ...
## $ Voltage : num 243 243 244 244 243 ...
## $ Global_intensity : num 1.4 1.4 1.4 1.4 1.4 1.4 1.4 1.4 1.4 1 ...
## $ Sub_metering_1 : num 0 0 0 0 0 0 0 0 0 0 ...
## $ Sub_metering_2 : num 0 0 0 0 0 0 0 0 0 0 ...
## $ Sub_metering_3 : num 0 0 0 0 0 0 0 0 0 0 ...
## Convert the Date and Time variables to Date/Time classes
DT2$Date <- as.Date(DT2$Date, "%d/%m/%Y")
DT3<-cbind(DT2, "DateTime" = as.POSIXct(paste(DT2$Date, DT2$Time)))
## Plot 3 code
with(DT3, plot(Sub_metering_1 ~ DateTime, type = "l", xlab = "", ylab = "Energy Sub Metering"))
lines(DT3$Sub_metering_2 ~ DT3$DateTime, col = 'Red')
lines(DT3$Sub_metering_3 ~ DT3$DateTime, col = 'Blue')
legend("topright", lty = 1, lwd = 1, col = c("black","red","blue") ,legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
## Export to png
dev.copy(png, file = "plot3.png", width = 480, height = 480)
dev.off() | 0084d9e4b81541ae5c4a7bf7b70b77702a9f0f36 | [
"R"
]
| 1 | R | Billliu1993/ExData_Plotting1 | 5a0d37daff6dac150dccc0ebed15573d9a438ae0 | f190ca1269025c7d5ad0c2d5b8526058e747c6ad |
refs/heads/master | <repo_name>mauroreisvieira/resume<file_sep>/src/js/model/Skill.ts
export default class Skill {
constructor () {}
}
<file_sep>/README.md
# Resume
This repository contains my skills, but you can clone, and change for your skills
## Supported Browsers:
- Google Chrome 62+
### Clone the repo using Git
```bash
git clone https://github.com/mauroreisvieira/resume
```
Alternatively you can [download](https://codeload.github.com/mauroreisvieira/resume/zip/master) this repository.
Created with ♥️ by [@mauroreisvieira](https://twitter.com/mauroreisvieira) in **Portugal**
| c1fca091c342f93dea4fad45dda344a4f982c9bd | [
"Markdown",
"TypeScript"
]
| 2 | TypeScript | mauroreisvieira/resume | 2f240c706d15b68d511b656f27000ca9faa369f0 | 0d69939c87f4af61c45ffb207aed656d8d2ee7a8 |
refs/heads/master | <repo_name>markbayley/blotto<file_sep>/build/precache-manifest.9fce65568ac535f05aa1eb61ecd61a6d.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "00564bf0d0e20bf1613a61dbd629a114",
"url": "./index.html"
},
{
"revision": "15c30f8c26d63e10a63b",
"url": "./static/css/main.14a88dfa.chunk.css"
},
{
"revision": "90616057a82e75d936fa",
"url": "./static/js/2.0e8c5cb0.chunk.js"
},
{
"revision": "15c30f8c26d63e10a63b",
"url": "./static/js/main.cdd826c8.chunk.js"
},
{
"revision": "33830ececaf3e321a603",
"url": "./static/js/runtime-main.b7c5ffbd.js"
}
]); | 39bf0b801ecc610b1849bfdd5d7bc2dbd5da86f3 | [
"JavaScript"
]
| 1 | JavaScript | markbayley/blotto | 45cfccbbbef7050a8f0f0e2b59bb8ddf7274da1a | d1043cc2ffd5d6371393a49e3547319fabaa4a12 |
refs/heads/master | <repo_name>Vollando/DissertationProject<file_sep>/AudioShooter/Assets/Scripts/raycastScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class raycastScript : MonoBehaviour {
CharacterController charCtrl;
AudioSource audioSource;
public AudioClip proximityAudio;
public float newDistance;
public float audiovolume = 0.5f;
// Use this for initialization
void Start ()
{
audioSource = GetComponent<AudioSource>();
audioSource.volume = audiovolume;
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Vector3 cameraRadius = new Vector3(-2, 0, 0);
CharacterController charContr = GetComponent<CharacterController>();
Vector3 p1 = transform.position + charContr.center + cameraRadius * -charContr.height * 0.5f;
Vector3 p2 = p1 + cameraRadius * charContr.height;
float distanceToObstacle = 5;
if (Physics.Raycast(ray, out hit, 5.0f))
{
Debug.DrawLine(ray.origin, hit.point, Color.red);
if (hit.collider.gameObject.tag == "Player")
{
Debug.Log("aiming at other player!");
audioSource.clip = proximityAudio;
audioSource.Play();
}
}
else Debug.Log("");
if (Physics.CapsuleCast(p1, p2, charContr.radius, transform.forward, out hit, 5))
{
newDistance = distanceToObstacle - hit.distance;
for (int i = 0; i < newDistance; i++)
{
audiovolume = newDistance;
}
Debug.Log(newDistance);
}
}
}
<file_sep>/AudioShooter/Assets/Scripts/wallScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class wallScript : MonoBehaviour {
AudioSource audioSource;
public AudioClip wallAudio;
// Use this for initialization
void Start () {
audioSource = GetComponent<AudioSource>();
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
Debug.Log("hit Wall");
audioSource.clip = wallAudio;
audioSource.Play();
}
}
}
<file_sep>/AudioShooter/Assets/Scripts/playerWeaponScript.cs
using UnityEngine;
[System.Serializable]
public class playerWeaponScript {
public int damage = 10;
public float range = 200f;
}
<file_sep>/README.md
# Audio Haptic multiplayer videogaming
## A 3D-Auditory virtual environment to analyse the accessibility of the medium for sighted and visually impaired audiences.
Supervisor: Dr. <NAME>

As the number of players suffering from visual impairments increases due to the expanding games market, there is a need for efficient sensory substitution mechanics that can facilitate a rich mental depiction of the virtual environment. The use of the auditory sense has proven to be an effective approach towards creating a method of interaction for players, and this project proposes a recontextualization of this technique for a multiplayer setting. The reasoning behind this is because of the growing market trends towards multiplayer only games.
In this project implementation, two players are paired against each-other and must process and decode audio information relating to their character position within an environment and convert it into a spatial mentation representation, with the goal of being able to outmaneuver and beat their opponent using traditional first-person shooter gameplay. Results show that a majority of participants found that relying exclusively on the perception of 3D audio cues to be an accessible form of game design, with several players noting the enjoyment of the experience regardless of their visual impairment. This highlights the achievements of the project, with further testing and development being an appropriate measure to ensure the validity of results before inferring to the wider game development community.
<file_sep>/AudioShooter/Assets/Scripts/playerSetupScript.cs
using UnityEngine;
using UnityEngine.Networking;
[RequireComponent(typeof(playerManagerScript))]
public class playerSetupScript : NetworkBehaviour {
[SerializeField]
Behaviour[] componenetsToDisable;
public Behaviour PlayerComponentToDisable;
[SerializeField]
private int remoteLayerName = 9;
Camera sceneCamera;
void Start ()
{
if (!isLocalPlayer)
{
DisableComponents();
AssignRemoteLayer();
}
else
{
PlayerComponentToDisable.enabled = false;
sceneCamera = Camera.main;
if (sceneCamera != null)
{
Camera.main.gameObject.SetActive(false);
}
}
GetComponent<playerManagerScript>().Setup();
}
public override void OnStartClient()
{
base.OnStartClient();
string _netID = GetComponent<NetworkIdentity>().netId.ToString();
playerManagerScript _player = GetComponent<playerManagerScript>();
gameManagerScript.RegisterPlayer(_netID, _player);
}
void DisableComponents ()
{
for (int i = 0; i < componenetsToDisable.Length; i++)
{
componenetsToDisable[i].enabled = false;
}
}
void AssignRemoteLayer ()
{
gameObject.layer = remoteLayerName;
}
void onDisable ()
{
if (sceneCamera != null)
{
sceneCamera.gameObject.SetActive(true);
}
gameManagerScript.UnRegisterPlayer(transform.name);
}
}
| 4a43e8f6604aa7b38c7c8048a06bdfaf578faaac | [
"Markdown",
"C#"
]
| 5 | C# | Vollando/DissertationProject | 9c9e252276dd4cdbbd9ba24f6723f5967b433506 | 0ca4dff3e51076fc264c860cce8f2aeb938beae4 |
refs/heads/master | <repo_name>ssadhuka-broad/MISCASTv1.0<file_sep>/README.md
# MISCASTv1.0
MISCAST (MIssense variant to protein StruCture Analysis web SuiTe; http://miscast.broadinstitute.org/) is a web server to interactively visualize and analyze missense variants in protein sequence and structure space.
The dataset in the current version of MISCAST spans 1,330 human genes, with 406,449 population variants from gnomAD (release 2.1.1, https://gnomad.broadinstitute.org/) and 54,137 variants from the ClinVar (February, 2019 release, pathogenic and likely-pathogenic variants, https://www.ncbi.nlm.nih.gov/clinvar/) and HGMD (Professional release 2018.4, disease mutations, http://www.hgmd.cf.ac.uk/ac/index.php) databases.
The variants are mapped from Ensembl transcript to 17,953 human protein 3D structures from Protein Data Bank (https://www.rcsb.org/).
Further, a comprehensive set of per annotations of protein structural, physicochemical, and functional features per residues were collected from multiple resources spanning DSSP (https://swift.cmbi.umcn.nl/gv/dssp/), PDBsum (http://www.ebi.ac.uk/thornton-srv/databases/cgi-bin/pdbsum/GetPage.pl?pdbcode=index.html), PhosphoSitePlus (https://www.phosphosite.org/homeAction), PANTHER (http://www.pantherdb.org/panther/ontologies.jsp?), UniProt (https://www.uniprot.org/). For the details about feature set annotation and mining, we refer the user to read the documentation page of MISCAST web server.
All annotation tracks (pathogenic and population missense variants and protein features) were subsequently mapped and displayed in protein sequence and structure in the web server.
# MISCASTv1.0 GitHub Repo Content
1. Genes1330_crossrefrences.txt
-- The list of 1,330 genes included in the web server and associated refrences
2. Protein_class_to_gene.txt
-- The list of twenty-four protei functional classe. The genes are grouped into these classes based on the molecular function of the encoded proteins.
3. Gene wise annotation tracks (2 directories)
-- Annotation tracks (pathogenic and population missense variants and forty different protein features) for 1,330 genes
4. app-source-code
-- The R codes to implement the web server
<file_sep>/app-source-code/ui.R
library(shinydashboard)
library(shiny)
library(shinyjs)
library(ggplot2)
library(readr)
library(DT)
library(ggrepel)
library(tm)
library(stringr)
library(shinythemes)
library(dplyr)
library(plyr)
library(tidyr)
library(scales)
library(ggpubr)
library(shinycssloaders)
library(plotly)
library(ggExtra)
library(ggalt)
## java script -- start ##
jsResetCode <- "shinyjs.reset = function() {history.go(0)}"
jscode <- "
shinyjs.runMolart = function(params) {
runMolart(params);
}
shinyjs.runMsa = function(params) {
runMsa(params);
}
shinyjs.disableTab = function(name) {
var tab = $('.nav li a[data-value=' + name + ']');
tab.bind('click.tab', function(e) {
e.preventDefault();
return false;
});
tab.addClass('disabled');
}
"
#a global variable
reload_var <- FALSE
molartContainerId <- "molartContainer"
msaContainerId <- "msaContainer"
## java script -- end ##
## data load -- start ##
#table for genes with protein subclass name and whether it is there as controlled missense or patient missense mutation
pmissOrgmissGene <- read.csv("csvFiles/Gene_Info.csv")
protein_class_def <- read.delim("csvFiles/protein_class_def_genes_counts.txt", header = T, sep = "\t", stringsAsFactors = F, colClasses = "character")
#one category table for all
psuperclass_wise_proteins <- read_delim("data/psuperclass_wise_proteins_prots_genes_with_name.txt", "\t", escape_double = FALSE, trim_ws = TRUE)
psuperclass_wise_proteins$category <- "By Protein Major Class"
func_wise_propteins <- rbind(psuperclass_wise_proteins)
# AA - SS - ASA - PTM property file
gmiss_dssp_ptm <- read.delim("data/gmiss_prp_164915.txt", header = T, sep = "\t", stringsAsFactors = F, colClasses = "character")
pmiss_dssp_ptm <- read.delim("data/pmiss_prp_32924.txt", header = T, sep = "\t", stringsAsFactors = F, colClasses = "character")
gmiss_prp_all <- read_delim("data/gmiss_4907_gene_492755_sav_prop.txt", "\t", escape_double = FALSE, trim_ws = TRUE)
pmiss_dssp_prp <- read_delim("data/pmiss_1330_gene_32923_sav_prop.txt", "\t", escape_double = FALSE, trim_ws = TRUE)
path_genes <- data.frame(unique(pmiss_dssp_prp$geneName))
colnames(path_genes) <- "genename"
gmiss_dssp_prp <- subset(gmiss_prp_all, geneName %in% path_genes$genename)
gmiss_dssp_uniprot <- read_delim("data/gmiss_1330_gene_164915_sav_uniprot_comb.txt", "\t", escape_double = FALSE, trim_ws = TRUE)
pmiss_dssp_uniprot <- read_delim("data/pmiss_1330_gene_32923_sav_uniprot_comb.txt", "\t", escape_double = FALSE, trim_ws = TRUE)
# gene- protein- transcript
GPTLPC_list <- read.delim("csvFiles/GPTLPC_1330.txt", header = T, sep = "\t", stringsAsFactors = F, colClasses = "character")
gene_1330_cv <- as.character(GPTLPC_list[,1])
feature_index_df <- read.delim("csvFiles/feature_index_to_name.txt", header = T, sep = "\t", stringsAsFactors = F, colClasses = "character")
aa_info <- read.delim("csvFiles/aa_info.txt", header = T, sep = "\t", stringsAsFactors = F)
PC24_PF40_pathogenic <- read_delim("data/PC24_PF40_pathogenic.txt", "\t", escape_double = FALSE, trim_ws = TRUE)
colnames(PC24_PF40_pathogenic)[1] <- "pcindex"
colnames(PC24_PF40_pathogenic)[2] <- "pcname"
colnames(PC24_PF40_pathogenic)[3] <- "pcnamelower"
PC24_PF40_population <- read_delim("data/PC24_PF40_population.txt", "\t", escape_double = FALSE, trim_ws = TRUE)
colnames(PC24_PF40_population)[1] <- "pcindex"
colnames(PC24_PF40_population)[2] <- "pcname"
colnames(PC24_PF40_population)[3] <- "pcnamelower"
bond_type_gmiss <- read.csv("csvFiles/bond_type_gmiss.csv")
bond_type_pmiss <- read.csv("csvFiles/bond_type_pmiss.csv")
dist_gmiss <- read.csv("csvFiles/dist_gmiss_new.csv")
dist_pmiss <- read.csv("csvFiles/dist_pmiss_new.csv")
## data load -- end ##
gnomAD_link = paste(c("http://gnomad.broadinstitute.org/", ""), collapse = "")
ClinVar_link = paste(c("https://www.ncbi.nlm.nih.gov/clinvar/", ""), collapse = "")
HGMD_link = paste(c("http://www.hgmd.cf.ac.uk/ac/index.php", ""), collapse = "")
SC_link = paste(c("https://www.broadinstitute.org/stanley", ""), collapse = "")
Broad_link = paste(c("https://www.broadinstitute.org/", ""), collapse = "")
PDB_link = paste(c("https://www.rcsb.org/", ""), collapse = "")
DSSP_link = paste(c("https://swift.cmbi.umcn.nl/gv/dssp/", ""), collapse = "")
PDBsum_link = paste(c("http://www.ebi.ac.uk/thornton-srv/databases/cgi-bin/pdbsum/GetPage.pl?pdbcode=index.html", ""), collapse = "")
SIFTS_link = paste(c("https://www.ebi.ac.uk/pdbe/docs/sifts/", ""), collapse = "")
PANTHER_link = paste(c("http://www.pantherdb.org/panther/ontologies.jsp?", ""), collapse = "")
PPS_link = paste(c("https://www.phosphosite.org/homeAction", ""), collapse = "")
Uniprot_link = paste(c("https://www.uniprot.org/", ""), collapse = "")
navbarPageWithInputs <- function(..., inputs) {
navbar <- navbarPage(...)
form <- tags$form(class = "navbar-form", inputs)
navbar[[3]][[1]]$children[[1]] <- htmltools::tagAppendChild(
navbar[[3]][[1]]$children[[1]], form)
navbar
}
# Define UI for application that draws a histogram
shinyUI(fluidPage(title = "MISCAST",
theme = "styles.css",
tags$head(tags$style("#UBIQstat{background-color: White; text-align: center;}div.box-header {
text-align: center;
}")),
tags$head(tags$style("#ASAstat{background-color: White;text-align: center;}")),
tags$head(tags$style("#RSAstat{background-color: White;text-align: center;}")),
tags$head(tags$style("#ACETstat{background-color: White;text-align: center;}")),
tags$head(tags$style("#GLCNstat{background-color: White;text-align: center;}")),
tags$head(tags$style("#GALNstat{background-color: White;text-align: center;}")),
tags$head(tags$style("#PHOSstat{background-color: White;text-align: center;}")),
tags$head(tags$style("#SUMOstat{background-color: White;text-align: center;}")),
tags$head(tags$style("#METHstat{background-color: White;text-align: center;}")),
#Molart
tags$head(tags$script(src="js/molart.js", type="text/javascript")),
tags$head(tags$script(src="js/molart_controller.js", type="text/javascript")),
tags$head(tags$script(src="js/color.min.js", type="text/javascript")),
#msa.biojs.net
tags$head(tags$script(src="js/msa.min.gz.js", type="text/javascript")),
tags$head(tags$script(src="js/msa_controller.js", type="text/javascript")),
#tags$head(tags$script(type="text/javascript", src="js/custom.js")),
useShinyjs(),
shinyjs::extendShinyjs(text = jsResetCode),
shinyjs::extendShinyjs(text = jscode), #script parameter is not working (can't find the js file)
#I have changed navbarPage with navbarPageWithInputs
navbarPageWithInputs(id = "upperlayer", tags$b("MISCAST"),
tabPanel(value = "page1",
tags$p("Home"),
fluidRow(
column(12, align = 'center',
HTML(paste("<h1><img src = 'miscast.png', height = 100, width = 600></h1>"))
#tags$img(src = 'miscast.png', height = 100, width = 500, align = 'center')
)
),
fluidRow(
HTML(paste("<h1>Welcome to MIssense variant to protein StruCture Analysis web SuiTe</h1>"))
),
fluidRow(
column(2),
column(8, align = 'center',
HTML(
paste(
"<br><br>",
"<color = Black face = Arial align = justify>", "<div align='justify'>",
"<b>MISCAST</b> is developed at the ",
"<a href=", Broad_link, " target=_blank>","Broad Institute","</a>","of ",
"MIT and Harvard, by a combined effort from the Genetics and Therapeutics group of",
"<a href=", SC_link, " target=_blank>","Stanley Center</a>.",
"The goal of MISCAST is to visualize and analyze single amino-acid-altering missense variants on protein sequence and 3-dimensional structure, and thereby forecast their biological impact.",
"<br><br>",
#"The dataset provided on this website spans 1,330 human genes, including 406,449 population variants from <a href = ",gnomAD_link," target=_blank>gnomAD</a> (release 2.1.1), ",
#"54,137 pathogenic variants and disease mutations from the <a href= ",ClinVar_link," target=_blank>ClinVar</a> (February, 2019 release) and <a href= ",HGMD_link," target=_blank>HGMD</a>, (Professional release 2018.4) databases, respectively,", "and >14k molecularly-solved human protein 3D structures from the Protein Data Bank (<a href=",PDB_link," target=_blank>PDB</a>). ",
"The website provides two primary tracks. The <strong>Variant Summary Report</strong> track provides an amino-acid-wise report, summarizing its pathogenic and population variant-associated protein features.",
"The <strong>Variant Analysis Suite</strong> provides a platform for detailed exploration, analysis, and visualization of protein features and missense variants on 1D, 2D and 3D protein structure space.",
"<br><br>",
"<strong>Disclaimer</strong>: <i>Please note that all content on this website is provided for academic and research purposes only. It has not undergone clinical validation, and should not be used for medical advice, diagnosis, or treatment. For best experience, please open Variant Analysis Suite on a laptop/desktop instead of any smaller screen.</i>",
"</div>"
)
)
),
column(2)
),
br(),
fluidRow(
column(2),
column(3, align = 'center',
actionButton(inputId = "reportB",
label = HTML(paste("<font size = +2><strong>Variant Summary Report</strong></font>")),style = "color: white;
background-color: #0059b3; width: 320px;")
)
,
column(3, offset = 2, align = 'center',
actionButton(inputId = "researchB",
label = HTML(paste("<font size = +2><strong>Variant Analysis Suite</strong></font>")),style = "color: white;
background-color: #0059b3; width: 320px;")
),
column(1)
),
br(),
fluidRow(
column(3),
column(6, align = 'center',
tags$a(href = 'https://www.broadinstitute.org/', target='_blank',
tags$img(src = 'BroadInstLogoforDigitalRGB.png', height = 80, width = 300, align = 'center')
),
HTML(paste("<p><span style='font-size: 10pt; color: #000000;'>Copyright © Broad Institute. All rights reserved.</span></p>"))
),
column(3)
)
),
tabPanel(value = "Documentation",tags$p("Documentation"),
mainPanel(style = "background-color: White;",
htmlOutput("doc")
)
),
tabPanel(value = "About",tags$p("About"),
mainPanel(style = "background-color: White;",
htmlOutput("about_page")
)
),
tabPanel(value = "singleTrack",
tags$p("Tracks"),
" ",
div(id = "reportTrackHide", fluidPage(
id = "reportTrack",
mainPanel(width = 12,
fluidRow(
column(3),
column(width = 2, align = 'center', offset = 0, style='padding:6px;', h3("Select Gene:")),
column(width = 3, offset = 0, style='padding:0px;',
selectizeInput(inputId = "reportTgeneSelected", label = "", choices = gene_1330_cv,
options = list(placeholder = "Gene Name",
maxOptions = 3000)
)),
column(1, offset = 0, align = 'center', style='padding:23px;',
actionButton(inputId = "reportTsubmit",
label = "Submit",style = "color: white;
background-color: #0059b3;font-size : 16px;")
)
),
br(),
fluidRow(
#column(10, align = 'center', offset = 0, style='padding:2px;',
div(id = "report_INFOwellpanel",
wellPanel(style = "background-color: White;",
htmlOutput("reportTinformation"),
selectizeInput(inputId = "aa_Selected", label = 'Select Amino Acid Index',
choices = "", width = '300px',
options = list(
placeholder = 'Please select an option below',
onInitialize = I('function() { this.setValue(""); }')
)),
#checkboxInput("checkbox", label = HTML(paste("<strong><i>", "<span style='font-size: 14pt; color: #ff0000;'>", "Please check: All content on this website is provided for academic and research purposes only. It has not undergone clinical validation, and should not be used for medical advice, diagnosis, or treatment.", "</span>", "</i></strong>")), value = FALSE),
div(id = "below_report_INFOwellpanel",
wellPanel(style = "background-color: White;",
#fluidRow(HTML(paste("<strong>"," ", "I) Amino acid information: ", "</strong>"))),
htmlOutput("reportTsummreportHeadlines"),
br(),
br(),
plotOutput("reportTsummreportPlot", width = "80%", height = "550px"),
htmlOutput("reportTsummreport")
#h3("here!")
),
fluidRow(HTML(paste(" ", "<strong>Disclaimer: </strong>", "<i>", "Please note that all content on this website is provided for academic and research purposes only. It has not undergone clinical validation, and should not be used for medical advice, diagnosis, or treatment.", "</i>")))
) %>% shinyjs::hidden()
)
) %>% shinyjs::hidden()
)
)
))%>% shinyjs::hidden(),#fluidpage1
div(id = "researchTrackHide", fluidPage(
id = "researchTrack",
br(),
fluidPage(
fluidRow(
HTML(paste("<h1>Explore Protein Features of Missense Variants by Gene</h1>"))
),
br(),
br(),
fluidRow(
column(3),
column(6, align = 'center',
wellPanel(
style = "background-color: White;",
fluidRow(
column(12, align = 'center',
tabsetPanel(
tabPanel("Select a Gene",
selectizeInput(inputId = "geneSelected", label = "", choices = c("", gene_1330_cv),
options = list(placeholder = "Gene Name",
maxOptions = 3000)
)
)
# ,
# tabPanel("Protein Class",
# selectizeInput(inputId = "pclassNameselected" ,
# label = "",
# choices = c(
# "","Receptor",
# "Signaling Molecule",
# "Kinase",
# "Phosphatase",
# "Protease",
# "Enzyme Modulator",
# "Calcium-Binding Protein",
# "Transcription Factor",
# "Nucleic Acid Binding",
# "Transporter",
# "Transfer/Carrier Protein",
# "Cell Adhesion Molecule",
# "Cytoskeletal Protein",
# "Extracellular Matrix Protein",
# "Cell Junction Protein",
# "Oxidoreductase",
# "Transferase",
# "Hydrolase",
# "Lyase",
# "Isomerase",
# "Ligase",
# "Defense/Immunity protein",
# "Membrane Traffic Protein",
# "Chaperone"
#
# ),
# options = list(placeholder = "Protein Class")
# )
#
# )
,
id = "homeSideBarTabSetPanel"
)
)
)
,
actionButton(inputId = "submit",
label = "Submit",style = "color: white;
background-color: #0059b3; "),
style = "width: 500px;"
)
),
column(3)
)
)
))%>% shinyjs::hidden(),#fluidpage2
div(id = "queryHide", fluidPage(
tabsetPanel(id = 'mainTabset',
tabPanel( value = "Information","Information",
br(),
br(),
fluidRow(
htmlOutput("Information2")
)
),
tabPanel(
value = "1D visualization", "1D visualization",
mainPanel(style = "background-color: White;",
htmlOutput("aaWiseFeatureTableGeneName")
),
fluidRow(
div(id = "aaFeature_wellPanel",
wellPanel(style = "background-color: White;",
htmlOutput("reportTinformation_aaFeat"),
fluidRow(
column(width = 12,
div(id=msaContainerId, class="msa"),
uiOutput("msaResearch")
),
br()
),
shinyjs::hidden(selectizeInput(inputId = "aa_Selected_aaFeat", label = 'Amino Acid Index',
choices = "", width = '300px',
options = list(
placeholder = 'Please select an option below',
onInitialize = I('function() { this.setValue(""); }')
))),
div(id = "below_report_aaFeat_wellPanel",
wellPanel(style = "background-color: White;",
htmlOutput("reportTaafeature")
#h3("here!")
)
) %>% shinyjs::hidden()
)
) %>% shinyjs::hidden()
)
),
tabPanel(value = "2D visualization","2D visualization",
mainPanel(style = "background-color: White;",
htmlOutput("TWODVisGeneName")
),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "3-class Secondary Structure", "</font>"
)
)),
column(5)
),
br(),
br(),
fluidRow(
column(width = 8,offset = 2,
withSpinner(plotlyOutput("SS3loli", height = 500, width = 900
)
)
)
),
br(),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "8-class Secondary Structure", "</font>"
)
)),
column(5)
),
br(),
br(),
fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("SS8loli", height = 500, width = 900))
)
),
br(),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "Accessible Surface Area", "</font>"
)
)),
column(5)
),
br(),
br(),
fluidRow(
column
(width = 8, offset = 2,
withSpinner(plotlyOutput("asaloli", height = 500, width = 900))
)
),
br(),
fluidRow(
column(5),
column(6,htmlOutput("asaplotSummary"))
),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "Twenty Amino Acids and Physiochemical Property", "</font>"
)
)),
column(5)
),
br(),
br(),
fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("chemloli", height = 500, width = 900
))
)
),
br(),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "Protein-protein Interaction types", "</font>"
)
)),
column(5)
),
br(),
fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("bondloli", height = 500, width = 900))
)
),
div(id = "PTMtext",br(),br(),br(),fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "Distance to Post-translational Modification (PTM) Types", "</font>"
)
)),
column(5)
))%>% shinyjs::hidden(),
div(id="Acet",br(),br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("distloliacet", height = 500, width = 900))
)
)) %>% shinyjs::hidden(),
div(id="Met",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("distlolimet", height = 500, width = 900))
)
))%>% shinyjs::hidden(),
div(id="Ogcl",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("distloliogcl", height = 500, width = 900))
)
))%>% shinyjs::hidden(),
div(id="Phos",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("distloliphos", height = 500, width = 900))
)
))%>% shinyjs::hidden(),
div(id="Sumo",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("distlolisumo", height = 500, width = 900))
)
))%>% shinyjs::hidden(),
div(id="Ubiq",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("distloliubiq", height = 500, width = 900))
)
))%>% shinyjs::hidden(),
div(
id = "ptmcaption",br(),
fluidRow(
column(3),
column(8,
htmlOutput("ptmplotsummary")
)
)
)%>% shinyjs::hidden(),
div(id="uniprottext",br(),fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "UniProt-based Functional Features", "</font>"
)
)),
column(5)
))%>% shinyjs::hidden(),
div(id="func_site",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("funclolifs", height = 500, width = 900
))
)
))%>% shinyjs::hidden(),
div(id="mol_proc",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("funclolimolp", height = 500, width = 900
))
)
))%>% shinyjs::hidden(),
div(id="func_bind",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("funclolifbr", height = 500, width = 900
))
)
))%>% shinyjs::hidden(),
div(id="seq_mot",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("funclolismr", height = 500, width = 900
))
)
))%>% shinyjs::hidden(),
div(id="mod_dom",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("funclolimd", height = 500, width = 900
))
)
))%>% shinyjs::hidden(),
div(id="mod_res",br(),fluidRow(
column(width = 8, offset = 2,
withSpinner(plotlyOutput("funclolimr", height = 500, width = 900
))
)
))%>% shinyjs::hidden()
),
tabPanel(value = "3D visualization","3D visualization",
mainPanel(style = "background-color: White;",
htmlOutput("THREEDVisGeneName")
),
fluidRow(
column(width = 12,
div(id=molartContainerId, class="molart"),
uiOutput("molart")
)
)
),
tabPanel(value = "Protein class wise characterization of variants","Protein class wise characterization of variants",
mainPanel(style = "background-color: White;",
htmlOutput("pClassVisGeneName")
),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "3-class Secondary Structure", "</font>"
)
)),
column(5)
),
fluidRow(
br(),
column(6, withSpinner(plotOutput("SS3bar", height = 450, width = 550))),
column(6, withSpinner(plotOutput("SS3forest", height = 500, width = 600))),
br()
),
br(),
br(),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "8-class Secondary Structure", "</font>"
)
)),
column(5)
),
fluidRow(
br(),
column(6, withSpinner(plotOutput("SS8bar", height = 500, width = 600))),
column(6, withSpinner(plotOutput("SS8forest", height = 500, width = 600))),
br()
),
br(),
br(),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "Acessible Surface Area/Residue Exposure", "</font>"
)
)),
column(5)
),
fluidRow(
br(),
column(6, withSpinner(plotOutput("ASAbox", height = 500, width = 600))),
column(6, withSpinner(plotOutput("RSAforest", height = 500, width = 600))),
br()
),
br(),
br(),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "Amino Acids and Physiochemical Property", "</font>"
)
)),
column(5)
),
fluidRow(
br(),
column(6, withSpinner(plotOutput("chemPropbar", height = 500, width = 600))),
column(6, withSpinner(plotOutput("chemPropforest", height = 500, width = 600))),
br()
),
br(),
br(),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "Protein-protein Interactions", "</font>"
)
)),
column(5)
),
fluidRow(
br(),
column(6, withSpinner(plotOutput("BONDbar", height = 500, width = 600))),
column(6, withSpinner(plotOutput("BONDforest", height = 500, width = 600))),
br()
),
br(),
br(),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "Post-translational Modifications (PTMs)", "</font>"
)
)),
column(5)
),
fluidRow(
br(),
column(6, withSpinner(plotOutput("PTMbox", height = 730, width = 630))),
column(6, withSpinner(plotOutput("PTMforest", height = 500, width = 630))),
br()
),
br(),
br(),
br(),
br(),
fluidRow(
column(7, HTML(
paste(
"<font size = +2 color = #0059b3 face = Arial align = left>",
" ", "UniProt-based Functional Features", "</font>"
)
)),
column(5)
),
fluidRow(
br(),
column(6, withSpinner(plotOutput("upFuncBar", height = 500, width = 600))),
column(6, withSpinner(plotOutput("upFuncForest", height = 500, width = 600))),
br()
),
br(),
br(),
br(),
br()
),
tabPanel(
value = "Feature table","Feature table",
fluidRow(
htmlOutput("TablularViewGeneName")
),
fluidRow(column(4),div(style="display:inline-block;vertical-align:top;width:100px;margin-left:10px;",tags$br(tags$h6(align = "left","Select Rows: "))),
div(style="display:inline-block;vertical-align:top;",selectizeInput(inputId = "tableFilterSelected",label = "",choices = c("All amino acids","Amino acids with population variants","Amino acids with pathogenic variants")))
),
fluidRow(column(4),
div(style="display:inline-block;vertical-align:top;width:100px;margin-left:10px;",downloadButton("downloadData", "Download"))
),
br(),
fluidRow(
sidebarPanel(
checkboxGroupInput("show_columns_of_Feature_Table","Select Columns:",
choices = c("Amino Acid Index",
"Amino Acid",
"Population Mutation",
"Population Mutation (details)",
"Pathogenic Mutation",
"Pathogenic Mutation (details)",
"Bond Detail(*)",
"Accessible Surface Area",
"Relative Accessible Surface Area",
"8-class DSSP Secondary Structure Properties",
"3-class DSSP Secondary Structure Properties",
"Exposure",
"Physiochemical Property",
"Acetylation Detail(*)",
"Methylation Detail(*)",
"O.GclNAc Detail(*)",
"Phosphorylation Detail(*)",
"Sumoylation Detail(*)",
"Ubiquitination Detail(*)",
"Active Site",
"Metal Binding Site",
"binding Site",
"Site",
"Zinc Finger",
"Dna Binding",
"Nucleotide Phosphate Binding",
"Calcium Binding",
"Region",
"Repeat",
"Coiled Coil",
"Topological Domain",
"Peptide",
"Modified Residue",
"Motif",
"Domain",
"Intramembrane",
"Propetide",
"Lipidation",
"Glycosylation",
"Cross Links",
"Disulfide Bond",
"Transit Peptide",
"Transmembrane",
"Signal Peptide",
"Functional Site",
"Functional Binding Region",
"Sequence Motif Region",
"Modular Domain",
"Molecular Processing",
"Modified Residues"
),
selected = c("Amino Acid Index",
"Amino Acid",
"Population Mutation",
"Pathogenic Mutation")
)
),
column(8,div(DT::dataTableOutput("full_gene_wise_info"),style = "font-size:70%")),
column(8,div(DT::dataTableOutput("gnomad_gene_wise_info"),style = "font-size:70%")),
column(8,div(DT::dataTableOutput("patient_gene_wise_info"),style = "font-size:70%"))
,
br(),
fluidRow(
column(4),
column(7,htmlOutput("FeatureTableSummary"))
)
)
),
tabPanel(
value = "Index table","Index table",
#mainPanel(style = "background-color: White;",
# htmlOutput("IndexTablularViewGeneName")
#),
fluidRow(
htmlOutput("IndexTablularViewGeneName")
),
fluidRow(column(4),div(style="display:inline-block;vertical-align:top;width:100px;margin-left:10px;",tags$br(tags$h6(align = "left","Select Rows: "))),
div(style="display:inline-block;vertical-align:top;",selectizeInput(inputId = "indextableFilterSelected",label = "",choices = c("All amino acids","Amino acids with structure")))
#column(1,radioButtons("indexTablefiletype", "File type:",choices = c("csv", "txt")))
),
fluidRow(column(4),
div(style="display:inline-block;vertical-align:top;width:100px;margin-left:10px;",downloadButton("indexTabledownloadData", "Download"))
),
fluidRow(
sidebarPanel(
checkboxGroupInput("show_columns_of_Index_Table","Select Columns:",choices = c(
"Amino Acid Index in Protein Sequence",
"Amino Acid",
"Genomic Index of the Amino Acid",
"Structure Index of the Amino Acid"),
selected = c(
"Amino Acid Index in Protein Sequence",
"Amino Acid",
"Genomic Index of the Amino Acid",
"Structure Index of the Amino Acid"
)
)
)
,
column(8,div(DT::dataTableOutput("structure_gene_wise_info"),style = "font-size:70%")),
column(8,div(DT::dataTableOutput("structure_all_gene_wise_info"),style = "font-size:70%"))
),
br(),
fluidRow(
column(4),
column(7,htmlOutput("IndexTableSummary"))
)
)
)
))%>% shinyjs::hidden()#query page
)
,
inputs = fluidRow(
div(style="display: inline-block;vertical-align:top; width: 250px;",selectInput(inputId = "trackInput",label = NULL, choices = c("","Variant Summary Report","Variant Analysis Suite"))),
div(style="display: inline-block;vertical-align:top; width: 100px;",actionButton(inputId = 'trackButton',label = "Select Track", padding='12px', style = "color: white; background-color: #0059b3;font-size : 14px;"))
)
)
)
) | 1463acdb40663deec15bb61559a8ca7100c15f29 | [
"Markdown",
"R"
]
| 2 | Markdown | ssadhuka-broad/MISCASTv1.0 | f086b8e60403e26362c721277a383110d19c6fd7 | 34a69351975c2711cec76e74df723f952f0bcdf0 |
refs/heads/master | <repo_name>tjking20/rupee-collector<file_sep>/README.md
# Rupee Collector!
## Description
In this game the client attempts to match the reandom number generated by the computer. Each of the rupees contains a randomly generated value which adds to the score when clicked. If the client score matches the target score, the user wins, if the client score exceeds the target number, a loss is added. After each round the user score, the target number, and the rupee values reset.

## Technologies
- HTML5
- CSS
- JavaScript
- jQuery
## Heroku
https://rupee-collector.herokuapp.com/
<file_sep>/assets/script.js
$(document).ready(function() {
var score = 0;
var wins = 0;
var losses = 0;
var targetNumber = '';
var value = '';
// The reset function assigns a random target number and random values to all rupees
function reset(){
function randomOption(){
targetNumber = Math.floor(Math.random() * (120-19)+19);
$("#targetNumber").html(targetNumber);
}
function randomVal(btn){
value = Math.floor(Math.random() * (10 - 1) + 1);
$(btn).attr("data-value", value);
}
randomOption();
randomVal("#button1");
randomVal("#button2");
randomVal("#button3");
randomVal("#button4");
score = 0;
$("h3").html("0");
}
reset();
// this onclick event effects the btn class by adding their values into the player's score.
$(document).on("click", ".btn", function(){
score += parseInt($(this).attr("data-value"));
$("h3").html(score);
// Conditional increments wins and losses, and resets the game.
if(score == targetNumber){
wins++;
$("#wins").html("Wins: " + wins);
reset();
}else if (score > targetNumber){
losses++;
$("#losses").html("Losses: " + losses);
reset();
}
});
$("#toggle-button").on("click", function(){
$("p").slideToggle(750);
});
}); | 435c38d8afed28cf72aad869c230f723523230cf | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | tjking20/rupee-collector | 0f9cfd8dd43e859b8e2dd70bb7852858d372a06f | e82c547fd61341f9fe2dae22384f51e6ec2d0946 |
refs/heads/master | <repo_name>yinjian318/x-admin<file_sep>/src/main/java/com/dao/AccountMapper.java
package com.dao;
import com.model.Account;
import org.apache.ibatis.annotations.Param;
public interface AccountMapper {
int deleteByPrimaryKey(Long accountId);
int insert(Account record);
int insertSelective(Account record);
Account selectByPrimaryKey(Long accountId);
Account selcetCheck(@Param("loginAccount")String loginAccount,@Param("password")String password);
int updateByPrimaryKeySelective(Account record);
int updateByPrimaryKey(Account record);
}<file_sep>/src/main/java/com/interceptor/XssFilter.java
package com.interceptor;
import com.web.XssHttpServletRequestWrapper;
import org.apache.commons.lang.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 防御跨站脚本攻击[XSS]filter
* @author lei.niu
*
*/
public class XssFilter implements Filter {
protected static final String REFERER = "Referer";
protected static final String LOGINURL_PARAM = "loginurl";
protected static final String INCLUDES_PARAM = "includes";
FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
String includes = filterConfig.getInitParameter(INCLUDES_PARAM);
String loginurl = filterConfig.getInitParameter(LOGINURL_PARAM);
String referer=request.getHeader(REFERER);
if(isCheckDomianName(includes,loginurl,referer)) {
chain.doFilter(new XssHttpServletRequestWrapper(request), response);
}else{
//域名检查失败,返回登录页
response.sendRedirect(loginurl);
}
}
/**
* 检查请求来源合法是否合法?
* (防Referer攻击)
* @return 合法:true 非法:false
*/
private boolean isCheckDomianName(String includes,String loginurl,String referer){
if(StringUtils.isEmpty(includes) || StringUtils.isEmpty(loginurl)) return true;//当includes参数为空不进行拦截
if(StringUtils.isEmpty(referer)) return true; //当referer参数为空不进行拦截
if(loginurl.contains("127.0.0.1")){
referer = referer.replace("localhost","127.0.0.1");
}
String[] incluedsArray = includes.split("\\|");
if(incluedsArray.length>0){
for(int i=0;i<incluedsArray.length;i++){
if(referer.equals(incluedsArray[i]) || referer.startsWith(incluedsArray[i])){
return true;
}
}
}else{
return true;
}
return false;
}
}<file_sep>/src/main/java/com/service/MemberService.java
package com.service;
import com.model.Member;
import java.util.List;
import java.util.Map;
/**
* Created by YINJIAN on 2018/2/5.
*/
public interface MemberService {
Map<String,Object> updateByPrimaryKey();
Member selectByPrimaryKey(Long memberid);
List<Member> selectAll(Member record);
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yinjian</groupId>
<artifactId>x-admin</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>x-admin Maven Webapp</name>
<url>http://maven.apache.org</url>
<distributionManagement>
<repository>
<id>nexus-releases</id>
<name>Nexus Releases Repository</name>
<url>http://oumi520.com:8081/nexus/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<name>Nexus Snapshots Repository</name>
<url>http://oumi520.com:8081/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
<repositories>
<repository>
<id>Nexus</id>
<name>Nexus</name>
<url>http://oumi520.com:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- spring版本号 -->
<spring.version>4.3.6.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.6</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.7.5</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.1</version>
</dependency>
<!--Apache Commons Upload-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!--Apache Commons Upload-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!-- <dependency>
<groupId>com.aliyun.openservices</groupId>
<artifactId>ons-client</artifactId>
<version>1.7.0.Final</version>
</dependency>-->
<!-- <dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.2</version>
</dependency>-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<finalName>x-damin</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.7.2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/src/main/java/com/model/Resource.java
package com.model;
import java.util.Date;
public class Resource {
private Long resourceId;
private Long parentId;
private String resourceCode;
private String resourceName;
private Short resourceType;
private String resourceUrl;
private String iconUrl;
private String iconName;
private Short hasChild;
private Short delFlag;
private Date createTime;
private Long createUserId;
private String createUserAccount;
private String createUserName;
private Date updateTime;
private Long updateUserId;
private String updateUserAccount;
private String updateUserName;
private String reserve01;
private String reserve02;
private String reserve03;
private String reserve04;
private String reserve05;
private String reserve06;
private String reserve07;
private String reserve08;
private String reserve09;
private String reserve10;
public Resource(Long resourceId, Long parentId, String resourceCode, String resourceName, Short resourceType, String resourceUrl, String iconUrl, String iconName, Short hasChild, Short delFlag, Date createTime, Long createUserId, String createUserAccount, String createUserName, Date updateTime, Long updateUserId, String updateUserAccount, String updateUserName, String reserve01, String reserve02, String reserve03, String reserve04, String reserve05, String reserve06, String reserve07, String reserve08, String reserve09, String reserve10) {
this.resourceId = resourceId;
this.parentId = parentId;
this.resourceCode = resourceCode;
this.resourceName = resourceName;
this.resourceType = resourceType;
this.resourceUrl = resourceUrl;
this.iconUrl = iconUrl;
this.iconName = iconName;
this.hasChild = hasChild;
this.delFlag = delFlag;
this.createTime = createTime;
this.createUserId = createUserId;
this.createUserAccount = createUserAccount;
this.createUserName = createUserName;
this.updateTime = updateTime;
this.updateUserId = updateUserId;
this.updateUserAccount = updateUserAccount;
this.updateUserName = updateUserName;
this.reserve01 = reserve01;
this.reserve02 = reserve02;
this.reserve03 = reserve03;
this.reserve04 = reserve04;
this.reserve05 = reserve05;
this.reserve06 = reserve06;
this.reserve07 = reserve07;
this.reserve08 = reserve08;
this.reserve09 = reserve09;
this.reserve10 = reserve10;
}
public Resource() {
super();
}
public Long getResourceId() {
return resourceId;
}
public void setResourceId(Long resourceId) {
this.resourceId = resourceId;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getResourceCode() {
return resourceCode;
}
public void setResourceCode(String resourceCode) {
this.resourceCode = resourceCode == null ? null : resourceCode.trim();
}
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName == null ? null : resourceName.trim();
}
public Short getResourceType() {
return resourceType;
}
public void setResourceType(Short resourceType) {
this.resourceType = resourceType;
}
public String getResourceUrl() {
return resourceUrl;
}
public void setResourceUrl(String resourceUrl) {
this.resourceUrl = resourceUrl == null ? null : resourceUrl.trim();
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl == null ? null : iconUrl.trim();
}
public String getIconName() {
return iconName;
}
public void setIconName(String iconName) {
this.iconName = iconName == null ? null : iconName.trim();
}
public Short getHasChild() {
return hasChild;
}
public void setHasChild(Short hasChild) {
this.hasChild = hasChild;
}
public Short getDelFlag() {
return delFlag;
}
public void setDelFlag(Short delFlag) {
this.delFlag = delFlag;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Long getCreateUserId() {
return createUserId;
}
public void setCreateUserId(Long createUserId) {
this.createUserId = createUserId;
}
public String getCreateUserAccount() {
return createUserAccount;
}
public void setCreateUserAccount(String createUserAccount) {
this.createUserAccount = createUserAccount == null ? null : createUserAccount.trim();
}
public String getCreateUserName() {
return createUserName;
}
public void setCreateUserName(String createUserName) {
this.createUserName = createUserName == null ? null : createUserName.trim();
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Long getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(Long updateUserId) {
this.updateUserId = updateUserId;
}
public String getUpdateUserAccount() {
return updateUserAccount;
}
public void setUpdateUserAccount(String updateUserAccount) {
this.updateUserAccount = updateUserAccount == null ? null : updateUserAccount.trim();
}
public String getUpdateUserName() {
return updateUserName;
}
public void setUpdateUserName(String updateUserName) {
this.updateUserName = updateUserName == null ? null : updateUserName.trim();
}
public String getReserve01() {
return reserve01;
}
public void setReserve01(String reserve01) {
this.reserve01 = reserve01 == null ? null : reserve01.trim();
}
public String getReserve02() {
return reserve02;
}
public void setReserve02(String reserve02) {
this.reserve02 = reserve02 == null ? null : reserve02.trim();
}
public String getReserve03() {
return reserve03;
}
public void setReserve03(String reserve03) {
this.reserve03 = reserve03 == null ? null : reserve03.trim();
}
public String getReserve04() {
return reserve04;
}
public void setReserve04(String reserve04) {
this.reserve04 = reserve04 == null ? null : reserve04.trim();
}
public String getReserve05() {
return reserve05;
}
public void setReserve05(String reserve05) {
this.reserve05 = reserve05 == null ? null : reserve05.trim();
}
public String getReserve06() {
return reserve06;
}
public void setReserve06(String reserve06) {
this.reserve06 = reserve06 == null ? null : reserve06.trim();
}
public String getReserve07() {
return reserve07;
}
public void setReserve07(String reserve07) {
this.reserve07 = reserve07 == null ? null : reserve07.trim();
}
public String getReserve08() {
return reserve08;
}
public void setReserve08(String reserve08) {
this.reserve08 = reserve08 == null ? null : reserve08.trim();
}
public String getReserve09() {
return reserve09;
}
public void setReserve09(String reserve09) {
this.reserve09 = reserve09 == null ? null : reserve09.trim();
}
public String getReserve10() {
return reserve10;
}
public void setReserve10(String reserve10) {
this.reserve10 = reserve10 == null ? null : reserve10.trim();
}
}<file_sep>/src/main/java/com/dao/MemberMapper.java
package com.dao;
import com.model.Member;
import java.util.List;
public interface MemberMapper {
int deleteByPrimaryKey(Long memberid);
int insert(Member record);
int insertSelective(Member record);
Member selectByPrimaryKey(Long memberid);
int updateByPrimaryKeySelective(Member record);
int updateByPrimaryKey(Member record);
List<Member> selectAll(Member record);
}<file_sep>/src/main/webapp/js/common1.js
$(function(){
var page = $("#page").val();var totlepage = $("#totlepage").val();
var url = $("form").attr("action");var parame = "&" + $("form").serialize();
localStorage.setItem("tolpage",totlepage)
localStorage.setItem("pag",page)
localStorage.setItem("parames",parame)
if(url){
if(url.indexOf("?") > 0){
url = url + "&";
}else{
url = url + "?";
}
localStorage.setItem("urls",url)
setTimeout(function(){
paging(page,totlepage, url, parame);
},1)
$ ('body').delegate('#page_input','keypress',function (){
return (/[\d]/.test(String.fromCharCode(event.keyCode)))
});
}
});
//跳转到指定页数
function gotoPage(){
var flag = true;
totlepage = localStorage.getItem("tolpage")
url = localStorage.getItem("urls")
parame = localStorage.getItem("parames")
var forPageNum = parseInt($("#page_input").val())
if(1 > forPageNum){
forPageNum = 1;
$("#page_input").val(forPageNum)
flag = false;
}
if(totlepage < forPageNum){
forPageNum = totlepage;
$("#page_input").val(forPageNum)
}
if(forPageNum == "" || forPageNum == " " || isNaN(forPageNum)){
forPageNum = 1;
flag = false;
}
if(flag){
if(totlepage){
window.location.href = url + "pageNo=" + forPageNum + parame;
}
}
}
/**
* Created by DC on 2016/9/5.
*/
function paging(page,totlepage,url,parame){
var paging = {
page : parseInt(page),
totlepage : parseInt(totlepage),
url : url,
pNo :'pageNo=',
parame : parame
}
if(paging.totlepage == null || paging.totlepage == 0 || paging.totlepage == "" || isNaN(paging.totlepage)){
paging.totlepage = 1;
paging.page = 1;
}
var prev = $("#prev").val();
var next = $("#next").val();
var totlepage = $("#totlepage").val();
var html = "";
if(paging.totlepage == 0 || paging.totlepage == null){
html = '<a href="javascript:void(0)" class="mgr15" style="width:auto;">共<strong>0</strong>页</a>';
}else{
html = '<a href="javascript:void(0)" class="mgr15" style="width:auto;">共<strong>'+paging.totlepage+'</strong>页</a>';
}
if(paging.page<=1){
html+='<a href="javascript:void(0)" class="no_up_btn"> 上一页</a>';
}else{
html+='<a href="'+paging.url+paging.pNo+prev+paging.parame+'"class="up_btn">上一页</a>'
}
if(paging.totlepage < 8){
for(var i=1;i<paging.totlepage+1;i++){
if(i == paging.page){
html += '<span class="on"> <a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+i+paging.parame+'">'+i+'</a></span>'
}else{
html += '<span> <a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+i+paging.parame+'">'+i+'</a> </span>'
}
}
}else{
if(paging.totlepage <= paging.page+2){
html += '<span><a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+1+paging.parame+'">1</a> </span><span><a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+2+paging.parame+'">2</a></span><span class="point"><a href="javascript:;">...</a></span>';
for(var i=paging.totlepage-5;i<paging.totlepage+1;i++){
if(i == paging.page){
html += '<span class="on"> <a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+i+paging.parame+'">'+i+'</a></span>'
}else{
html += '<span> <a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+i+paging.parame+'">'+i+'</a> </span>'
}
}
}else{
if(paging.page-2 > 3){
html += '<span><a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+1+paging.parame+'">1</a> </span><span><a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+2+paging.parame+'">2</a></span><span class="point"><a href="javascript:;">...</a></span>';
for(var i=paging.page-2;i<paging.page+3;i++){
if(i == paging.page){
html += '<span class="on"> <a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+i+paging.parame+'">'+i+'</a></span>'
}else{
html += '<span> <a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+i+paging.parame+'">'+i+'</a> </span>'
}
}
html += '<span class="point"><a href="javascript:void(0)">...</a></span>';
}else{
for(var i=1;i<8;i++){
if(i == paging.page){
html += '<span class="on"> <a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+i+paging.parame+'">'+i+'</a></span>'
}else{
html += '<span> <a style="display:inline-block;text-align:center;" href="'+paging.url+paging.pNo+i+paging.parame+'">'+i+'</a> </span>'
}
}
html += '<span class="point"><a href="javascript:void(0)">...</a></span>';
}
}
}
if(paging.page<paging.totlepage){
html += '<a href="'+paging.url+paging.pNo+next+paging.parame+'" class="next_btn">下一页</a>';
}else{
html += '<a href="javascript:void(0)" class="no_next_btn">下一页</a>'
}
html += '<span style="margin-left: 5px;width:auto;border:none;background: #fff;">到第 <input type="number" value="1" id="page_input" class="page_input"> 页 </span> <button class="confrim" style="margin-left:10px;" onclick="gotoPage()">确定</button>'
document.getElementById("paging").innerHTML = html;
} | 9433a35b9dbf4dfd6feeb1559da893af8a34179e | [
"JavaScript",
"Java",
"Maven POM"
]
| 7 | Java | yinjian318/x-admin | 3304a80ccd887a65c497d1d67152749010372775 | 044f1364a5093d4a04f8a43320172363954696ca |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.