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># Stripe-With-Node-js<file_sep>const stripe = require("stripe")(process.env.STRIPE_API_KEY);
const createCustomer = async (email, name) => {
try {
const customer = await stripe.customers.create({
email,
name
});
return customer;
} catch (err) {
throw err;
}
};
const createPaymentMethod = async (number, exp_month, exp_year, cvc) => {
try {
const paymentMethod = await stripe.paymentMethods.create({
type: "card",
card: {
number,
exp_month,
exp_year,
cvc
}
});
return paymentMethod;
} catch (err) {
throw err;
}
};
const attachPaymentMethod = async (payment_method_id, customer) => {
try {
const attachedPaymentMethod = await stripe.paymentMethods.attach(
payment_method_id,
{
customer
}
);
return attachedPaymentMethod;
} catch (err) {
throw err;
}
};
const createPaymentIntent = async (amount, customer, payment_method) => {
try {
const createdPaymentIntent = await stripe.paymentIntents.create({
amount,
currency: "usd",
customer,
payment_method
});
return createdPaymentIntent;
} catch (err) {
throw err;
}
};
const confirmCardPayment = async payment_intent_id => {
try {
const confirmedPayment = await stripe.paymentIntents.confirm(
payment_intent_id
);
return confirmedPayment;
} catch (err) {
throw err;
}
};
const createTransfer = async (amount, destination, transfer_group) => {
try {
const createdTransfer = await stripe.transfers.create({
amount,
currency: "usd",
destination,
transfer_group
});
return createdTransfer;
} catch (err) {
throw err;
}
};
const createAccount = async email => {
try {
const createdAccount = await stripe.accounts.create({
type: "custom",
country: "US",
email,
requested_capabilities: ["card_payments", "transfers"]
});
return createdAccount;
} catch (err) {
throw err;
}
};
module.exports = {
createCustomer,
createPaymentMethod,
attachPaymentMethod,
createPaymentIntent,
confirmCardPayment,
createAccount,
createTransfer
};
|
fd21868740a791c61139be94de09d8f6f7a7e2fe
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Syed-Kashan-Adil/Stripe-With-Node-js
|
f2a036357d40380570877d1406f3d79d1f20dbd3
|
8c810714f6c1135f105744dfaf38ccb9239e67d9
|
refs/heads/master
|
<file_sep>package com.ibm.swing;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Add2Num extends JFrame implements ActionListener{
JTextField t1,t2;
JButton btn;
JLabel l;
public Add2Num() {
// TODO Auto-generated constructor stub
t1=new JTextField(20);
t2=new JTextField(20);
btn=new JButton("OK");
l=new JLabel("RESULT");
btn.addActionListener(this);//ActionListener is an interface
add(t1);
add(t2);
add(btn);
add(l);
setVisible(true);
setSize(400,400);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent ev) {
// TODO Auto-generated method stub
int num1=Integer.parseInt(t1.getText());
int num2=Integer.parseInt(t2.getText());
int value=num1+num2;
l.setText(value+"");
}
}
<file_sep>package com.ibm.swing;
public class FirstSwingDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
HelloWorld obj=new HelloWorld();
}
}
<file_sep>package com.ibm.swing;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
//CardLayout one component override old component
public class HelloWorld extends JFrame {
public HelloWorld() {
// TODO Auto-generated constructor stub
setVisible(true);
setSize(400,400);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//follow default CardLayout which override old component with new component
//thats why we have to explicitly set the layout then we can able to see all the component
JLabel l=new JLabel("Hello World");
JLabel l1=new JLabel("Welcome Shital");
add(l);
add(l1);
}
}
<file_sep>package com.ibm.string;
public interface Appraisable {
//by default all methods are default
public void appraise();
//by default all variable are constants
}
|
41b5622fc1d7f11f7b869e3cc7d225dca9dff89a
|
[
"Java"
] | 4
|
Java
|
shitaljagdale/ClassRoom-trainning-Java-Programs
|
fd6bc4ab7f1a9f701f8e2dabff5102cac205e23f
|
7ab9f6b1bb5b53d2ffbbf075aaebfb8701dec74b
|
refs/heads/master
|
<repo_name>joesus/dotfiles<file_sep>/zsh/zsh-aliases.zsh
################
# Global aliases
################
alias reload!='source ~/.zshrc'
alias -g ...='../..'
alias -g ....='../../..'
alias -g .....='../../../..'
alias -g C='| wc -l'
alias -g H='| head'
alias -g L="| less"
alias -g N="| /dev/null"
alias -g S='| sort'
alias -g G='| grep' # now you can do: ls foo G something
alias rmDerived='rm -rf ~/library/Developer/Xcode/DerivedData/*'
##########################
# Global environment vars
#########################
# RbEnv Stuff
export PATH="$HOME/.rbenv/bin:$PATH"
export PATH="$HOME/.rbenv/shims:$PATH"
if which rbenv > /dev/null; then eval "$(rbenv init - zsh)"; fi
###########
# Functions
###########
#
# (f)ind by (n)ame
# usage: fn foo
# to find all files containing 'foo' in the name
function fn() { ls **/*$1* }
# Boot2Docker
docker-ip() {
boot2docker ip 2> /dev/null
}
# grabs your ip address
function hosts
{
file=/etc/hosts
if [ -e $file ]; then
ip=`ifconfig | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' | awk 'NR==1{ print $2}'`
if ! grep -x ".*[[:space:]]*laptop$" $file; then
echo "$ip laptop" | sudo tee -a $file
else
sudo sed -i '.bak' "s/.*[[:space:]]*laptop$/$ip laptop/" $file
fi
fi
}
function ipaddr
{
ifconfig | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' | awk 'NR==1{ print $2}'
}
# Jenkins
triggerBuild() {
REPO="$1"
BRANCH="$2"
curl -g "http://jenkins.dev-utopia.com/git/notifyCommit?url=ssh://git@stash.<EMAIL>.com/projects/ITH/repos/$REPO.git&branch=$BRANCH"
}
|
0a7ac3e04bfe25a87d9de129c808400b562f1171
|
[
"Shell"
] | 1
|
Shell
|
joesus/dotfiles
|
852271cbe9a9d689ad303e9849e9404cdd3b39ac
|
374e78709399b3e54018d11a704c502786ac008c
|
refs/heads/main
|
<file_sep>import { useEffect, useMemo, useRef, useState } from 'react'
import { Redirect, useParams } from 'react-router-dom'
import io from 'socket.io-client'
function GamePage() {
const { gameId } = useParams()
const [socket, setSocket] = useState(null)
const [joinFailed, setJoinFailed] = useState(false)
const [side, setSide] = useState()
const [pieces, setPieces] = useState([])
const [absPos, setAbsPos] = useState({ position: 'absolute', top: 0, left: 0 })
const [draggedPiece, setDraggedPiece] = useState(null)
const squares = useMemo(() => {
const squares = []
for (let i = 0; i < 64; i++) {
const square = {}
// set square.id using algebraic notation
const row = Math.floor(i / 8)
const col = i % 8
square.id = (side === 'white') ? 'abcdefgh'[col] + (8 - row) : 'hgfedcba'[col] + (row + 1)
// if there is a piece on this square, add a reference to the piece object
square.piece = null
pieces.forEach((piece) => {
if (piece.square === square.id) {
square.piece = piece
}
})
squares.push(square)
}
return squares
}, [pieces, side])
// initialize socket, connect to game
useEffect(() => {
const mySocket = io()
mySocket.emit('join', gameId)
mySocket.on('join failed', (reason) => {
console.log('join failed: ' + reason)
setJoinFailed(true) // will cause redirect to home
})
mySocket.on('game data', (game) => {
if (game.white === mySocket.id) {
setSide('white')
} else if (game.black === mySocket.id) {
setSide('black')
}
setPieces(game.pieces)
})
setSocket(mySocket)
return function cleanup() {
mySocket.disconnect()
}
}, [gameId])
// using native DOM events to allow preventDefault() with TouchEvents (non-passive)
// these events are for drag-and-dropping pieces
const page = useRef()
useEffect(() => {
const trackPointer = (e) => {
// update the absolute position styling applied to the dragged piece
const offset = Math.min(window.innerWidth, window.innerHeight) / 16
const x = e.changedTouches ? e.changedTouches[0].pageX : e.pageX
const y = e.changedTouches ? e.changedTouches[0].pageY : e.pageY
setAbsPos({
position: 'absolute',
left: x - offset + 'px',
top: y - offset + 'px'
})
}
const startDrag = (e) => {
// find the square the pointer is over
const pointerX = e.changedTouches ? e.changedTouches[0].clientX : e.clientX
const pointerY = e.changedTouches ? e.changedTouches[0].clientY : e.clientY
const elementId = document.elementFromPoint(pointerX, pointerY).id
const square = squares.find((square) => square.id === elementId)
if (square && square.piece) {
// start dragging the piece on the square
e.preventDefault()
setDraggedPiece(square.piece)
trackPointer(e)
}
}
const endDrag = (e) => {
if (draggedPiece) {
// find the square the pointer is over
e.preventDefault()
const pointerX = e.changedTouches ? e.changedTouches[0].clientX : e.clientX
const pointerY = e.changedTouches ? e.changedTouches[0].clientY : e.clientY
const elementId = document.elementFromPoint(pointerX, pointerY).id
const square = squares.find((square) => {
return square.id === elementId
})
if (square && !square.piece) {
// set the dropped piece's new square
const previousSquare = draggedPiece.square
setPieces((pieces) => {
const newPieces = pieces.slice()
const index = newPieces.indexOf(draggedPiece)
newPieces[index] = Object.assign(draggedPiece, { square: square.id })
return newPieces
})
// send the move to server
socket.emit('move', previousSquare, square.id)
}
setDraggedPiece(null)
}
}
const moveDrag = (e) => {
if (draggedPiece) {
e.preventDefault()
trackPointer(e)
}
}
const pageElement = page.current
pageElement.addEventListener('touchmove', moveDrag, { passive: false })
pageElement.addEventListener('mousemove', moveDrag)
pageElement.addEventListener('touchstart', startDrag, { passive: false })
pageElement.addEventListener('mousedown', startDrag)
pageElement.addEventListener('touchend', endDrag, { passive: false })
pageElement.addEventListener('mouseup', endDrag)
return (() => {
pageElement.removeEventListener('touchmove', moveDrag, { passive: false })
pageElement.removeEventListener('mousemove', moveDrag)
pageElement.removeEventListener('touchstart', startDrag, { passive: false })
pageElement.removeEventListener('mousedown', startDrag)
pageElement.removeEventListener('touchend', endDrag, { passive: false })
pageElement.removeEventListener('mouseup', endDrag)
})
}, [squares, draggedPiece, socket])
return (
<div ref={page}>
<h1>This is game {gameId}</h1>
<h2>You are playing as {side}</h2>
{joinFailed && <Redirect to="/"/>}
<div id="board">
{squares.map((square) => {
return (
<div id={square.id} className="square" key={square.id}>
{square.piece &&
<div className={'piece ' + square.piece.player + '-' + square.piece.type}
style={draggedPiece === square.piece ? absPos : {}}
/>}
</div>
)
})}
</div>
</div>
)
}
export default GamePage<file_sep>import { useState } from 'react'
import { Redirect } from 'react-router-dom'
function HomePage() {
const [newGameId, setNewGameId] = useState('')
const createGame = () => {
fetch('game/create', {
method: 'POST',
}).then((res) => {
return res.json()
}).then((json) => {
if (json.status === 'success') {
setNewGameId(json.data.id)
} else if (json.status === 'error') {
console.error(json.message)
}
}).catch(console.error.bind(console))
}
return (
<div className="main-container">
<div className="sub-container">
<h1>Chess</h1>
<p>
Play Chess with your friends!
</p>
<button onClick={createGame}>Create Game</button>
</div>
{newGameId !== '' && <NewGame gameId={newGameId}/>}
</div>
);
}
function NewGame({ gameId }) {
const [joinGame, setJoinGame] = useState(false)
return (
<div className="sub-container">
<div className="m-1">
Share this link with your opponent: <span className="copy-url">{process.env.REACT_APP_BASEURL + '/game/' + gameId}</span>
</div>
<button onClick={() => setJoinGame(true)}>Join Game</button>
{joinGame && <Redirect to={'/game/' + gameId} />}
</div>
)
}
export default HomePage
|
f090a251af8e314d65a8ddf24e8ac728fb43e2ad
|
[
"JavaScript"
] | 2
|
JavaScript
|
dvosecky/chess
|
35b0ea05264d4e7562cc7c6a7a3fda48dd541b3e
|
3c4f73a88791e0af3a4dcce1069cc19941396bad
|
refs/heads/main
|
<repo_name>Kandy16/sentitect<file_sep>/src/run_deploy.py
from azureml.core.webservice import AciWebservice
from azureml.core.webservice import Webservice
from azureml.core.model import InferenceConfig
from azureml.core.environment import Environment
from azureml.core import Workspace
from azureml.core.model import Model
ws = Workspace.from_config()
aciconfig = AciWebservice.deploy_configuration(cpu_cores=1,
memory_gb=1,
tags={"data": "sentiment", "method" : "lightgbm"},
description='Predict sentiments of movie reviews')
# get hold of the current run
runObj = Run.get_context()
model = runObj.register_model(model_name='sentitect_lightgbm', filename= os.path.join(args.output, 'sentitect-best-model.pkl'))
print(model.name, model.id, model.version, sep='\t')
model = Model(ws, 'sentitect_lightgbm')
env = Environment('sentitect-env')
cd = CondaDependencies(conda_dependencies_file_path='../environment.yml')
env.python.conda_dependencies = cd
inference_config = InferenceConfig(entry_script="deploy.py", environment=myenv)
service = Model.deploy(workspace=ws,
name='sentitect_lightgbm',
models=[model],
inference_config=inference_config,
deployment_config=aciconfig)
service.wait_for_deployment(show_output=True)
print(service.scoring_uri)<file_sep>/src/test-general.py
from azureml.pipeline.core import PublishedPipeline
from azureml.pipeline.core import PipelineEndpoint
from azureml.core import Workspace
import requests
ws = Workspace.from_config()
print(ws)
published_pipeline = PipelineEndpoint.get(workspace=ws, name="check_deploy")
print(published_pipeline)<file_sep>/tryouts/tryouts.py
import os
import argparse
import joblib
import pandas as pd
import numpy as np
from azureml.core import Run
def run(args):
print('--------Inside register file --------------------')
print(args.data_path)
print(os.listdir(args.data_path))
best_model = joblib.load(os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'))
print(best_model)
data = pd.read_csv(os.path.join(args.data_path, 'output-vectorize.csv'))
data['vectors'] = data['vectors'].apply(lambda row: [float(t) for t in row.split(';')])
X_train = data.vectors.values
X_train = [np.array(tmp) for tmp in X_train]
X_train = np.array(X_train)
y_train = data.sentiment.values
result = best_model.predict(X_train)
print(np.average(result == y_train))
runObj = Run.get_context()
print('--------After getting the context --------------------')
print(args.data_path)
print(os.listdir(args.data_path))
best_model = joblib.load(os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'))
print(best_model)
data = pd.read_csv(os.path.join(args.data_path, 'output-vectorize.csv'))
data['vectors'] = data['vectors'].apply(lambda row: [float(t) for t in row.split(';')])
X_train = data.vectors.values
X_train = [np.array(tmp) for tmp in X_train]
X_train = np.array(X_train)
y_train = data.sentiment.values
result = best_model.predict(X_train)
print(np.average(result == y_train))
#'sentitect-best-model-pkl.pkl'
try:
print('Files inside run context -- before download or/and upload')
print(runObj.get_file_names())
for tmp in runObj.get_file_names():
print(tmp)
except Exception as e:
print(e)
idx = 1
try:
print(idx)
idx += 1
runObj.download_file(name=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'),
output_file_path='outputs/sentitect-best-model-pkl.pkl')
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.download_file(name='outputs/sentitect-best-model-pkl.pkl',
output_file_path=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'))
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.download_file(name=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'),
output_file_path='sentitect-best-model-pkl.pkl')
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.download_file(name='sentitect-best-model-pkl.pkl',
output_file_path=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'))
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.download_file(name='sentitect-best-model-pkl.pkl',
output_file_path=args.data_path)
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.download_file(name='outputs/sentitect-best-model-pkl.pkl',
output_file_path=args.data_path)
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.upload_file(name=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'),
path_or_stream='sentitect-best-model-pkl.pkl')
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.upload_file(name='sentitect-best-model-pkl.pkl',
path_or_stream=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'))
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.upload_file(name=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'),
path_or_stream='outputs/sentitect-best-model-pkl.pkl')
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.upload_file(name='outputs/sentitect-best-model-pkl.pkl',
path_or_stream=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'))
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.upload_file(name='outputs/sentitect-best-model-pkl.pkl',
path_or_stream=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'))
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.upload_file(name='outputs/sentitect-best-model-pkl.pkl',
path_or_stream=args.data_path)
except Exception as e:
print(e)
try:
print(idx)
idx += 1
runObj.upload_file(name='sentitect-best-model-pkl.pkl',
path_or_stream=args.data_path)
except Exception as e:
print(e)
try:
print('Files inside run context -- after download or/and upload')
print(runObj.get_file_names())
for tmp in runObj.get_file_names():
print(tmp)
except Exception as e:
print(e)
try:
print(idx)
idx += 1
model = runObj.register_model(model_name='sentimodel',
model_path=os.path.join(args.data_path, 'sentitect-best-model-pkl.pkl'))
except Exception as e:
print(e)
try:
print(idx)
idx += 1
model = runObj.register_model(model_name='sentimodel',
model_path='outputs/sentitect-best-model-pkl.pkl')
except Exception as e:
print(e)
try:
print(idx)
idx += 1
model = runObj.register_model(model_name='sentimodel',
model_path='sentitect-best-model-pkl.pkl')
except Exception as e:
print(e)
return model
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--data-path',
dest='data_path',
type=str,
required=True,
help='Path to the best model'
)
args = parser.parse_args()
model = run(args)
print(model.name, model.id, model.version, sep='\t')
<file_sep>/src/register.py
import os
import argparse
import joblib
import pandas as pd
import numpy as np
from azureml.core import Run
def run(args):
print(args.model_path)
runObj = Run.get_context()
ws = runObj.experiment.workspace
try:
runObj.upload_file(name='sentitect-best-model-pkl.pkl',
path_or_stream=os.path.join(args.model_path, 'sentitect-best-model-pkl.pkl'))
model = runObj.register_model(model_name='sentimodel',
model_path='sentitect-best-model-pkl.pkl',
workspace=ws)
except Exception as e:
print(e)
return model
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--model-path',
dest='model_path',
type=str,
required=True,
help='Path to the best model'
)
args = parser.parse_args()
model = run(args)
print(model.name, model.id, model.version, sep='\t')
<file_sep>/src/vectorize.py
import os
import argparse
import numpy as np
import pandas as pd
import spacy
def run(args):
data = pd.read_csv(os.path.join(args.data_path,"output-data-prep.csv"))
print(data.head(5))
#VECTORIZE the sentence using spacy
nlp = spacy.load('en_core_web_sm')
# Embed sentences for the training set
# It took a lot of time when used all the pipeline chains of space
# Disable irrelevant sub-pipelines. The quality of vectors may get affected -- need to test
X_train = []
for r in nlp.pipe(data.review.values, disable=['parser','ner','entity_linker','entity_ruler',
'textcat','textcat_multilabel','lemmatizer', 'morphologizer',
'attribute_ruler','senter','sentencizer','tok2vec','transformer']):
#for r in nlp.pipe(data.review.values):
emb = r.vector
review_emb = emb.reshape(-1)
tmp = review_emb.tolist()
tmp = [str(t) for t in tmp]
X_train.append(';'.join(tmp))
#print(X_train)
#print(np.array(X_train))
#X_train = np.array(X_train)
#y_train = data.sentiment.values if 'sentiment' in data.columns else None
#return X_train,y_train
data['vectors'] = X_train
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--data-path',
dest='data_path',
type=str,
required=True,
help='Path to the training data'
)
parser.add_argument(
'--output',
type=str,
required=True,
help='Output path'
)
args = parser.parse_args()
result = run(args)
print(result.head(5))
result.to_csv(os.path.join(args.output,"output-vectorize.csv"), index=False)<file_sep>/src/predict.py
import os
import argparse
import numpy as np
import pandas as pd
from azureml.core import Run
from azureml.core.runconfig import DataPath
from azureml.core.model import Model
import joblib
def run(args):
runObj = Run.get_context()
ws = runObj.experiment.workspace
reg_model_path = Model.get_model_path(model_name='sentimodel', _workspace=ws)
#print(os.getenv('AZUREML_MODEL_DIR'))
#reg_model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'sentimodel')
best_model = joblib.load(reg_model_path)
# read the vectors an convert them to numpy
data = pd.read_csv(os.path.join(args.data_path,"output-vectorize.csv"))
data['vectors'] = data['vectors'].apply(lambda row: [float(t) for t in row.split(';')])
x = data.vectors.values
x = [np.array(tmp) for tmp in x]
x = np.array(x)
predictions = best_model.predict(x)
data['prediction'] = predictions
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--data-path',
dest='data_path',
type=str,
required=True,
help='Path to the predict data'
)
parser.add_argument(
'--output',
type=str,
required=True,
help='Output result path'
)
args = parser.parse_args()
result = run(args)
result[['review','prediction']].to_csv(os.path.join(args.output, 'output.csv'), index=False)
print(result.head(5))
<file_sep>/tryouts/check-deploy.py
import azureml.core
from azureml.core import Workspace
from azureml.core import Experiment
from azureml.core import Environment
from azureml.core import ScriptRunConfig
from azureml.core import Dataset
from azureml.core.runconfig import RunConfiguration
from azureml.core.compute import AmlCompute
from azureml.core.compute import ComputeTarget
from azureml.pipeline.steps import PythonScriptStep
from azureml.data import OutputFileDatasetConfig
from azureml.data.datapath import DataPath
#from azureml.core.environment import Environment
from azureml.core.conda_dependencies import CondaDependencies
import os
# check core SDK version number
print("Azure ML SDK Version: ", azureml.core.VERSION)
# load workspace configuration from the config.json file in the current folder.
ws = Workspace.from_config()
print(ws.name, ws.location, ws.resource_group, sep='\t')
aml_run_config = RunConfiguration()
# choose a name for your cluster. If not available then create the instance
compute_name = os.environ.get("AML_COMPUTE_CLUSTER_NAME", "senti-train")
if compute_name in ws.compute_targets:
compute_target = ws.compute_targets[compute_name]
if compute_target and type(compute_target) is AmlCompute:
print('found compute target. just use it. ' + compute_name)
else:
print(f'creating a new compute target {compute_name}...')
compute_min_nodes = os.environ.get("AML_COMPUTE_CLUSTER_MIN_NODES", 0)
compute_max_nodes = os.environ.get("AML_COMPUTE_CLUSTER_MAX_NODES", 4)
# This example uses CPU VM. For using GPU VM, set SKU to STANDARD_NC6
vm_size = os.environ.get("AML_COMPUTE_CLUSTER_SKU", "STANDARD_D2_V2")
provisioning_config = AmlCompute.provisioning_configuration(vm_size=vm_size,
min_nodes=compute_min_nodes,
max_nodes=compute_max_nodes)
# create the cluster
compute_target = ComputeTarget.create(ws, compute_name, provisioning_config)
# can poll for a minimum number of nodes and for a specific timeout.
# if no min node count is provided it will use the scale settings for the cluster
compute_target.wait_for_completion(
show_output=True, min_node_count=None, timeout_in_minutes=20)
# For a more detailed view of current AmlCompute status, use get_status()
print(compute_target.get_status().serialize())
# assign target to run_config
aml_run_config.target = compute_target
#first of all the local data folder is copied into a datastore.
datastore = ws.get_default_datastore()
datastore.upload(src_dir='../data-train',
target_path='data-train/',
overwrite=True)
datastore_path = [
DataPath(datastore, 'data/train-data.csv'),
DataPath(datastore, 'data/test-data.csv')
]
#dataset = Dataset.File.from_files(path=datastore_path)
dataset = Dataset.File.from_files(path=(datastore, 'data-train/'))
output_data1 = OutputFileDatasetConfig(destination = (datastore, 'outputdataset'))
#output_data_dataset = output_data1.register_on_complete(name = 'prepared_output_data')
# the data preparation does primitive cleaning and stores the intermediate result in datastore
#data-count -1 will read all the data. 100 or 200 size is considered a toy set
data_prep_step = PythonScriptStep(
source_directory='.',
script_name='check-run.py',
arguments=[
'--data-path', dataset.as_named_input('input').as_mount(),
"--output", output_data1
],
compute_target=compute_target,
runconfig=aml_run_config,
allow_reuse=True
)
# the pipeline sequence
train_models = [data_prep_step]
from azureml.pipeline.core import Pipeline
# Build the pipeline
pipeline1 = Pipeline(workspace=ws, steps=[train_models])
# Submit the pipeline to be run
experiment_name = 'check_deploy'
pipeline_run1 = Experiment(workspace=ws, name=experiment_name).submit(pipeline1)
pipeline_run1.wait_for_completion()
published_training = pipeline_run1.publish_pipeline(
name = 'check_deploy',
description = 'Check deployment using pipeline',
version = '2.0')
<file_sep>/ds-experiments/tuning.py
# explore lightgbm number of trees effect on performance
from numpy import mean
from numpy import std
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from lightgbm import LGBMClassifier
from matplotlib import pyplot
# get the dataset
def get_dataset():
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=7)
return X, y
# get a list of models to evaluate
def get_models():
models = dict()
trees = [10, 50, 100, 500, 1000, 5000]
for n in trees:
models[str(n)] = LGBMClassifier(n_estimators=n)
return models
# evaluate a give model using cross-validation
def evaluate_model(model):
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1)
return scores
# define dataset
X, y = get_dataset()
# get the models to evaluate
models = get_models()
# evaluate the models and store results
results, names = list(), list()
for name, model in models.items():
scores = evaluate_model(model)
results.append(scores)
names.append(name)
print('>%s %.3f (%.3f)' % (name, mean(scores), std(scores)))
# plot model performance for comparison
pyplot.boxplot(results, labels=names, showmeans=True)
pyplot.show()<file_sep>/tryouts/check-run.py
import os
import argparse
def run(args):
count = 0
for file1 in os.listdir(args.data_path):
print(file1)
count += 1
return count
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--data-path',
dest='data_path',
type=str,
required=True,
help='Path to the training data'
)
parser.add_argument(
'--output',
type=str,
required=True,
help='Output path'
)
args = parser.parse_args()
print('arguments:',args)
result = run(args)
print('The answer is : ', result)
with open(os.path.join(args.output, 'count-files.txt'),'w') as f:
f.write(str(result))
<file_sep>/src/train.py
import os
import argparse
import numpy as np
import pandas as pd
from azureml.core import Run
from azureml.core.runconfig import DataPath
from sklearn.model_selection import train_test_split
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from scipy.stats import randint as sp_randint
from scipy.stats import uniform as sp_uniform
import lightgbm as lgbm
import joblib
def run(args):
# read the vectors an convert them to numpy
data = pd.read_csv(os.path.join(args.data_path,"output-vectorize.csv"))
data['vectors'] = data['vectors'].apply(lambda row: [float(t) for t in row.split(';')])
X_train = data.vectors.values
X_train = [np.array(tmp) for tmp in X_train]
X_train = np.array(X_train)
y_train = data.sentiment.values
# dataset is sepearted into training, test and validation
X_train, X_test, y_train, y_test = train_test_split(X_train,y_train,test_size=0.2, stratify=y_train, random_state = 42)
X_val, X_test, y_val, y_test = train_test_split(X_test,y_test,test_size=0.5, stratify=y_test, random_state = 42)
# Get the train and val data for the training sequence
#test will at predicting the final accuracy
train_data = lgbm.Dataset(X_train, label=y_train)
val_data = lgbm.Dataset(X_val, label=y_val)
'''
# Parameters we'll use for the prediction
parameters = {
'application': 'binary',
'objective': 'binary',
'metric': 'auc',
'boosting': 'gbdt',
'num_leaves': 31,
'feature_fraction': 0.5,
'bagging_fraction': 0.5,
'bagging_freq': 20,
'learning_rate': 0.05,
'verbose': 0
}
classifier = lgbm.train(parameters,
train_data,
valid_sets= val_data,
num_boost_round=100,
early_stopping_rounds=10)
'''
# at the beginning random search and then grid search for scale_pos_weight parameter. choose the best model and compute
# accuracy on test dataset
fit_params={"early_stopping_rounds":30,
"eval_metric" : 'auc',
"eval_set" : [(X_val,y_val)],
'eval_names': ['valid'],
#'callbacks': [lgbm.reset_parameter(learning_rate=learning_rate_010_decay_power_099)],
'verbose': 100,
'categorical_feature': 'auto'}
param_test ={'num_leaves': sp_randint(6, 50),
'min_child_samples': sp_randint(100, 500),
'min_child_weight': [1e-5, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2, 1e3, 1e4],
'subsample': sp_uniform(loc=0.2, scale=0.8),
'boosting_type':['gbdt','goss'],
'colsample_bytree': sp_uniform(loc=0.4, scale=0.6),
'reg_alpha': [0, 1e-1, 1, 2, 5, 7, 10, 50, 100],
'reg_lambda': [0, 1e-1, 1, 5, 10, 20, 50, 100]}
#This parameter defines the number of HP points to be tested
n_HP_points_to_test = 100
#n_estimators is set to a "large value". The actual number of trees build will depend on early stopping and 5000 define only the absolute maximum
clf = lgbm.LGBMClassifier(max_depth=-1, random_state=314, silent=True, metric='None', n_jobs=4, n_estimators=5000)
gs = RandomizedSearchCV(
estimator=clf, param_distributions=param_test,
n_iter=n_HP_points_to_test,
scoring='roc_auc',
cv=5,
refit=True,
random_state=314,
verbose=True)
gs.fit(X_train, y_train, **fit_params)
print('Best score reached: {} with params: {} '.format(gs.best_score_, gs.best_params_))
clf_sw = lgbm.LGBMClassifier(**clf.get_params())
#set optimal parameters
clf_sw.set_params(**gs.best_estimator_.get_params())
gs_sample_weight = GridSearchCV(estimator=clf_sw,
param_grid={'scale_pos_weight':[1,2,6,12]},
scoring='roc_auc',
cv=5,
refit=True,
verbose=True)
gs_sample_weight.fit(X_train, y_train, **fit_params)
print('Best score reached: {} with params: {} '.format(gs_sample_weight.best_score_, gs_sample_weight.best_params_))
#Configure from the HP optimisation
clf_final = lgbm.LGBMClassifier(**clf_sw.get_params())
res = clf_final.set_params(**gs_sample_weight.best_estimator_.get_params())
print(res)
def learning_rate_010_decay_power_099(current_iter):
base_learning_rate = 0.1
lr = base_learning_rate * np.power(.99, current_iter)
return lr if lr > 1e-3 else 1e-3
def learning_rate_010_decay_power_0995(current_iter):
print(current_iter)
base_learning_rate = 0.1
lr = base_learning_rate * np.power(.995, current_iter)
return lr if lr > 1e-3 else 1e-3
def learning_rate_005_decay_power_099(current_iter):
base_learning_rate = 0.05
lr = base_learning_rate * np.power(.99, current_iter)
return lr if lr > 1e-3 else 1e-3
#Train the final model with learning rate decay
#clf_final.fit(X_train, y_train, **fit_params,
# callbacks=[lgbm.reset_parameter(learning_rate=learning_rate_010_decay_power_0995)])
clf_final.fit(X_train, y_train, **fit_params)
# get hold of the current run
runObj = Run.get_context()
print('Predict the test set')
y_hat = clf_final.predict(X_test)
# calculate accuracy on the prediction
acc = np.average(y_hat == y_test)
print('Accuracy is', acc)
runObj.log('accuracy', float(acc))
# the best model is saved to a persistent location
return clf_final
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--data-path',
dest='data_path',
type=str,
required=True,
help='Path to the training data'
)
parser.add_argument(
'--output',
type=str,
required=True,
help='Output path'
)
args = parser.parse_args()
result = run(args)
print('Saving the best model...')
joblib.dump(value=result, filename= os.path.join(args.output, 'sentitect-best-model-pkl.pkl'))
<file_sep>/tryouts/test-deploy.py
from azureml.pipeline.core import PublishedPipeline
from azureml.pipeline.core import PipelineEndpoint
from azureml.core import Experiment
from azureml.core import Workspace
import requests
ws = Workspace.from_config()
print(ws)
published_pipeline = PublishedPipeline.get(workspace=ws, id="f8d8a01b-57a9-4d53-bd50-f4eef67f610d")
print(published_pipeline)
'''
ws1 = Workspace(subscription_id="2a312bc4-2d2c-41be-810d-95fbe06a6aa3",
resource_group="sentitect",
workspace_name="sentitect-ws")
print(ws1)
published_pipeline = PublishedPipeline.get(workspace=ws, id="f8d8a01b-57a9-4d53-bd50-f4eef67f610d")
print(published_pipeline)
response = requests.post(published_pipeline.endpoint,
headers={'Content-Type':'application/json'},
json={"ExperimentName": "my_http_experiment"})
#,"ParameterAssignments": {"pipeline_arg": 20}})
print(response)
'''
'''
experiment = Experiment(workspace=ws, name='my_experiment')
pipeline_run = experiment.submit(published_pipeline,
pipeline_parameters={})
print(pipeline_run)
'''
'''
# tenant id - 5254eecf-63bd-403a-9077-71f987bb793b
# workspace suscription id - 2a312bc4-2d2c-41be-810d-95fbe06a6aa3
# pipeline id - f8d8a01b-57a9-4d53-bd50-f4eef67f610d
# api id - 3f6dff05-a9d0-4d1d-8607-4e029e69c546
from azureml.core.authentication import TokenAuthentication, Audience
# This is a sample method to retrieve token and will be passed to TokenAuthentication
def get_token_for_audience(audience):
from adal import AuthenticationContext
client_id = "3f6dff05-a9d0-4d1d-8607-4e029e69c546"
client_secret = "<KEY>"
tenant_id = "5254eecf-63bd-403a-9077-71f987bb793b"
auth_context = AuthenticationContext("https://login.microsoftonline.com/{}".format(tenant_id))
resp = auth_context.acquire_token_with_client_credentials(audience,client_id,client_secret)
token = resp["accessToken"]
return token
token_auth = TokenAuthentication(get_token_for_audience=get_token_for_audience)
print(token_auth)
print(Audience.ARM)
print(Audience.AZUREML)
token_arm_audience = token_auth.get_token(Audience.AZUREML)
token_aml_audience = token_auth.get_token(Audience.ARM)
print(token_aml_audience)
print('----------')
print(token_arm_audience)
'''
aad_token = '<KEY>'
headers = {'Content-Type': 'application/json'}
response = requests.post(published_pipeline.endpoint,
headers=headers,
json={"ExperimentName": "my_http_experiment",
"ParameterAssignments": {"pipeline_arg": 20}})
print(response)
'''
pipeline_endpoint = PipelineEndpoint.publish(workspace=ws, name="PipelineEndpointTest",
pipeline=published_pipeline, description="Test description Notebook")
pipeline_endpoint_by_name = PipelineEndpoint.get(workspace=ws, name="PipelineEndpointTest")
run_id = pipeline_endpoint_by_name.submit("PipelineEndpointExperiment")
print(run_id)
rest_endpoint = pipeline_endpoint_by_name.endpoint
response = requests.post(rest_endpoint,
headers=aad_token,
json={"ExperimentName": "PipelineEndpointExperiment",
"RunSource": "API",
"ParameterAssignments": {"1": "united", "2":"city"}})
response = requests.post(published_pipeline.endpoint,
#headers=aad_token,
json={"ExperimentName": "check_deploy"})
#,"ParameterAssignments": {"pipeline_arg": 20}})
print(response)
rest_endpoint = 'https://westeurope.api.azureml.ms/pipelines/v1.0/subscriptions/2a312bc4-2d2c-41be-810d-95fbe06a6aa3/resourceGroups/sentitect/providers/Microsoft.MachineLearningServices/workspaces/sentitect-ws/PipelineRuns/PipelineSubmit/f8d8a01b-57a9-4d53-bd50-f4eef67f610d'
response = requests.post(rest_endpoint,
headers=aad_token,
json={"ExperimentName": "PipelineEndpointExperiment",
"RunSource": "API",
"ParameterAssignments": {"1": "united", "2":"city"}})
'''
<file_sep>/ds-experiments/sample.py
"""
Code samples inspired from
https://machinelearningmastery.com/light-gradient-boosted-machine-lightgbm-ensemble/
"""
# evaluate lightgbm algorithm for classification
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from lightgbm import LGBMClassifier
# define dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=7)
# define the model
model = LGBMClassifier()
# evaluate the model
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1)
# report performance
print('Accuracy: %.3f (%.3f)' % (np.mean(n_scores), np.std(n_scores)))
# fit the model on the whole dataset
model.fit(X, y)
# make a single prediction
row = [0.2929949,-4.21223056,-1.288332,-2.17849815,-0.64527665,2.58097719,0.28422388,-7.1827928,-1.91211104,2.73729512,0.81395695,3.96973717,-2.66939799,3.34692332,4.19791821,0.99990998,-0.30201875,-4.43170633,-2.82646737,0.44916808]
yhat = model.predict([row])
print('Predicted Class: %d' % yhat[0])<file_sep>/ds-experiments/train.py
import numpy as np
import pandas as pd
import re
import spacy
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import lightgbm as lgbm
import time
start_time = time.time()
# LOAD DATA SETS
# Load the train, test and submission data frames
TOY_NUM = 200
print('--------------- Data preparation ------------------')
train_df = pd.read_csv("data/train-data.csv")
train_df = shuffle(train_df)[0:TOY_NUM]
test_df = pd.read_csv("data/test-data.csv")
test_df = shuffle(test_df)[0:TOY_NUM]
submission_df = pd.read_csv("data/predict-data.csv")
submission_df = shuffle(submission_df)[0:TOY_NUM]
# Create a merged data set and review initial information
combined_df = pd.concat([train_df, test_df])
# DATA EXPLORATION
# Quickly check for class imbalance
print(combined_df.describe())
# Check what the text looks like
print(combined_df.head(5))
# Get all the unique keywords
#print(combined_df["review"]-str.split.unique())
# Create small function to clean text
def text_clean(text):
for element in ["http\S+", "RT ", "[^a-zA-Z\'\.\,\d\s]", "[0-9]","\t", "\n", "\s+", "<.*?>"]:
text = re.sub("r"+element, " ", text)
return text
# Clean data sets
combined_df.review = combined_df.review.apply(text_clean)
#test_df.review = test_df.review.apply(text_clean)
submission_df.review = submission_df.review.apply(text_clean)
# CORRECT SPELLING
print('--------------- Vectorizing data ------------------')
start_vector_time = time.time()
#VECTORIZE the sentence
nlp = spacy.load('en_core_web_sm')
'''
nlp = spacy.load('en_core_web_sm',
exclude=['tagger','parser','ner','entity_linker','entity_ruler',
'textcat','textcat_multilabel','lemmatizer', 'morphologizer',
'attribute_ruler','senter','sentencizer','tok2vec','transformer'])
'''
# Embed sentences for the training set
X_train = []
for r in nlp.pipe(combined_df.review.values, disable=['parser','ner','entity_linker','entity_ruler',
'textcat','textcat_multilabel','lemmatizer', 'morphologizer',
'attribute_ruler','senter','sentencizer','tok2vec','transformer']):
#print(f"{idx} out of {train_df.shape[0]}")
emb = r.vector
review_emb = emb.reshape(-1)
X_train.append(review_emb)
X_train = np.array(X_train)
y_train = combined_df.sentiment.values
end_vector_time = time.time()
print(f'Vectorization Time taken in seconds : {end_vector_time - start_vector_time}')
print(f'Vectorization Time taken in minutes : {(end_vector_time - start_vector_time)/60}')
'''
# Embed sentences for the submission set
submission_data = []
for r in nlp.pipe(submission_df.review.values):
emb = r.vector
review_emb = emb.reshape(-1)
submission_data.append(review_emb)
submission_data = np.array(submission_data)
'''
print('--------------- Training Data ------------------')
# LGBM
# Split data into train and testing data
X_train, X_test, y_train, y_test = train_test_split(X_train,y_train,test_size=0.2, random_state = 42)
# Get the train and test data for the training sequence
train_data = lgbm.Dataset(X_train, label=y_train)
test_data = lgbm.Dataset(X_test, label=y_test)
# Parameters we'll use for the prediction
parameters = {
'application': 'binary',
'objective': 'binary',
'metric': 'auc',
'boosting': 'dart',
'num_leaves': 31,
'feature_fraction': 0.5,
'bagging_fraction': 0.5,
'bagging_freq': 20,
'learning_rate': 0.05,
'verbose': 0
}
# Train the classifier
classifier = lgbm.train(parameters,
train_data,
valid_sets= test_data,
num_boost_round=5000,
early_stopping_rounds=100)
'''
print('--------------- Prediction ------------------')
# PREDICTION
val_pred = classifier.predict(submission_data)
# Submission file
submission_df['sentiment_predicted'] = val_pred.round().astype(int)
submission_df.to_csv('submission_lgbm.csv', index=False)
'''
end_time = time.time()
print(f'Time taken in seconds : {end_time - start_time}')
print(f'Time taken in minutes : {(end_time - start_time)/60}')
#correct_pred_count = sum(submission_df['sentiment'] == submission_df['sentiment_predicted'])
#print('The accuracy is : ', (100*correct_pred_count/submission_df.shape[0]))<file_sep>/README.md
# sentitect - Sentiment detection using machine learning
* Used LightGBM algorithm
* Used Azure ML python sdk
The development and run environment can be replicated using conda and environment.yml file.
### Important files to consider
1) 'lightgbm.ipynb'in ds-experiments folder contains the rough model development (Taken as input)
2) 'data' folder contains the sentiment analysis dataset. data-preparation.py creates the CSV files. https://ai.stanford.edu/~amaas/data/sentiment/
3) 'src' folder contains all the codes to be run with azure environment. Uses pipelines.
4) 'run_train.py' amd 'run_predict.py' are the main files to perform training and prediction
Inline comments will be there to assist understanding
The codes in the following links are used to build the code:
https://www.kaggle.com/mehdislim01/simple-yet-efficient-spacy-lightgbm-combination
https://medium.com/@invest_gs/classifying-tweets-with-lightgbm-and-the-universal-sentence-encoder-2a0208de0424
Azure info:
https://docs.microsoft.com/en-us/azure/machine-learning/tutorial-train-models-with-aml
https://docs.microsoft.com/en-us/azure/machine-learning/tutorial-deploy-models-with-aml
https://docs.microsoft.com/en-us/azure/machine-learning/tutorial-pipeline-batch-scoring-classification
https://docs.microsoft.com/en-us/azure/machine-learning/tutorial-convert-ml-experiment-to-production
https://docs.microsoft.com/en-us/azure/machine-learning/how-to-create-machine-learning-pipelines
https://docs.microsoft.com/en-us/azure/machine-learning/how-to-move-data-in-out-of-pipelines
<file_sep>/src/data_prep.py
import os
import argparse
import pandas as pd
import re
from sklearn.utils import shuffle
from azureml.core import Run
# Removes stop words and other entities which are not likely meaningful words
def text_clean(text):
for element in ["http\S+", "RT ", "[^a-zA-Z\'\.\,\d\s]", "[0-9]","\t", "\n", "\s+", "<.*?>"]:
text = re.sub("r"+element, " ", text)
return text
def run(args):
df_list = []
print(f'Data path: {args.data_path}')
#data_path = Run.get_context().input_datasets['input_data']
#print(f'Listing files inside directory {data_path}')
for file1 in os.listdir(args.data_path):
print(file1)
for file1 in os.listdir(args.data_path):
if(file1.endswith('.csv')):
df = pd.read_csv(os.path.join(args.data_path,file1))
df = shuffle(df)[0:args.data_count]
df_list.append(df)
# Create a merged data set and review initial information
combined_df = pd.concat(df_list)
# Clean data sets
combined_df.review = combined_df.review.apply(text_clean)
return combined_df
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--data-path',
dest='data_path',
type=str,
required=True,
help='Path to the training data'
)
parser.add_argument(
'--data-count',
dest='data_count',
type=int,
nargs='?',
const=-1,
help='Count of data to be processed. -1 refers to all'
)
parser.add_argument(
'--output',
type=str,
required=True,
help='Output path'
)
args = parser.parse_args()
if args.data_count == -1:
args.data_count = None
print('arguments:',args)
result = run(args)
print(result.head(5))
result.to_csv(os.path.join(args.output,"output-data-prep.csv"), index=False)<file_sep>/ds-experiments/data-preparation.py
#let us assume that the dataset exists
import os
import pandas as pd
current_dir = os.path.dirname(__file__)
print(current_dir)
def retrieve_train_data(input_dir):
data = []
for sub_dir in enumerate(['neg', 'pos']):
complete_path = os.path.join(input_dir,sub_dir[1])
for file in os.listdir(complete_path):
#print(os.path.join(complete_path, file))
with open(os.path.join(complete_path, file),'r') as f:
content = f.read(-1)
data.append([content, sub_dir[0]])
return data
def retrieve_predict_data(input_dir):
data = []
for sub_dir in enumerate(['unsup']):
complete_path = os.path.join(input_dir,sub_dir[1])
for file in os.listdir(complete_path):
print(os.path.join(complete_path, file))
with open(os.path.join(complete_path, file),'r') as f:
content = f.read(-1)
data.append(content)
return data
print('Training data preparation')
train_dir = os.path.join(current_dir, 'dataset/aclImdb/train')
train_data = retrieve_train_data(train_dir)
df = pd.DataFrame(train_data,columns=['review','sentiment'])
df.to_csv('train-data.csv',index=False)
print('Test data preparation')
test_dir = os.path.join(current_dir, 'dataset/aclImdb/test')
test_data = retrieve_train_data(test_dir)
df = pd.DataFrame(test_data,columns=['review','sentiment'])
df.to_csv('test-data.csv',index=False)
print('Predict data preparation')
predict_dir = os.path.join(current_dir, 'dataset/aclImdb/train')
predict_data = retrieve_predict_data(predict_dir)
df = pd.DataFrame(predict_data,columns=['review'])
df.to_csv('predict-data.csv',index=False)
|
68a8cf0fab56098f15f84bc6e14503224793395e
|
[
"Markdown",
"Python"
] | 16
|
Python
|
Kandy16/sentitect
|
ceba12116ea0fe2f58e53209a14004fe8131325e
|
f8c16263204ad64b33049829a5ae3895830d2acf
|
refs/heads/master
|
<file_sep>package io.sloeber.core.common;
import static io.sloeber.core.common.Const.*;
import java.io.File;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.TreeSet;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.osgi.service.prefs.BackingStoreException;
import io.sloeber.core.api.Defaults;
/**
* Items on the Configuration level are linked to the ConfigurationScope
* (=eclipse install base).
*
* @author jan
*
*/
public class ConfigurationPreferences {
private static final String EXAMPLE_FOLDER_NAME = "examples"; //$NON-NLS-1$
private static final String DOWNLOADS_FOLDER = "downloads"; //$NON-NLS-1$
private static final String PRE_PROCESSING_PLATFORM_TXT = "pre_processing_platform.txt"; //$NON-NLS-1$
private static final String POST_PROCESSING_PLATFORM_TXT = "post_processing_platform.txt"; //$NON-NLS-1$
private static final String PRE_PROCESSING_BOARDS_TXT = "pre_processing_boards.txt"; //$NON-NLS-1$
private static final String POST_PROCESSING_BOARDS_TXT = "post_processing_boards.txt"; //$NON-NLS-1$
private static final String KEY_UPDATE_JASONS = "Update jsons files"; //$NON-NLS-1$
// preference nodes
private static final String PACKAGES_FOLDER_NAME = "packages"; //$NON-NLS-1$
private static String systemHash = "no hash generated"; //$NON-NLS-1$
static {
// make a hashkey to identify the system
Collection<String> macs = new TreeSet<>();
Enumeration<NetworkInterface> inters;
try {
inters = NetworkInterface.getNetworkInterfaces();
while (inters.hasMoreElements()) {
NetworkInterface inter = inters.nextElement();
if (inter.getHardwareAddress() == null) {
continue;
}
if (inter.isVirtual()) {
continue;
}
byte curmac[] = inter.getHardwareAddress();
StringBuilder b = new StringBuilder();
for (byte curbyte : curmac) {
b.append(String.format("%02X", Byte.valueOf(curbyte))); //$NON-NLS-1$
}
macs.add(b.toString());
}
} catch (@SuppressWarnings("unused") SocketException e) {
// ignore
}
Integer hascode = Integer.valueOf(macs.toString().hashCode());
systemHash = hascode.toString();
}
public static void removeKey(String key) {
IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO);
myScope.remove(key);
}
public static String getString(String key, String defaultValue) {
IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO);
return myScope.get(key, defaultValue);
}
private static boolean getBoolean(String key, boolean defaultValue) {
IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO);
return myScope.getBoolean(key, defaultValue);
}
private static void setBoolean(String key, boolean value) {
IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO);
myScope.putBoolean(key, value);
try {
myScope.flush();
} catch (BackingStoreException e) {
e.printStackTrace();
}
}
public static void setString(String key, String value) {
IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO);
myScope.put(key, value);
try {
myScope.flush();
} catch (BackingStoreException e) {
e.printStackTrace();
}
}
public static IPath getInstallationPath() {
return Common.sloeberHomePath.append("arduinoPlugin"); //$NON-NLS-1$
}
public static IPath getInstallationPathLibraries() {
return getInstallationPath().append(LIBRARY_PATH_SUFFIX);
}
public static IPath getInstallationPathExamples() {
return getInstallationPath().append(EXAMPLE_FOLDER_NAME);
}
public static IPath getInstallationPathDownload() {
return getInstallationPath().append(DOWNLOADS_FOLDER);
}
public static IPath getInstallationPathPackages() {
return getInstallationPath().append(PACKAGES_FOLDER_NAME);
}
/**
* Get the file that contains the preprocessing platform content
*
* @return
*/
public static File getPreProcessingPlatformFile() {
return getInstallationPath().append(PRE_PROCESSING_PLATFORM_TXT).toFile();
}
/**
* Get the file that contains the post processing platform content
*
* @return
*/
public static File getPostProcessingPlatformFile() {
return getInstallationPath().append(POST_PROCESSING_PLATFORM_TXT).toFile();
}
public static File getPreProcessingBoardsFile() {
return getInstallationPath().append(PRE_PROCESSING_BOARDS_TXT).toFile();
}
public static File getPostProcessingBoardsFile() {
return getInstallationPath().append(POST_PROCESSING_BOARDS_TXT).toFile();
}
public static Path getMakePath() {
return new Path(getInstallationPath().append("tools/make").toString()); //$NON-NLS-1$
}
public static IPath getAwkPath() {
return new Path(getInstallationPath().append("tools/awk").toString()); //$NON-NLS-1$
}
public static boolean getUpdateJasonFilesFlag() {
return getBoolean(KEY_UPDATE_JASONS, Defaults.updateJsonFiles);
}
public static void setUpdateJasonFilesFlag(boolean newFlag) {
setBoolean(KEY_UPDATE_JASONS, newFlag);
}
/**
* Make a unique hashKey based on system parameters so we can identify users To
* make the key the mac addresses of the network cards are used
*
* @return a unique key identifying the system
*/
public static String getSystemHash() {
return systemHash;
}
}
<file_sep>package io.sloeber.providers;
import static org.junit.Assert.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import io.sloeber.core.api.PackageManager;
@SuppressWarnings("nls")
public class Arduino extends MCUBoard {
private static final String providerArduino = "arduino";
private static final String providerIntel = "Intel";
private static final String AVRArchitectureName = "avr";
private static final String SAMDArchitectureName = "samd";
private static final String SAMArchitectureName = "sam";
private static final String NFRArchitectureName = "nrf52";
private static final String intelCurieArchitectureName = "arc32";
private static final String jsonFileName ="package_index.json";
public static final String circuitplay32ID="circuitplay32u4cat";
public static final String unoID="uno";
public static final String ethernetID="ethernet";
public static MCUBoard gemma() {
MCUBoard ret = new Arduino(providerArduino, AVRArchitectureName, "gemma");
ret.mySlangName="gemma";
return ret;
}
public static MCUBoard MegaADK() {
return new Arduino(providerArduino, AVRArchitectureName, "megaADK");
}
public static MCUBoard esplora() {
return new Arduino(providerArduino, AVRArchitectureName, "esplora");
}
public static MCUBoard adafruitnCirquitPlayground() {
return new Arduino(providerArduino, AVRArchitectureName, circuitplay32ID);
}
public static MCUBoard cirquitPlaygroundExpress() {
return new Arduino(providerArduino, SAMDArchitectureName, "adafruit_circuitplayground_m0");
}
public static MCUBoard getAvrBoard(String boardID) {
return new Arduino(providerArduino, AVRArchitectureName, boardID);
}
public static MCUBoard fried2016() {
return new Arduino(providerArduino, AVRArchitectureName, "LilyPadUSB");
}
public static MCUBoard fried2016(String uploadPort) {
MCUBoard fried = fried2016();
fried.myBoardDescriptor.setUploadPort(uploadPort);
return fried;
}
public static MCUBoard getMega2560Board() {
MCUBoard mega = new Arduino(providerArduino, AVRArchitectureName, "mega");
Map<String, String> options = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
options.put("cpu", "atmega2560");
mega.myBoardDescriptor.setOptions(options);
return mega;
}
public static MCUBoard getMega2560Board(String uploadPort) {
MCUBoard mega = getMega2560Board();
mega.myBoardDescriptor.setUploadPort(uploadPort);
return mega;
}
public static MCUBoard leonardo() {
MCUBoard leonardo = new Arduino(providerArduino, AVRArchitectureName, "leonardo");
return leonardo;
}
public static MCUBoard leonardo(String uploadPort) {
MCUBoard leonardo = leonardo();
leonardo.myBoardDescriptor.setUploadPort(uploadPort);
return leonardo;
}
public static MCUBoard yun() {
MCUBoard yun = new Arduino(providerArduino, AVRArchitectureName, "yun");
return yun;
}
public static MCUBoard yun(String uploadPort) {
MCUBoard yun = yun();
yun.myBoardDescriptor.setUploadPort(uploadPort);
return yun;
}
public static MCUBoard zeroProgrammingPort() {
MCUBoard zero = new Arduino(providerArduino, SAMDArchitectureName, "arduino_zero_edbg");
zero.mySlangName="zero";
return zero;
}
public static MCUBoard zeroProgrammingPort(String uploadPort) {
MCUBoard zero = zeroProgrammingPort();
zero.myBoardDescriptor.setUploadPort(uploadPort);
return zero;
}
public static MCUBoard due() {
return new Arduino(providerArduino, SAMArchitectureName, "arduino_due_x");
}
public static MCUBoard due(String uploadPort) {
MCUBoard board = due();
board.myBoardDescriptor.setUploadPort(uploadPort);
return board;
}
public static MCUBoard dueprogramming() {
return new Arduino(providerArduino, SAMArchitectureName, "arduino_due_x_dbg");
}
public static MCUBoard dueprogramming(String uploadPort) {
MCUBoard board = dueprogramming();
board.myBoardDescriptor.setUploadPort(uploadPort);
return board;
}
public static MCUBoard mkrfox1200() {
return new Arduino(providerArduino, SAMDArchitectureName, "mkrfox1200");
}
public static MCUBoard primo() {
return new Arduino(providerArduino, NFRArchitectureName, "primo");
}
public static MCUBoard uno() {
MCUBoard uno = new Arduino(providerArduino, AVRArchitectureName, unoID);
uno.mySlangName="uno";
return uno;
}
public static MCUBoard ethernet() {
MCUBoard uno = new Arduino(providerArduino, AVRArchitectureName, ethernetID);
return uno;
}
public static MCUBoard uno(String uploadPort) {
MCUBoard uno = uno();
uno.myBoardDescriptor.setUploadPort(uploadPort);
return uno;
}
public static MCUBoard arduino_101() {
MCUBoard arduino_101 = new Arduino(providerIntel, intelCurieArchitectureName, "arduino_101");
arduino_101.mySlangName="101";
return arduino_101;
}
public static MCUBoard arduino_101(String uploadPort) {
MCUBoard arduino_101 = arduino_101();
arduino_101.myBoardDescriptor.setUploadPort(uploadPort);
return arduino_101;
}
private Arduino(String providerName, String architectureName, String boardName) {
this.myBoardDescriptor = PackageManager.getBoardDescription(jsonFileName, providerName, architectureName,
boardName, null);
if (this.myBoardDescriptor == null) {
fail(boardName + " Board not found");
}
this.myBoardDescriptor.setUploadPort("none");
myAttributes.serial = !doesNotSupportSerialList().contains(boardName);
myAttributes.serial1 = supportSerial1List().contains(boardName);
myAttributes.keyboard = supportKeyboardList().contains(boardName);
myAttributes.wire1 = supportWire1List().contains(boardName);
myAttributes.buildInLed = !doesNotSupportbuildInLed().contains(boardName);
}
static List<String> supportWire1List() {
List<String> ret = new LinkedList<>();
ret.add("zero");
return ret;
}
static List<String> doesNotSupportbuildInLed() {
List<String> ret = new LinkedList<>();
ret.add("robotControl");
ret.add("robotMotor");
return ret;
}
static List<String> supportSerial1List() {
List<String> ret = new LinkedList<>();
ret.add("circuitplay32u4cat");
ret.add("LilyPadUSB");
ret.add("Micro");
ret.add("yunMini");
ret.add("robotControl");
ret.add("Esplora");
ret.add("mega");
ret.add("chiwawa");
ret.add("yun");
ret.add("one");
ret.add("leonardo");
ret.add("robotMotor");
ret.add("leonardoEth");
ret.add("megaADK");
return ret;
}
static List<String> doesNotSupportSerialList() {
List<String> ret = new LinkedList<>();
ret.add("gemma");
return ret;
}
static List<String> supportKeyboardList() {
List<String> ret = new LinkedList<>();
ret.add("circuitplay32u4cat");
ret.add("LilyPadUSB");
ret.add("Micro");
ret.add("yunMini");
ret.add("robotControl");
ret.add("Esplora");
ret.add("chiwawa");
ret.add("yun");
// mySupportKeyboardList.add("one");
// mySupportKeyboardList.add("Leonardo");
// mySupportKeyboardList.add("robotMotor");
// mySupportKeyboardList.add("LeonardoEth");
// mySupportKeyboardList.add("MegaADK");
return ret;
}
public static void installLatestAVRBoards() {
PackageManager.installLatestPlatform(jsonFileName,providerArduino, AVRArchitectureName);
}
public static void installLatestSamDBoards() {
PackageManager.installLatestPlatform(jsonFileName, providerArduino, SAMDArchitectureName);
}
public static void installLatestSamBoards() {
PackageManager.installLatestPlatform(jsonFileName, providerArduino, SAMArchitectureName);
}
public static void installLatestIntellCurieBoards() {
PackageManager.installLatestPlatform(jsonFileName, providerIntel, intelCurieArchitectureName);
}
public static MCUBoard[] getAllBoards() {
// TODO
// hardcode this stuff now because I want to release 4.3.1
//shoulds be something like
//return PackageManager.getAllBoardDescriptors(getJsonFileName(),getPackageName(),getPlatformName() , options);
MCUBoard[] boards = { Arduino.uno(),
Arduino.leonardo(),
Arduino.esplora(),
Arduino.yun(),
Arduino.getAvrBoard("diecimila"),
Arduino.getMega2560Board(),
Arduino.MegaADK(),
Arduino.getAvrBoard("leonardoeth"),
Arduino.getAvrBoard("micro"),
Arduino.getAvrBoard("mini"),
Arduino.getAvrBoard("ethernet"),
Arduino.getAvrBoard("fio"),
Arduino.getAvrBoard("bt"),
Arduino.getAvrBoard("LilyPadUSB"),
Arduino.getAvrBoard("lilypad"),
Arduino.getAvrBoard("pro"),
Arduino.getAvrBoard("atmegang"),
Arduino.getAvrBoard("robotControl"),
Arduino.getAvrBoard("robotMotor"),
Arduino.getAvrBoard("gemma"),
Arduino.adafruitnCirquitPlayground(),
Arduino.getAvrBoard("yunmini"),
Arduino.getAvrBoard("chiwawa"),
Arduino.getAvrBoard("one"),
Arduino.getAvrBoard("unowifi"), };
return boards;
}
public static MCUBoard zeroNatviePort() {
MCUBoard zero = new Arduino(providerArduino, SAMDArchitectureName, "arduino_zero_native");
zero.mySlangName="zero Native";
zero.mySerialPort="SerialUSB";
return zero;
}
public static MCUBoard zeroNatviePort(String uploadPort) {
MCUBoard zero = zeroNatviePort();
zero.myBoardDescriptor.setUploadPort(uploadPort);
return zero;
}
}<file_sep>package io.sloeber.junit;
import static io.sloeber.core.txt.WorkAround.*;
import static org.junit.Assert.*;
import org.junit.Test;
import io.sloeber.core.tools.Version;
@SuppressWarnings({ "nls", "static-method" })
public class TestPlatformWorkAround {
@Test
public void PlatformFixes() {
String Input = "compiler.path.windows={runtime.tools.mingw.path}/bin/";
String Expected = "compiler.path=${runtime.tools.MinGW.path}/bin/";
String output = platformApplyWorkArounds(Input, null);
assertEquals("Jantjes mingw fix", Expected, output);
Input = "compiler.path.windows={runtime.tools.mingw.path}/bin/";
Expected = "compiler.path=${runtime.tools.MinGW.path}/bin/";
output = platformApplyWorkArounds(Input, null);
assertEquals("Jantjes mingw fix", Expected, output);
}
@Test
public void ToolFixes() {
assertEquals("1", Version.compare("1.0.0", "16"), -1);
assertEquals("2", Version.compare("1.1.0", "1.16"), -1);
assertEquals("3", Version.compare("1.1", "1.1.16"), -1);
assertEquals("3", Version.compare("1", "16.1"), -1);
assertEquals("4", Version.compare("1.16.0", "1.1.0"), 1);
assertEquals("5", Version.compare("16.0.0", "1.0.1"), 1);
assertEquals("6", Version.compare("1.1.16", "1.1.1"), 1);
}
@Test
public void StringVersions() {
assertEquals("1", Version.compare("4.5.2r2", "4.5.2"), 1);
assertEquals("1", Version.compare("4.5.2r2", "4.5.2r3"), -1);
assertEquals("1", Version.compare("4.5.2r2", "4.5.20"), -1);
assertEquals("1", Version.compare("4.5.20r2", "4.5.20"), 1);
}
}
|
a07e62285a36f11f81dcda80520c0a1b48551383
|
[
"Java"
] | 3
|
Java
|
Joseph-Muc/arduino-eclipse-plugin
|
533582d3fcd92d4eaade891ef4129e82426c6a89
|
394d0697bb5aaa10ad0720a3dba37530166d351b
|
refs/heads/master
|
<repo_name>Jesus-Antonio-Martinez/EVA1_Practicas<file_sep>/EVA1_9_LlaveForanea.sql
-- MySQL dump 10.13 Distrib 5.7.12, for Win32 (AMD64)
--
-- Host: localhost Database: evaluacion_1
-- ------------------------------------------------------
-- Server version 5.5.20
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `carrera`
--
DROP TABLE IF EXISTS `carrera`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `carrera` (
`nombre` varchar(50) NOT NULL DEFAULT '',
`creditos` int(11) DEFAULT NULL,
`semestres` int(11) DEFAULT NULL,
`area` varchar(50) NOT NULL DEFAULT '',
PRIMARY KEY (`nombre`,`area`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `carrera`
--
LOCK TABLES `carrera` WRITE;
/*!40000 ALTER TABLE `carrera` DISABLE KEYS */;
/*!40000 ALTER TABLE `carrera` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `clientes`
--
DROP TABLE IF EXISTS `clientes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientes` (
`no_cliente` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(50) DEFAULT NULL,
`apellido` varchar(50) DEFAULT NULL,
`RFC` varchar(50) DEFAULT NULL,
`direccion` varchar(50) DEFAULT NULL,
`telefono` varchar(50) DEFAULT NULL,
`celular` varchar(50) DEFAULT NULL,
PRIMARY KEY (`no_cliente`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `clientes`
--
LOCK TABLES `clientes` WRITE;
/*!40000 ALTER TABLE `clientes` DISABLE KEYS */;
INSERT INTO `clientes` VALUES (5,'Juan','Perez',NULL,NULL,NULL,NULL);
/*!40000 ALTER TABLE `clientes` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `compras`
--
DROP TABLE IF EXISTS `compras`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `compras` (
`nombre_cliente` varchar(50) NOT NULL DEFAULT '',
`fecha` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`cantidad` float DEFAULT NULL,
PRIMARY KEY (`nombre_cliente`,`fecha`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `compras`
--
LOCK TABLES `compras` WRITE;
/*!40000 ALTER TABLE `compras` DISABLE KEYS */;
INSERT INTO `compras` VALUES ('jesus','2018-08-29 00:00:00',NULL);
/*!40000 ALTER TABLE `compras` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `estudiante`
--
DROP TABLE IF EXISTS `estudiante`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `estudiante` (
`no_control` varchar(10) NOT NULL DEFAULT '',
`nombre` varchar(50) DEFAULT NULL,
`apellido_paterno` varchar(50) DEFAULT NULL,
`apellido_materno` varchar(50) DEFAULT NULL,
`direccion` varchar(100) DEFAULT NULL,
`fecha_nacimiento` date DEFAULT NULL,
`lugar_nacimiento` varchar(50) DEFAULT NULL,
`pais_nacimiento` varchar(50) DEFAULT NULL,
`genero` varchar(50) DEFAULT NULL,
`no_telefono` varchar(50) DEFAULT NULL,
PRIMARY KEY (`no_control`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `estudiante`
--
LOCK TABLES `estudiante` WRITE;
/*!40000 ALTER TABLE `estudiante` DISABLE KEYS */;
INSERT INTO `estudiante` VALUES ('0001122','Juan);\n',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
/*!40000 ALTER TABLE `estudiante` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `facturas`
--
DROP TABLE IF EXISTS `facturas`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `facturas` (
`no_factura` int(11) NOT NULL AUTO_INCREMENT,
`fecha_compra` datetime DEFAULT NULL,
`no_cliente` int(11) DEFAULT NULL,
PRIMARY KEY (`no_factura`),
KEY `no_cliente` (`no_cliente`),
CONSTRAINT `facturas_ibfk_1` FOREIGN KEY (`no_cliente`) REFERENCES `clientes` (`no_cliente`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `facturas`
--
LOCK TABLES `facturas` WRITE;
/*!40000 ALTER TABLE `facturas` DISABLE KEYS */;
INSERT INTO `facturas` VALUES (2,'2018-08-22 00:00:00',5);
/*!40000 ALTER TABLE `facturas` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `horario`
--
DROP TABLE IF EXISTS `horario`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `horario` (
`materia` varchar(50) DEFAULT NULL,
`salon` varchar(50) DEFAULT NULL,
`profesor` varchar(50) DEFAULT NULL,
`hora` time DEFAULT NULL,
`dia` date DEFAULT NULL,
`no_control` varchar(20) DEFAULT NULL,
`carrera` varchar(50) DEFAULT NULL,
`creditos` int(11) DEFAULT NULL,
`semestre_actual` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `horario`
--
LOCK TABLES `horario` WRITE;
/*!40000 ALTER TABLE `horario` DISABLE KEYS */;
/*!40000 ALTER TABLE `horario` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `jobs`
--
DROP TABLE IF EXISTS `jobs`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `jobs` (
`id_jobs` int(11) NOT NULL,
`job_titule` varchar(50) NOT NULL DEFAULT ' ',
`salary_min` float DEFAULT '8000',
`salary_max` float DEFAULT '15000',
PRIMARY KEY (`id_jobs`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `jobs`
--
LOCK TABLES `jobs` WRITE;
/*!40000 ALTER TABLE `jobs` DISABLE KEYS */;
/*!40000 ALTER TABLE `jobs` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `materias`
--
DROP TABLE IF EXISTS `materias`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `materias` (
`Nombre` varchar(100) NOT NULL DEFAULT '',
`Creditos` int(11) DEFAULT NULL,
`Horas_Teoricas` int(11) DEFAULT NULL,
`Horas_Practicas` int(11) DEFAULT NULL,
`Carrera` varchar(3) DEFAULT NULL,
`Semestre` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`Nombre`,`Semestre`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `materias`
--
LOCK TABLES `materias` WRITE;
/*!40000 ALTER TABLE `materias` DISABLE KEYS */;
INSERT INTO `materias` VALUES ('matematicas',NULL,NULL,NULL,NULL,1);
/*!40000 ALTER TABLE `materias` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `nueva_carrera`
--
DROP TABLE IF EXISTS `nueva_carrera`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `nueva_carrera` (
`nombre` varchar(50) DEFAULT NULL,
`creditos` int(11) DEFAULT NULL,
`semestres` int(11) DEFAULT NULL,
`area` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `nueva_carrera`
--
LOCK TABLES `nueva_carrera` WRITE;
/*!40000 ALTER TABLE `nueva_carrera` DISABLE KEYS */;
INSERT INTO `nueva_carrera` VALUES ('Sistemas',500,9,'Sistemas y Computacion'),('Sistemas',500,9,'Sistemas y Computacion'),('Sistemas',500,9,'Sistemas y Computacion'),('Sistemas',500,9,'Sistemas y Computacion'),('Sistemas',500,9,'Sistemas y Computacion');
/*!40000 ALTER TABLE `nueva_carrera` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `nueva_carrerota`
--
DROP TABLE IF EXISTS `nueva_carrerota`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `nueva_carrerota` (
`nombre` varchar(50) DEFAULT NULL,
`creditos` int(11) DEFAULT NULL,
`semestres` int(11) DEFAULT NULL,
`area` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `nueva_carrerota`
--
LOCK TABLES `nueva_carrerota` WRITE;
/*!40000 ALTER TABLE `nueva_carrerota` DISABLE KEYS */;
/*!40000 ALTER TABLE `nueva_carrerota` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `paises`
--
DROP TABLE IF EXISTS `paises`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `paises` (
`clave` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(50) NOT NULL,
`poblacion` int(11) DEFAULT '1',
`continente` enum('Africa','America','Asia','Oceania','Europa') DEFAULT NULL,
PRIMARY KEY (`clave`),
UNIQUE KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `paises`
--
LOCK TABLES `paises` WRITE;
/*!40000 ALTER TABLE `paises` DISABLE KEYS */;
/*!40000 ALTER TABLE `paises` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `personal`
--
DROP TABLE IF EXISTS `personal`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `personal` (
`clave` int(11) DEFAULT NULL,
`nombre` varchar(50) NOT NULL DEFAULT '',
`apellido` varchar(50) NOT NULL DEFAULT '',
`departamento` varchar(50) DEFAULT NULL,
`salario` float DEFAULT NULL,
PRIMARY KEY (`nombre`,`apellido`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `personal`
--
LOCK TABLES `personal` WRITE;
/*!40000 ALTER TABLE `personal` DISABLE KEYS */;
/*!40000 ALTER TABLE `personal` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `personal2`
--
DROP TABLE IF EXISTS `personal2`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `personal2` (
`clave` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(50) NOT NULL,
`apellido` varchar(50) NOT NULL,
`departamento` enum('SISTEMAS','CONTABILIDAD','INHUMANOS','PRODUCCION') DEFAULT NULL,
`salario` float DEFAULT '15000',
PRIMARY KEY (`clave`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `personal2`
--
LOCK TABLES `personal2` WRITE;
/*!40000 ALTER TABLE `personal2` DISABLE KEYS */;
INSERT INTO `personal2` VALUES (1,'Ruben','Hernandez',NULL,15000),(2,'Juan','<NAME>','SISTEMAS',15000),(3,'x','y','INHUMANOS',5000),(5,'','',NULL,15000),(6,'','',NULL,15000);
/*!40000 ALTER TABLE `personal2` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `productos`
--
DROP TABLE IF EXISTS `productos`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `productos` (
`no_producto` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(50) DEFAULT NULL,
`precio` float DEFAULT NULL,
PRIMARY KEY (`no_producto`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `productos`
--
LOCK TABLES `productos` WRITE;
/*!40000 ALTER TABLE `productos` DISABLE KEYS */;
/*!40000 ALTER TABLE `productos` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-09-14 11:55:44
|
509309e5520f6da419528607db5c0c1d5ff60966
|
[
"SQL"
] | 1
|
SQL
|
Jesus-Antonio-Martinez/EVA1_Practicas
|
aa634bdf1524c72b0d9dc61b4f0c714efdc1d357
|
4a3d4ce54734addc8bdf33eacb8ce887b9487a9a
|
refs/heads/main
|
<file_sep>function preload()
{
}
function setup()
{
canvas = createCanvas (640,480);
canvas.position(100,250);
video = createCapture(VIDEO);
video.hide();
tint_color = "";
}
function draw()
{
image(video,0,0,640,480);
tint(tint_color);
}
function take_snapshot()
{
save('student_name.png');
}
function filter_tint()
{
tint_color = document.getElementById("color_name").value;
}
|
9c110303e255ad7ca0757d441dd3baecfac8c064
|
[
"JavaScript"
] | 1
|
JavaScript
|
ssada735/JavaScript
|
d00c6de2a58659d1680a6315446625cae4805798
|
f0f10507ba2c264a49ffa4426db4022840711649
|
refs/heads/master
|
<repo_name>raindogg/real-estate-app<file_sep>/db/migrate/20160909012958_remove_floors_from_listings.rb
class RemoveFloorsFromListings < ActiveRecord::Migration[5.0]
def change
remove_column :listings, :floor, :integer
end
end
|
1df3af27b000e32f42bd6fef6e9ca58eca81083c
|
[
"Ruby"
] | 1
|
Ruby
|
raindogg/real-estate-app
|
ef13c1d3c38f9c7dc5fc6de90900df7f05382464
|
66458dc3c72636825b328ef899b27d630a42980b
|
refs/heads/master
|
<file_sep>/*
* 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.
*/
package server;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
*
* @author Administraattori
*/
public class ServerSystemTray {
final PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon = new TrayIcon(createImage("systemtrayicon.png", "tray icon"));
final SystemTray tray = SystemTray.getSystemTray();
final Main MAIN;
ServerSystemTray(Main MAIN) {
this.MAIN = MAIN;
trayIcon.setToolTip("The Server Menu");
trayIcon.addActionListener( MAIN.actionListener );
trayIcon.setActionCommand( "cmanager" );
trayIcon.setPopupMenu( popup );
MenuItem start = new MenuItem("Start");
MenuItem stop = new MenuItem("Stop");
MenuItem status = new MenuItem("Status");
MenuItem cmanager = new MenuItem("Connections Manager");
MenuItem debugw = new MenuItem("Debug Window");
MenuItem exit = new MenuItem("Exit");
start.setActionCommand("start");
stop.setActionCommand("stop");
status.setActionCommand("status");
cmanager.setActionCommand("cmanager");
debugw.setActionCommand("debugw");
exit.setActionCommand("exit");
start.addActionListener( MAIN.actionListener );
stop.addActionListener( MAIN.actionListener );
status.addActionListener( MAIN.actionListener );
cmanager.addActionListener( MAIN.actionListener );
debugw.addActionListener( MAIN.actionListener );
exit.addActionListener( MAIN.actionListener );
popup.add(start);
popup.add(stop);
popup.add(status);
popup.add(cmanager);
popup.add(debugw);
popup.add(exit);
try {
tray.add( trayIcon );
} catch (AWTException e) {
System.out.println( "Error: TrayIcon could not be added." );
}
}
//Obtain the image URL
protected static Image createImage(String path, String description) {
String sPath = ServerSystemTray.class.getResource(".").getPath();
URL imageURL = ServerSystemTray.class.getResource(path);
if (imageURL == null) {
System.err.println("Resource not found: " + sPath + path );
System.out.println("Cannot continue.");
System.exit(0);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
}
<file_sep>/*
* 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.
*/
package client;
import java.awt.Dimension;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administraattori
*/
public class StaticData {
private static Properties Settings = null;
private static String SettingsFilename = "settings.xml";
public static Properties getSettings() {
if (Settings == null) {
Settings = new Properties();
try {
Settings.load( new FileReader( SettingsFilename ) );
} catch (IOException ex) {
System.out.println( "Could not save '" + SettingsFilename + "' file" );
}
}
return Settings;
}
public static void saveSettings() {
if (Settings != null) {
try {
Settings.store( new FileWriter(SettingsFilename), "Client configuration file");
} catch (IOException ex) {
System.out.println( "Could not save '" + SettingsFilename + "' file,\n" + ex.getLocalizedMessage() );
}
}
}
public static String getWindowTitle() {
return "The Client";
}
public static Dimension getWindowSize() {
return new Dimension(640,480);
}
}
<file_sep>/*
* 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.
*/
package client.j;
import client.Main;
import client.StaticData;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.WindowConstants;
/**
*
* @author Administraattori
*/
public class JSettingsWindow extends JInnerWindow {
private Main MAIN;
private JLoginWindowActionListener actionListener;
JTextField jtfServerAddress;
JTextField jtfServerPort;
public JSettingsWindow(Main main) {
super("settings");
MAIN = main;
actionListener = new JLoginWindowActionListener( this , MAIN );
this.setTitle( "Settings" );
this.setLocation( 20 , 20 );
this.setSize( 640, 480 );
this.setClosable( true );
this.setResizable( true );
this.setDefaultCloseOperation( JInternalFrame.DISPOSE_ON_CLOSE );
this.setContentPane();
this.loadSettings();
}
@Override
public void getObject(Object o) {
}
private void setContentPane() {
JPanel content = (JPanel) this.getContentPane();
JTabbedPane jtp = new JTabbedPane();
jtp.addTab( "Server settings" , this.getServerSettings() );
content.add(jtp);
}
private JPanel getServerSettings() {
JPanel content = new JPanel();
SpringLayout layout = new SpringLayout();
content.setLayout( layout );
Dimension minimLabelSize = new Dimension(150,27);
Dimension minimJtfSize = new Dimension(200,30);
JLabel labelServerAddress = new JLabel("Server address");
labelServerAddress.setMinimumSize(minimLabelSize);
labelServerAddress.setPreferredSize(minimLabelSize);
jtfServerAddress = new JTextField( "address");
jtfServerAddress.setMinimumSize( minimJtfSize );
jtfServerAddress.setPreferredSize( minimJtfSize );
JLabel labelServerPort = new JLabel("Server port");
labelServerPort.setMinimumSize(minimLabelSize);
labelServerPort.setPreferredSize(minimLabelSize);
jtfServerPort = new JTextField("44");
jtfServerPort.setMinimumSize(minimJtfSize);
jtfServerPort.setPreferredSize(minimJtfSize);
content.add( labelServerAddress );
content.add( jtfServerAddress );
// First label to upper-left corner
layout.putConstraint( SpringLayout.WEST, labelServerAddress, 5, SpringLayout.WEST, content );
layout.putConstraint( SpringLayout.NORTH, labelServerAddress, 5, SpringLayout.NORTH, content );
// Textfield next to label
layout.putConstraint( SpringLayout.WEST, jtfServerAddress, 5, SpringLayout.EAST, labelServerAddress );
layout.putConstraint( SpringLayout.NORTH, jtfServerAddress, 5, SpringLayout.NORTH, content );
content.add( labelServerPort );
content.add( jtfServerPort );
// Next line, first label
layout.putConstraint( SpringLayout.WEST, labelServerPort, 5, SpringLayout.WEST, content );
layout.putConstraint( SpringLayout.NORTH, labelServerPort, 5, SpringLayout.SOUTH, labelServerAddress );
// Then, again, textfield next to it
layout.putConstraint( SpringLayout.WEST, jtfServerPort, 5, SpringLayout.EAST, labelServerPort );
layout.putConstraint( SpringLayout.NORTH, jtfServerPort, 5, SpringLayout.SOUTH, jtfServerAddress );
// Save settings button
Dimension buttonSize = new Dimension( 100,30 );
JButton saveButton = new JButton( "Save" );
saveButton.setMinimumSize( buttonSize );
saveButton.setPreferredSize( buttonSize );
saveButton.setActionCommand( "saveServerSettings" );
saveButton.addActionListener( this.actionListener );
content.add( saveButton );
layout.putConstraint( SpringLayout.EAST , saveButton , -5 , SpringLayout.EAST , content );
layout.putConstraint( SpringLayout.SOUTH , saveButton , -5 , SpringLayout.SOUTH , content );
return content;
}
private void loadSettings() {
Properties settings = StaticData.getSettings();
this.jtfServerAddress.setText( settings.getProperty("ServerAddress" ) );
this.jtfServerPort.setText( settings.getProperty("ServerPort") );
}
}
<file_sep>/*
* 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.
*/
package client.j;
import client.Main;
import client.x.XMainWindow;
import common.LogInfo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JOptionPane;
/**
*
* @author Administraattori
*/
public class JMainWindowActionListener implements ActionListener, WindowListener {
Main MAIN;
public JMainWindowActionListener(Main aMain) {
MAIN = aMain;
}
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "editSettings":
this.editSettingsAction();
break;
case "login":
this.loginAction();
break;
case "logout":
this.logoutAction();
break;
case "connect":
Runnable r = new Runnable() {
@Override
public void run() {
MAIN.MAINWINDOW.busy( true );
MAIN.makeConnection();
MAIN.MAINWINDOW.busy( false );
}
};
Thread t = new Thread(r);
t.start();
break;
case "disconnect":
MAIN.closeConnection();
break;
case "close":
this.windowClosing();
break;
}
}
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
this.windowClosing();
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
private void loginAction() {
if (!this.MAIN.isLoggedIn()) {
JLoginWindow LW = new JLoginWindow( MAIN );
this.MAIN.addWindow( LW );
LW.setVisible( true );
}
}
private void logoutAction() {
System.out.println("logoutAction");
if (this.MAIN.isLoggedIn()) {
LogInfo li = new LogInfo();
li.setStatus( LogInfo.LOG_OUT );
System.out.println("Sending LOG_OUT");
this.MAIN.send( li );
} else {
System.out.println("Already logged out!");
}
}
private void windowClosing() {
JMainWindow window = (JMainWindow) MAIN.MAINWINDOW;
int confirm = JOptionPane.showInternalOptionDialog(window.getDesktopPane(),
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
window.dispose();
MAIN.closeProgram();
}
}
private void editSettingsAction() {
JSettingsWindow SW = new JSettingsWindow( MAIN );
this.MAIN.addWindow( SW );
SW.setVisible( true );
}
}
<file_sep>/*
* 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.
*/
package client.j;
import client.x.InnerWindow;
import javax.swing.JInternalFrame;
/**
*
* @author Administraattori
*/
abstract public class JInnerWindow extends JInternalFrame implements InnerWindow {
private String sWindowCode;
private JMainWindow MAINWINDOW = null;
public JInnerWindow( String sWindowCode ) {
this.setWindowcode( sWindowCode );
}
abstract public void getObject(Object o);
@Override
public void setWindowcode(String sCode) { this.sWindowCode = sCode; }
@Override
public String getWindowcode() { return sWindowCode; }
public void setMainWindow( JMainWindow mw ) { this.MAINWINDOW = mw; }
public JMainWindow getMainWindow() { return this.MAINWINDOW; }
}
<file_sep>/*
* 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.
*/
package client.j;
import client.Main;
import client.x.InnerWindow;
import common.LogInfo;
import common.XMLObject;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/**
*
* @author Administraattori
*/
public class JLoginWindow extends JInnerWindow implements ActionListener {
private JTextField USERNAME;
private JPasswordField PASSWORD;
private final Main MAIN;
public JLoginWindow( Main MAIN ) {
super("LOGINWINDOW");
this.MAIN = MAIN;
this.setTitle( "Login Window" );
this.setSize( 380, 180 );
this.setDefaultCloseOperation( JInternalFrame.DISPOSE_ON_CLOSE );
this.setLocation( 10, 10 );
this.setClosable( true );
this.setContent();
}
private void setContent() {
this.getContentPane().setLayout( null );
JLabel label;
JButton loginButton;
JButton cancelButton;
USERNAME = new JTextField();
PASSWORD = new JPasswordField();
int iLabelX = 5;
int iFieldX = 150;
int iLabelHeight = 27;
int iLabelWidth = 100;
int iFieldHeigth = 27;
int iFieldWidth = 200;
int iButtonHeight = 27;
int iButtonWidth = 110;
int iCancelButtonX = 40;
int iCancelButtonY = 70;
int iLoginButtonX = 220;
int iLoginButtonY = 70;
USERNAME.setSize( iFieldWidth , iFieldHeigth );
PASSWORD.setSize( iFieldWidth , iFieldHeigth );
USERNAME.setLocation( iFieldX, 5 );
PASSWORD.setLocation( iFieldX, 30 );
PASSWORD.setActionCommand( "login" );
PASSWORD.addActionListener( this );
label = new JLabel( "Username : " );
label.setSize( iLabelWidth , iLabelHeight );
label.setLocation( iLabelX, 5);
this.getContentPane().add( label );
label = new JLabel( "Password : " );
label.setSize( iLabelWidth , iLabelHeight );
label.setLocation( iLabelX, 30);
this.getContentPane().add( label );
this.getContentPane().add( USERNAME );
this.getContentPane().add( PASSWORD );
loginButton = new JButton("Log IN");
loginButton.setSize( iButtonWidth , iButtonHeight );
loginButton.setLocation( iLoginButtonX , iLoginButtonY );
loginButton.setActionCommand( "login" );
loginButton.addActionListener( this );
this.getContentPane().add( loginButton );
cancelButton = new JButton("Cancel");
cancelButton.setSize( iButtonWidth , iButtonHeight );
cancelButton.setLocation( iCancelButtonX , iCancelButtonY );
cancelButton.setActionCommand( "cancel" );
cancelButton.addActionListener( this );
this.getContentPane().add( cancelButton );
}
@Override
public void actionPerformed(ActionEvent e) {
switch ( e.getActionCommand() ) {
case "login":
this.logIn( this.USERNAME.getText() , this.PASSWORD.getPassword() );
break;
case "cancel":
this.setVisible( false );
this.dispose();
break;
}
}
void logIn(String username, char[] password) {
LogInfo logTry = new LogInfo();
logTry.setReceivingWindowcode( this.getWindowcode() );
logTry.setUsername( username );
logTry.setPassword( LogInfo.hash(password) );
this.MAIN.send(logTry);
}
@Override
public void getObject(Object o) {
if (o instanceof LogInfo) {
LogInfo info = (LogInfo) o;
switch( info.getStatus() ) {
case LogInfo.FAIL:
this.MAIN.MAINWINDOW.setLoggedIn( false );
JOptionPane.showInternalMessageDialog( this , "Login failed, wrong usename and/or password!");
break;
case LogInfo.SUCCESS:
this.MAIN.setLoggedIn( true );
this.MAIN.MAINWINDOW.setLoggedIn( true );
JOptionPane.showInternalMessageDialog( this , "You have logged in successfully!");
this.MAIN.MAINWINDOW.removeWindow( (InnerWindow) this );
break;
case LogInfo.TRY:
JOptionPane.showInternalMessageDialog( this , "Weird happening has occurred about login!");
break;
}
}
}
}<file_sep>/*
* 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.
*/
package client.x;
import javax.swing.JInternalFrame;
/**
*
* @author Administraattori
*/
public interface InnerWindow {
public abstract void getObject(Object o);
public void setWindowcode( String sCode);
public String getWindowcode();
public void dispose();
}
<file_sep>/*
* 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.
*/
package common;
import java.io.Serializable;
/**
*
* @author Administraattori
*/
public class Sendable implements Serializable {
private String sWindowcode;
public void setReceivingWindowcode( String sWindowCode ) { this.sWindowcode = sWindowCode; }
public String getReceivingWindowcode() { return this.sWindowcode; }
}
<file_sep>/*
* 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.
*/
package common;
/**
*
* @author Administraattori
*/
public class StringTools {
public static String searchFromArrayAndGetNext(String[] stack, String needle) {
String sNext = null;
for (int i = 0 ; i < stack.length; i++) {
if (stack[i].equalsIgnoreCase(needle)) {
try {
i++;
sNext = stack[i];
break;
} catch (Exception e) {}
}
}
return sNext;
}
}
<file_sep>/*
* 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.
*/
package server;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import server.cw.ConnectionsTableModel;
/**
*
* @author Administraattori
*/
public class ConnectionsWindow extends JFrame implements ActionListener {
private ConnectionsTableModel ctm;
private JTable table;
private JMenuBar jmb;
private JScrollPane jsp;
private final Main MAIN;
ConnectionsWindow(Main mMain) {
this.MAIN = mMain;
this.setTitle( "Connections Manager" );
this.setSize(640,480);
this.setLocationRelativeTo( null );
this.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
jmb = new JMenuBar();
JMenu jmMenu = new JMenu("Menu");
JMenuItem jmiRefresh = new JMenuItem("Refresh");
jmiRefresh.setActionCommand("refresh");
jmiRefresh.addActionListener( this );
jmMenu.add( jmiRefresh );
jmb.add( jmMenu );
this.setJMenuBar( jmb );
JPopupMenu popupmenu = new JPopupMenu();
JMenuItem closeConnection = new JMenuItem("Close connection");
closeConnection.setActionCommand("closeconnection");
closeConnection.addActionListener( this );
popupmenu.add( closeConnection );
ctm = new ConnectionsTableModel( mMain );
table = new JTable( ctm );
table.setComponentPopupMenu( popupmenu );
jsp = new JScrollPane( table );
this.getContentPane().add( jsp );
}
@Override
public void actionPerformed(ActionEvent e) {
switch( e.getActionCommand() ) {
case "refresh":
this.refreshAction();
break;
case "closeconnection":
this.closeSelectedConnection();
break;
}
}
private void refreshAction() {
ctm.updateData();
ctm.fireTableDataChanged();
}
private long getConnectionID(int iRow) {
long lID = this.ctm.getID( iRow );
return lID;
}
private void closeSelectedConnection() {
int iSelectedRow = this.table.getSelectedRow();
if (iSelectedRow > -1) {
long lID = this.getConnectionID( iSelectedRow );
this.MAIN.closeConnection( lID );
}
}
}<file_sep>/*
* 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.
*/
package server;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
/**
*
* @author Administraattori
*/
public class ServerActionListener implements ActionListener {
private final Main MAIN;
public ServerActionListener(Main MAIN) {
this.MAIN = MAIN;
}
@Override
public void actionPerformed(ActionEvent e) {
switch(e.getActionCommand()) {
case "start":
this.startAction();
break;
case "stop":
this.stopAction();
break;
case "status":
this.statusAction();
break;
case "cmanager":
this.cmanagerAction();
break;
case "debugw":
this.debugwAction();
break;
case "exit":
this.exitAction();
break;
}
}
public void showMessage(String sMessage) {
this.MAIN.SST.trayIcon.displayMessage("The Server Message", sMessage, TrayIcon.MessageType.INFO);
}
private void startAction() {
if (MAIN.bSystemTray) showMessage( this.MAIN.startServer());
else JOptionPane.showMessageDialog(null, this.MAIN.startServer() );
}
private void stopAction() {
if (MAIN.bSystemTray) showMessage( this.MAIN.stopServer());
else JOptionPane.showMessageDialog(null, this.MAIN.stopServer() );
}
private void statusAction() {
JOptionPane.showMessageDialog(null, this.MAIN.getStatusMessage() );
}
private void exitAction() {
JOptionPane.showMessageDialog(null, "Bye Bye!" );
this.MAIN.exit();
}
private void cmanagerAction() {
this.MAIN.connectionManagerWindow();
}
private void debugwAction() {
this.MAIN.toggleDebugWindowVisibility();
}
}
<file_sep>AmepeNB
=======
Project Amepe, using NetBeans 8.x
<file_sep>package client;
import client.j.JMainWindow;
import client.j.JMainWindowActionListener;
import client.x.InnerWindow;
import client.x.XMainWindow;
import common.LogInfo;
import common.Sendable;
import common.StringTools;
import common.XMLObject;
import java.awt.GraphicsEnvironment;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Properties;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class Main {
private static String sLookAndFeelName = null;
private boolean bLoggedIn = false;
private String sAddress = null;
private int iServerPort = -1;
private ClientConnection connection = null;
public XMainWindow MAINWINDOW = null;
public Main(String[] args) {
Properties settings = StaticData.getSettings();
this.sAddress = settings.getProperty( "ServerAddress" );
this.iServerPort = Integer.parseInt( settings.getProperty("ServerPort") );
windowInit();
}
private void windowInit() {
if (!GraphicsEnvironment.isHeadless()) {
SwingUtilities.invokeLater(() -> {
MAINWINDOW = new JMainWindow( this );
});
}
}
public synchronized boolean isLoggedIn() { return this.bLoggedIn; }
public static void main(String[] args) {
boolean bListOnly = false;
if (args.length == 1) {
if (args[0].equals("-listlnf")) {
bListOnly = true;
}
}
if (args.length > 1) {
sLookAndFeelName = StringTools.searchFromArrayAndGetNext(args, "-lnf");
}
if (sLookAndFeelName == null) sLookAndFeelName = "Nimbus";
System.out.println("System lnf:" + UIManager.getSystemLookAndFeelClassName());
System.out.println("Lookin' for installed Look´n´Feels:");
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
System.out.print("- '"+info.getName() + "'");
if (info.getClassName().equals(UIManager.getSystemLookAndFeelClassName())) {
System.out.print(" (system)");
}
if (sLookAndFeelName.equals(info.getName())) {
if (!bListOnly) System.out.println(", yes!");
if (!bListOnly) UIManager.setLookAndFeel(info.getClassName());
} else {
if (!bListOnly) System.out.println(", no");
}
if (bListOnly) System.out.println("");
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
System.out.println("");
JFrame.setDefaultLookAndFeelDecorated(true);
if (!bListOnly) new Main(args);
}
public void makeConnection() {
if (this.sAddress != null && this.iServerPort > -1) {
if (connection == null) {
System.out.println("Connecting...");
try {
Socket socket = new Socket();
if (sAddress.equalsIgnoreCase("localhost")){
sAddress = InetAddress.getLocalHost().getHostAddress();
}
socket.connect( new InetSocketAddress( sAddress, iServerPort), 500);
connection = new ClientConnection( this , socket );
connection.start();
this.MAINWINDOW.setLoggedIn( false );
this.MAINWINDOW.setConnected( true );
MAINWINDOW.showMessage("Connected!");
} catch (IOException e) {
MAINWINDOW.showMessage( "FAIL! Can´t connect to server " + sAddress + ":" + iServerPort + "\nError message: " + e.getLocalizedMessage() );
}
} else {
MAINWINDOW.showMessage("Already connected!");
}
}
}
public void closeConnection() {
if (connection != null) {
connection.terminate();
connection = null;
}
this.MAINWINDOW.setLoggedIn( false );
this.MAINWINDOW.setConnected( false );
}
public void closeProgram() {
this.closeConnection();
System.exit( 0 );
}
public void receive(Sendable sendable) {
String sWindowCode = sendable.getReceivingWindowcode();
InnerWindow iw = this.MAINWINDOW.getWindow(sWindowCode);
if (iw != null) {
iw.getObject( sendable );
} else {
if (sendable instanceof LogInfo) {
LogInfo li = (LogInfo) sendable;
Runnable r = new Runnable() {
public void run() {
if (li.getStatus() == LogInfo.LOG_OUT) {
System.out.println("Log Out");
MAINWINDOW.setLoggedIn( false );
setLoggedIn( false );
MAINWINDOW.showMessage( "Logged out!");
}
}
};
Thread t = new Thread(r);
t.start();
}
}
}
public void addWindow(InnerWindow iw) {
this.MAINWINDOW.addWindow( iw );
}
public void send(Sendable sendable) {
String sendThis = XMLObject.getXML( sendable );
if (connection != null) {
this.connection.writeln( sendThis );
}
}
public void removeWindow(InnerWindow innerWindow) {
this.MAINWINDOW.removeWindow( innerWindow );
}
public void setXWindow(XMainWindow mainWindow) {
this.MAINWINDOW = mainWindow;
}
public void setLoggedIn(boolean b) {
this.bLoggedIn = b;
}
}
|
acd2eb9b9612989e7d13639bd2bdc175941fcf16
|
[
"Markdown",
"Java"
] | 13
|
Java
|
petkos1981/AmepeNB
|
752d6e0c4a906a255de03e89a7efa9d875b74514
|
adbf7b676cb878fdfaa5b3e611ee8f434a8d576f
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
use App\Project;
use App\Bid;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$projects = DB::table('projects')->select('id', 'name', 'description', 'group', 'investor', 'leader', 'money', 'approval', 'status', 'userId', 'created_at')
->get()->toarray();
return View('layouts.index', compact('projects'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$projects = DB::table('projects')->select('*')
->get()->toarray();
return view('project.list_project', compact('projects'));
}
public function createadd()
{
return View('project.add_project');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validate = Validator::make(
$request->all(),
[
'name' => ['required', 'string', 'max:255'],
'description' => ['required', 'string', 'min:10'],
'group' => ['required', 'string', 'max:8'],
'investor' => ['required', 'string', 'max:255'],
'leader' => ['required', 'string', 'max:255'],
'oda' => ['required', 'max:11'],
'money' => ['required', 'min:7' ,'max:255'],
'approval' => ['required', 'min:5', 'max:10'],
]
);
if ($validate->fails()) {
return View('project.add_project')->withErrors($validate);
}
$projects = new Project();
$projects->name = $request->name;
$projects->description = $request->description;
$projects->group = $request->group;
$projects->investor = $request->investor;
$projects->leader = $request->leader;
$projects->oda = $request->oda;
$projects->money = $request->money;
$projects->approval = $request->approval;
$projects->userId = $request->userId;
$projects->status = 0;
$projects->save();
return redirect()->action('ProjectController@create');
}
/**
* Display the specified resource.
*
* @param \App\Project $project
* @return \Illuminate\Http\Response
*/
public function show($id)
{
if(Auth::check()) {
$userId = Auth::id();
$bids = Bid::where('projectId', '=', $id)->where('userId', '=', $userId)->count();
}
$projects = Project::where('id', '=', $id)->select('*')->first();
return View('project.detail', compact('projects', 'bids'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Project $project
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$project = Project::where('id', '=', $id)->select('*')->first();
return View('project.edit', compact('project'));
}
public function editProject(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'description' => ['required', 'string', 'min:10'],
'group' => ['required', 'string', 'max:8'],
'investor' => ['required', 'string', 'max:255'],
'leader' => ['required', 'string', 'max:255'],
'oda' => ['required', 'max:11'],
'money' => ['required', 'min:7' ,'max:255'],
'approval' => ['required', 'min:5', 'max:10'],
]);
Project::where('id', '=', $request->id)->update($request->except(['_token']));
return redirect()->action('ProjectController@create');
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Project $project
* @return \Illuminate\Http\Response
*/
public function update($id)
{
$projects = Project::where('id', '=', $id)->update(['status' => 1]);
return redirect()->action('ProjectController@create');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Project $project
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Project::destroy($id);
return redirect()->action('ProjectController@create');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function user()
{
$users = DB::table('users')->select('id', 'name', 'email', 'level', 'address', 'phone', 'status')->get()->toarray();
return view('users.user', compact('users') );
}
public function customer()
{
$users = DB::table('users')->select('name', 'email', 'level', 'address', 'phone', 'status')->get()->toarray();
return view('users.customer', compact('users') );
}
public function contractor()
{
$users = DB::table('users')->select('name', 'email', 'level', 'address', 'phone', 'status')->get()->toarray();
return view('users.contractor', compact('users') );
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create($id)
{
$users = DB::table('users')->where('id', '=', $id)->update(['status' => 1]);
return redirect()->action('UserController@user');
}
public function dangnhap()
{
//
return View('auth.login');
}
public function dangky()
{
//
return View('auth.register');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
Route::get('/', 'ProjectController@index' )->name('index');
//route login
Route::get('login','UserController@dangnhap')->name('login');
Route::get('register','UserController@dangky')->name('register');
//route user
Route::get('user','UserController@user')->name('user');
Route::get('customer','UserController@customer')->name('customer');
Route::get('contractor','UserController@contractor')->name('contractor');
Route::get('approval/{id}', 'UserController@create')->name('approval');
//route project
Route::get('add_project','ProjectController@createadd')->name('add_project');
Route::post('add_project', 'ProjectController@store');
Route::get('list_project', 'ProjectController@create')->name('list_project');
Route::get('detail_project/{id}', 'ProjectController@show')->name('detail_project');
Route::get('post/{id}', 'ProjectController@update')->name('post');
Route::get('edit/{id}', 'ProjectController@edit')->name('edit');
Route::post('editproject', 'ProjectController@editProject')->name('editproject');
Route::get('delete/{id}', 'ProjectController@destroy')->name('delete');
//route bidding
Route::post('bidding', 'BidController@store')->name('bidding');
<file_sep><?php
namespace App\Http\Controllers;
use App\Bid;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class BidController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
public function show($id)
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validate = Validator::make(
$request->all(),
[
'userId' => ['required', 'string', 'max:255'],
'projectId' => ['required', 'string', 'max:255'],
'money' => ['required', 'min:7' ,'max:255'],
]
);
if ($validate->fails()) {
return redirect()->action('ProjectController@index')->withErrors($validate);
}
$bids = new Bid();
$bids->userId = $request->userId;
$bids->projectId = $request->projectId;
$bids->money = $request->money;
$bids->save();
return redirect()->action('ProjectController@index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
|
f4ef9d210be05a96e93375f4c1855843a8f7c737
|
[
"PHP"
] | 4
|
PHP
|
bao11111997/laravel_php
|
1ecc1f3077bbcecccc5843f0e0a77292439a54a1
|
0b3bdb46f39e99735c2deb458daac6f643d3b079
|
refs/heads/master
|
<repo_name>xiaozhan-source/-<file_sep>/js/小米哟品.js
// 菜单栏轮播图
$(function(){
// 设置菜单栏图片轮播
var i=0;
$(".circle li").eq(0).css({background:'red'})
$(".btn2").click(function(){
if(i<6){
i++
}else{
i=0
}
$(".mi_mdown_right").css({background:"url(./img/背景图/背景图"+i+".jpg) no-repeat",backgroundSize:"850px 358px"});
$(".circle li").eq(i).css({background:'red'});
$(".circle li").eq(i)
.siblings()
.css({background:'white'});
})
//设置图片自动轮播
var time=setInterval(function(){
$(".btn2").click()
},2000)
// $(".mi_mdown_right").mouseenter()
$(".btn1").click(function(){
if(i>0){
i--
}else{
i=6;
}
$(".mi_mdown_right").css({background:"url(./img/背景图/背景图"+i+".jpg) no-repeat",backgroundSize:"850px 358px"});
$(".circle li").eq(i).css({background:'red'});
$(".circle li").eq(i).siblings().css({background:'white'});
})
// 菜单左侧分类隐藏
var menuleft=$('.mdown_fenlei li');
console.log($('.mdown_fenlei_img').eq(0))
menuleft.mouseover(function(){
var index=$(this).index();
$('.mdown_fenlei_img').children().eq(index).css('display','block').siblings().css('display','none');
})
menuleft.mouseout(function(){
$('.mdown_fenlei_img').children().css('display','none')
})
// 限时购倒计时
// 小火箭
$(window).scroll(function(){
var xiaohuojian=$(document).scrollTop();
$('.fixed_top').click(function(){
$('html,body').stop().animate({'scrollTop':1},1000)
})
$('.fixed_top').mousemove(function(){
$('.fixed_top div').css('background-position','0px -1323px')
$('.fixed_top p').css('color','#845f3f')
})
$('.fixed_top').mouseout(function(){
$('.fixed_top div').css('background-position','0px -1289px')
$('.fixed_top p').css('color','#333333')
})
})
// 限时购轮播图
})
window.onload=function(){
//补零函数,当数字小于10时自动给前边添加0
function addZero(i) {
return i < 10 ? "0" + i: i + "";
}
time=setInterval(function(){
var nowtime=new Date();
var endtime=new Date("2019/10/23,20:00:00")
var lefttime=parseInt((endtime.getTime()-nowtime.getTime())/1000);
// var d=parseInt(lefttime/60/60/24)
h=parseInt(lefttime/60/60%24)
m=parseInt(lefttime/60%60)
s=parseInt(lefttime%60)
// console.log(111)
h=addZero(h);
m=addZero(m);
s=addZero(s);
document.getElementsByClassName('tshop_hour')[0].innerHTML=h;
// document.querySelector(".tshop_hour").innerHTML=h;
document.querySelector(".tshop_men").innerHTML=m;
document.querySelector(".tshop_sec").innerHTML=s;
if(lefttime<=0){
clearInterval(time)
console.log(111)
}
},1000)
}
// 登录注册
// 限时购轮播图
// 右侧悬浮窗鼠标移入事件
//
|
5d46c12272cbb3f9f6ad82c4553ffef84875f9f1
|
[
"JavaScript"
] | 1
|
JavaScript
|
xiaozhan-source/-
|
2c9e537931218d63256f6ca8502ac934cb30d1ed
|
2bac375a7e477d3848751c95e94e3506b806a789
|
refs/heads/main
|
<repo_name>inzayn99/React-Route<file_sep>/src/Pages/Services.jsx
import React from "react";
const Google = () =>{
return <h1>I'M SERVICES PAGE</h1>
};
export default Google;<file_sep>/src/Pages/Menu.jsx
import React from "react";
import { NavLink } from "react-router-dom";
const Menu = () => {
return (
<>
<NavLink exact activeClassName="active_class" to="/about">About</NavLink>
<NavLink exact activeClassName="active_class" to="/Contact">Contact</NavLink>
<NavLink exact activeClassName="active_class" to="/Services">Services</NavLink>
</>
);
};
export default Menu;<file_sep>/src/Pages/About.jsx
import React from "react";
const About = () =>{
return <h1>I'M ABOUT PAGE </h1>
};
export default About;
|
138b1a05aff49602c98161b55de5dde3fb70339f
|
[
"JavaScript"
] | 3
|
JavaScript
|
inzayn99/React-Route
|
06e487386a6208ee8f3e07f808f396ebd6d61f3e
|
e2eb17c1eda2b1d49960d5c7eebceb7a0ee9d695
|
refs/heads/master
|
<file_sep># Generated by Django 3.1.7 on 2021-02-25 09:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('newapp', '0004_auto_20210225_1437'),
]
operations = [
migrations.AddField(
model_name='section',
name='fname',
field=models.CharField(default=1, max_length=30),
preserve_default=False,
),
migrations.AlterField(
model_name='section',
name='music',
field=models.CharField(max_length=30),
),
]
<file_sep>from django.urls import path
from.views import home,formpage
urlpatterns=[
path('',home,name='homep'),
path('formpagu/',formpage,name='formk'),
]<file_sep>from django.contrib import admin
from.models import member
admin.site.register(member)
# admin.site.register(section)
<file_sep>from django.db import models
class member(models.Model):
fname=models.CharField(max_length=30)
lname=models.CharField(max_length=20)
age=models.IntegerField()
password=models.CharField(max_length=12)
email=models.EmailField(max_length=40)
birthdate=models.DateField()
def __str__(self):
return self.fname + " | " +self.lname
# created another table in databae
# class section(models.Model):
# music=models.CharField(max_length=30)
# fname=models.CharField(max_length=30)
# artist=models.CharField(max_length=100)
#
#
# def __str__(self):
# return self.music + " || "+self.artist
<file_sep># Generated by Django 3.1.7 on 2021-02-25 09:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('newapp', '0003_section'),
]
operations = [
migrations.AlterField(
model_name='section',
name='music',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='newapp.member'),
),
]
<file_sep>from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import member
from .forms import memberform
from django.contrib import messages
from django.urls import reverse
def home(request):
all_members=member.objects.all()
return render(request,'homepage.html',{"all":all_members})
def formpage(request):
form = memberform()
if request.method == "POST":
form=memberform(request.POST or None)
if form.is_valid():
form.save()
context={'forms':form}
return render(request,"lap.html",context)
# else:
# return redirect("/")
<file_sep># Generated by Django 3.1.7 on 2021-02-25 16:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('newapp', '0005_auto_20210225_1446'),
]
operations = [
migrations.DeleteModel(
name='section',
),
]
<file_sep>from django import forms
from .models import member
class memberform(forms.ModelForm):
class Meta:
model = member
#it will take the fields from the models
fields = ['fname','lname','age','<PASSWORD>','email','birthdate']
|
23e236503c6c3e3fd3510f579def26401202f03b
|
[
"Python"
] | 8
|
Python
|
shalman13091994/djangowithmodels
|
4cbc89ea53ac239b1e7edee4e10fe984523aea0d
|
5bcbd885209c7d9414ed2a40129a81309c330879
|
refs/heads/master
|
<file_sep>const changeHash = (hash) => {
location.hash = hash;
};
export const inicio = () => {
const inicioTmp = `
<div class="inicio-background">
<h1 class="title-text">I'M NOT</h1>
<h3 class="sub-title">What a paper says</h3>
<img class ="icon-img" src="/img/iconinicio.png" alt="">
<button id="start-btn" class="start-btn">EMPEZAR</button>
<button id="login-btn" class="login-btn">TENGO UNA CUENTA</button>
</div>
`;
const inicioElement = document.createElement('div');
inicioElement.innerHTML = inicioTmp;
const toIntroSection = inicioElement.querySelector('#start-btn');
toIntroSection.addEventListener('click', () => {
changeHash('/introduction')
});
return inicioElement;
}<file_sep>export const signIn = () => {
const templateSignIn = `
<div id="signin-container" class="signin-container">
<h2>Ingresa directamente con:</h2>
<button id="facebook-login" class="fa fa-facebook"></button>
<button id="google-login" class="fa fa-google"></button>
<button id="twitter-login" class="fa fa-twitter"></button>
</div>
</div>`;
const divElem = document.createElement('div');
divElem.innerHTML = templateSignIn;
// const btnFacebook = divElem.querySelector('#facebook-login');
// btnFacebook.addEventListener('click', facebookOnClick);
// const btnGoogle = divElem.querySelector('#google-login');
// btnGoogle.addEventListener('click', googleOnClick);
// const btnTwitter = divElem.querySelector('#twitter-login');
// btnTwitter.addEventListener('click', twitterOnClick);
return divElem;
}; <file_sep>const searchDataFunction = (data, dataSearch) => {
let dataCopy = []; // Copia de la data
let arraySearch = []; // Data en minúsculas
let newArraySearch = [];
for (let i = 0; i < data.length; i++)
dataCopy.push(Object.assign({}, data[i]));
for (let i = 0; i < dataCopy.length; i++) {
arraySearch.push(dataCopy[i].name.toLowerCase());
if (arraySearch[i].indexOf(dataSearch.toLowerCase()) !== -1) {
newArraySearch.push(dataCopy[i]);
}
}
return newArraySearch;
};<file_sep>const changeHash = (hash) => {
location.hash = hash;
};
export const introduction = () => {
const tmpIntroduction = `
<div class="inicio-background">
<h1 class="sub-title">Tú eliges cambiar</h1>
<div class="rectangle"></div>
<div id="intro-btn" class="intro-box">
<div>
<h2 class="intro-subtitle">Escribe</h2>
<p>Lo que quieres comentar en tus redes o lo que has escuchado</p>
</div>
<img class="intro-img" src="/img/foto1.png" alt="">
</div>
<div id="intro-btn" class="intro-box">
<div>
<h2 class="intro-subtitle">Ayuda</h2>
<p>O guía a la comunidad para un mundo mejor.</p>
</div>
<img class="intro-img" src="/img/foto2.png" alt="">
</div>
</div>
`;
const introElement = document.createElement('div');
introElement.innerHTML = tmpIntroduction;
const toNextSection = introElement.querySelector('#intro-btn');
toNextSection.addEventListener('click', () => {
changeHash('/stereotypeList')
});
return introElement;
}<file_sep>export const stereotypeBox = (data) => {
const firstTemplate = `
<div id= "text-box">
<textarea name="text-input" id="stereotypes-box" cols="30" rows="10"></textarea>
<button type="button" id="sb-button">Añadir</button>
</div>`;
const divElement = document.createElement('div');
divElement.innerHTML = firstTemplate;
const paintingDiv = divElement.querySelector('#sb-button');
paintingDiv.addEventListener('click', () => {
addStereotypeOnClick();
});
// const ul = divElement.querySelector('text-box');
// data.forEach((post) => {
// ul.appendChild(itemStereotype(post))
// });
return divElement;
}
const itemStereotype = () => {
const liElement = document.createElement('li');
liElement.classList.add('mdl-list__item')
liElement.innerHTML = `
<div id="stereotype-result">
<p id="text-list"></p>
<label for="text-list"></label>
</div>`;
return liElement;
}
const totalValue = () => {
const total = `
<h3>Total:</h3>
<button type="button" id="next-btn">Siguiente</button>`;
const totalElement = document.createElement('div');
totalElement.innerHtml = total;
}
<file_sep>import { actionPlan } from './lib/templates/action-plan.js';
import { stereotypeBox } from './lib/templates/stereotype-box.js';
import { introduction } from './lib/templates/introduction.js';
import { signIn } from './lib/templates/singIn.js';
import { inicio } from './lib/templates/inicio.js';
const changeTmp = (hash) => {
if (hash === '#/' || hash === '' || hash === '#') {
return viewTmp('#/inicio');
} else if (hash === '#/inicio' ||hash === '#/introduction'||hash === '#/stereotypeList' ||hash === '#/signin' || hash === '#/actionPlan') {
return viewTmp(hash);
} else {
return viewTmp('#/inicio');
}
};
const viewTmp = (routers) => {
const router = routers.substr(2, routers.length - 2);
const section = document.getElementById('first-template');
const actionPlanSection = document.getElementById('action-plan');
actionPlanSection.innerHTML = '';
section.innerHTML = '';
switch (router) {
case 'actionPlan':
section.appendChild(actionPlan());
// printList((actionList) => {
// postSection.innerHTML = '';
// });
break;
case 'signin':
section.appendChild(signIn());
break;
case 'stereotypeList':
section.appendChild(stereotypeBox());
break;
case 'introduction':
section.appendChild(introduction());
break;
case 'inicio':
section.appendChild(inicio());
default:
section.appendChild(inicio());
break;
}
};
export const routerRed = () => {
window.addEventListener('load',
changeTmp(window.location.hash));
if (('onhashchange' in window)) window.onhashchange = () => changeTmp(window.location.hash);
};<file_sep># Hackeando-la-desigualdad<file_sep>export const actionPlan = (list) => {
const actionTemplate = `
<div id="action-plan-tmpl">
<h1>Plan de Acción</h1>
<img src="" alt="">
<p>Explicación. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit omnis, hic tempore placeat quibusdam ducimus nulla ipsam odio perferendis accusantium magnam recusandae deleniti dignissimos ullam inventore, earum reiciendis odit cum! Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, quidem recusandae! Suscipit et, consectetur tempore ducimus culpa sit deleniti facilis reprehenderit dolorum tenetur ab unde illo impedit. Optio, error earum.
Nihil iste illo nemo itaque fugit facilis! Ullam velit facere rem consequuntur enim cupiditate quibusdam obcaecati nostrum atque rerum quia aliquid maxime qui iste facilis, laudantium ad, non architecto perferendis.
Veritatis autem mollitia aperiam, vero fugiat ipsum nihil dolor, at rerum voluptas ab placeat pariatur amet ipsam distinctio. Nihil at sint nisi perspiciatis dolorem ab sapiente aliquid, autem sit dolore.</p>
</div>`
const actionElement = document.createElement('div');
actionElement.innerHTML = actionTemplate;
// const ul = actionElement.querySelector('#action-plan-tmpl');
// list.forEach((list) => {
// ul.appendChild(actionPlanObj(list))
// });
return actionElement;
}
const actionPlanObj = () => {
const liElement = document.createElement('li');
liElement.classList.add('mdl-list__item')
liElement.innerHTML = `
<div id="stereotype-result">
</div>`;
return liElement;
};
|
306ecf57dbc167a1b2484d63e9c51e2753c7971c
|
[
"JavaScript",
"Markdown"
] | 8
|
JavaScript
|
GabrielaDiazB/Hackeando-la-desigualdad
|
c31b32eff03e44d1408553e2da1a86877e157344
|
b5cd70cfb998ee82f59c2a3137cde871dfbd8ec0
|
refs/heads/master
|
<repo_name>developit/babel-preset-es2015-minimal-rollup<file_sep>/README.md
# babel-preset-es2015-minimal-rollup
[](http://npm.im/babel-preset-es2015-minimal-rollup)
[](https://travis-ci.org/developit/babel-preset-es2015-minimal-rollup)
> Babel es2015 preset in loose mode without frills, made for Rollup.
## Installation
```sh
$ npm i -S babel-preset-es2015 babel-preset-es2015-minimal-rollup
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"presets": ["es2015-minimal-rollup"]
}
```
### Via CLI
```sh
$ babel script.js --presets es2015-minimal-rollup
```
### Via Node API
```javascript
require('babel-core').transform('code', {
presets: ['es2015-minimal-rollup']
});
```
<file_sep>/test/index.js
var preset = require('..'),
es2015 = require('babel-preset-es2015'),
assert = require('assert');
// strip a nested module path + filename down to just the innermost module's (file)name
function getModuleName(path) {
return String(path).replace(/(?:(?:.+\/)?node_modules\/|\/|\.\.\/)((@[^\/]+\/)?[^\/]+)(\/.*)?$/g, '$1');
}
console.log(preset.plugins.map(function(p) {
var name = getModuleName(( Array.isArray(p) ? p[0] : p )._original_name);
return Array.isArray(p) ? [name].concat(p.slice(1)) : name;
}));
var loosed = preset.plugins.reduce(function(count, p) {
var loose = Array.isArray(p) && p[1] && p[1].loose;
return count + (loose ? 1 : 0);
}, 0);
assert.equal(loosed, 6);
console.log('👍 Should put 6 plugins into loose mode');
assert.equal(preset.plugins.length, es2015.plugins.length-2, 'Should remove two plugins from es2015 preset');
console.log('👍 Should remove two plugins from es2015 preset');
console.log('🎉 all good');
|
4fd12008e046e859cfb6bee49b337ec162aec381
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
developit/babel-preset-es2015-minimal-rollup
|
680c876631910a6f4bc74a0ee74fe1bd1947318e
|
4e7e62c523cdf2b48a0d1e4d4e71efeeeb5fdc9c
|
refs/heads/main
|
<file_sep>import { createAction } from '@reduxjs/toolkit';
export const fetchContactsRequest = createAction(
'contacts/fetchContactsRequest'
);
export const fetchContactsSuccess = createAction(
'contacts/fetchContactsSuccess'
);
export const fetchContactsError = createAction('contacts/fetchContactsError');
export const addContactRequest = createAction('contacts/addContactRequest');
export const addContactSuccess = createAction('contacts/addContactSuccess');
export const addContactError = createAction('contacts/addContactError');
export const deleteContactRequest = createAction(
'contacts/deleteContactRequest'
);
export const deleteContactSuccess = createAction(
'contacts/deleteContactSuccess'
);
export const deleteContactError = createAction('contacts/deleteContactError');
export const contactFilter = createAction('contacts/filter');
// export const contactAdd = createAction('contacts/add', (name, number) => ({
// payload: {
// id: Date.now(),
// name,
// number,
// },
// }));
// export const contactAdd = (name, number) => {
// return {
// type: actionType.ADD,
// payload: {
// id: Date.now(),
// name,
// number,
// },
// };
// };
// export const contactDelete = (id) => {
// return {
// type: actionType.DELETE,
// payload: id,
// };
// };
// export const conatactFilter = (value) => ({
// type: actionType.CHANGE_FILTER,
// payload: value,
// });
<file_sep>import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';
import logger from 'redux-logger';
import storage from 'redux-persist/lib/storage';
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from 'redux-persist';
import counterReducer from './contact/contacts-reducer';
import authReducer from './auth/auth-reducer';
const middleware = [
...getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
logger,
];
const authPersistConfig = {
key: 'auth',
storage,
whiteList: ['token'],
};
const store = configureStore({
reducer: {
contacts: counterReducer,
auth: persistReducer(authPersistConfig, authReducer),
},
middleware: middleware,
devTools: process.env.NODE_ENV === 'development',
});
const persistor = persistStore(store);
export default { store, persistor };
//
// const rootReducer = combineReducers({
// contacts: persisterReducer(PersistConfig, counterReducer),
// });
// const persisterReducer = persistReducer(PersistConfig, rootReducer);
// import { applyMiddleware, combineReducers } from 'redux';
// const rootReducer = combineReducers({
// contacts: counterReducer,
// });
// const store = createStore(rootReducer, composeWithDevTools());
// const initialState = {
// contacts: {
// items: [
// { id: 'id-1', name: '<NAME>', number: '459-12-56' },
// { id: 'id-2', name: '<NAME>', number: '443-89-12' },
// { id: 'id-3', name: '<NAME>', number: '645-17-79' },
// { id: 'id-4', name: '<NAME>', number: '227-91-26' },
// ],
// filters: '',
// },
// };
// const reducer = (state = initialState, { type, payload }) => {
// switch (type) {
// case 'contacts/add':
// return {
// ...state,
// contacts: {
// ...state.contacts,
// items: [payload, ...state.contacts.items],
// },
// };
// case 'contacts/delete':
// return {
// ...state,
// contacts: {
// ...state.contacts,
// items: state.contacts.items.filter(({ id }) => id !== payload),
// },
// };
// case 'contacts/filter':
// return {
// ...state,
// contacts: {
// ...state.contacts,
// items: state.contacts.items.filter((name) =>
// name.toLowerCase().includes(state.contacts.filters.toLowerCase())
// ),
// },
// };
// default:
// return state;
// }
// };
<file_sep>import React from 'react';
import { NavLink, withRouter } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { getIsisAuthorizedSelector } from '../../redux/auth/auth-selectors';
import styles from './Nav.module.css';
import routes from '../routes';
const Nav = () => {
const IsisAuthorized = useSelector(getIsisAuthorizedSelector);
return (
<nav>
<ul className={styles.navList}>
<li className={styles.navListItem}>
<NavLink
exact
to={routes.HOME}
className={styles.Link}
activeClassName={styles.linkFocusColor}
>
Home
</NavLink>
</li>
{IsisAuthorized && (
<li className={styles.navListItem}>
<NavLink
exact
to={routes.CONTACTS}
className={styles.Link}
activeClassName={styles.linkFocusColor}
>
Contacts
</NavLink>
</li>
)}
</ul>
</nav>
);
};
export default Nav;
<file_sep>import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import PropTypes from 'prop-types';
import styles from './ContactForm.module.css';
import { connect } from 'react-redux';
import * as contactOperations from '../../redux/contact/contact-operations';
import * as contactSelectors from '../../redux/contact/contact-selectors';
const ContactForm = () => {
const items = useSelector(contactSelectors.getContacts);
const dispatch = useDispatch();
const onSubmit = (name, number) =>
dispatch(contactOperations.contactAdd(name, number));
const [name, setName] = useState('');
const [number, setNumber] = useState('');
const handleChangeName = (e) => {
setName(e.target.value);
};
const handleChangeNumber = (e) => {
setNumber(e.target.value);
};
const contactValidation = () => {
if (items.find((contact) => name === contact.name)) {
alert(`${name} is already in contacts`);
return true;
}
};
const handleSubmit = (e) => {
e.preventDefault();
if (contactValidation()) {
return;
}
onSubmit(name, number);
setName('');
setNumber('');
};
return (
<>
<form className={styles.TaskEditor} onSubmit={handleSubmit}>
<label className={styles.TaskEditor_label}>
Name
<input
className={styles.TaskEditor_input}
type="text"
name="name"
value={name}
onChange={handleChangeName}
required
/>
</label>
<label className={styles.TaskEditor_label}>
Number
<input
className={styles.TaskEditor_input}
type="tel"
name="number"
value={number}
onChange={handleChangeNumber}
required
/>
</label>
<button className={styles.TaskEditor_button}> Add contact</button>
</form>
</>
);
};
export default ContactForm;
// ContactForm.propTypes = {
// onSubmit: PropTypes.func.isRequired,
// };
// const mapStateToProps = (state) => {
// return {
// items: contactSelectors.getContacts(state),
// };
// };
// const mapDispatchToProps = (dispatch) => {
// return {
// onSubmit: (name, number) =>
// dispatch(contactOperations.contactAdd(name, number)),
// };
// };
// export default connect(null, mapDispatchToProps)(ContactForm);
<file_sep>import { createAction } from '@reduxjs/toolkit';
export const loginRequest = createAction('/users/login/request');
export const loginSuccess = createAction('/users/login/success');
export const loginError = createAction('/users/login/error');
export const signupRequest = createAction('/users/signup/request');
export const signupSuccess = createAction('/users/signup/success');
export const signupError = createAction('/users/signup/error');
export const logoutRequest = createAction('/users/logout/request');
export const logoutSuccess = createAction('/users/logout/success');
export const logoutError = createAction('/users/logout/error');
export const currentRequest = createAction('/users/current/request');
export const currentSuccess = createAction('/users/current/success');
export const currentError = createAction('/users/current/error');
<file_sep>import React from 'react';
import { NavLink } from 'react-router-dom';
import s from './AuthNav.module.css';
import routes from '../routes';
const AuthNav = () => {
const styles = {
activeLink: {
color: '#ffffff',
backgroundColor: 'rgb(70, 100, 100)',
borderColor: 'rgb(50, 80, 100)',
},
};
return (
<div>
<NavLink
to={routes.REGISTER}
className={s.link}
activeStyle={styles.activeLink}
>
Sign up
</NavLink>
<NavLink
to={routes.LOGIN}
className={s.link}
activeStyle={styles.activeLink}
>
Sign in
</NavLink>
</div>
);
};
export default AuthNav;
<file_sep>import { combineReducers } from 'redux';
import { createReducer } from '@reduxjs/toolkit';
import * as authActions from './auth-actios';
const initialState = {
name: null,
email: null,
};
const isAuthorized = createReducer(false, {
[authActions.loginSuccess]: () => true,
[authActions.signupSuccess]: () => true,
[authActions.currentSuccess]: () => true,
[authActions.logoutSuccess]: () => false,
[authActions.currentError]: () => false,
[authActions.loginError]: () => false,
[authActions.signupError]: () => false,
});
const isLoading = createReducer(false, {
[authActions.currentRequest]: () => true,
[authActions.currentSuccess]: () => false,
[authActions.currentError]: () => false,
[authActions.loginRequest]: () => true,
[authActions.loginSuccess]: () => false,
[authActions.loginError]: () => false,
[authActions.logoutRequest]: () => true,
[authActions.logoutSuccess]: () => false,
[authActions.logoutError]: () => false,
[authActions.signupRequest]: () => true,
[authActions.signupSuccess]: () => false,
[authActions.signupError]: () => false,
});
const user = createReducer(initialState, {
[authActions.signupSuccess]: (_, { payload }) => payload.user,
[authActions.loginSuccess]: (_, { payload }) => payload.user,
[authActions.logoutSuccess]: () => initialState,
[authActions.currentSuccess]: (_, { payload }) => payload,
});
const token = createReducer(null, {
[authActions.signupSuccess]: (_, action) => action.payload.token,
[authActions.loginSuccess]: (_, action) => action.payload.token,
[authActions.logoutSuccess]: () => null,
});
const error = createReducer(null, {
[authActions.signupError]: () => (_, action) => action.payload,
[authActions.loginError]: () => (_, action) => action.payload,
[authActions.currentError]: () => (_, action) => action.payload,
[authActions.logoutError]: () => (_, { payload }) => payload,
});
export default combineReducers({
user,
token,
isLoading,
error,
isAuthorized,
});
<file_sep>import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Filter from '../../components/Filter/Filter';
import { getLoading } from '../../redux/contact/contact-selectors';
import ContactForm from '../../components/ContactForm/ContactForm';
import ContactList from '../../components/ContactList/ContactList';
import * as contactOperations from '../../redux/contact/contact-operations';
const ContactsView = () => {
const loading = useSelector(getLoading);
const dispatch = useDispatch();
useEffect(() => dispatch(contactOperations.fetchContacts()), [dispatch]);
return (
<>
<h1>Phonebook</h1>
<ContactForm />
{loading && <h1>Загружаем ...</h1>}
<h2>Contacts</h2>
<Filter />
<ContactList />
</>
);
};
export default ContactsView;
<file_sep>const ADD = 'contacts/add';
const DELETE = 'contacts/delete';
const CHANGE_FILTER = 'contacts/filter';
export default {
ADD,
DELETE,
CHANGE_FILTER,
};
<file_sep>import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as actions from '../../redux/contact/contact-actions';
import * as contactSelectors from '../../redux/contact/contact-selectors';
const Filter = ({}) => {
const dispatch = useDispatch();
const value = useSelector(contactSelectors.getFilter);
const onFilter = (e) => dispatch(actions.contactFilter(e.target.value));
return (
<div>
Find contacts by name
<input type="text" value={value} onChange={onFilter} />
</div>
);
};
Filter.propTypes = {
value: PropTypes.string.isRequired,
};
// const mapStateToProps = (state) => ({
// value: contactSelectors.getFilter(state),
// });
// const mapDispatchToProps = (dispatch) => ({
// onFilter: (e) => dispatch(actions.contactFilter(e.target.value)),
// });
// export default connect(null, mapDispatchToProps)(Filter);
export default Filter;
<file_sep>import { useSelector } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
import { getIsisAuthorizedSelector } from '../../redux/auth/auth-selectors';
/**
* - Если маршрут ограниченный, и юзер залогинен, рендерит редирект на redirectTo
* - В противном случае рендерит компонент
*
*/
export default function PublicRoute({ children, redirectTo, ...routeProps }) {
const isLoadID = useSelector(getIsisAuthorizedSelector);
const shouldRedirect = isLoadID && routeProps.restricted;
return (
<Route {...routeProps}>
{shouldRedirect ? <Redirect to={redirectTo} /> : children}
</Route>
);
}
<file_sep>import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { login } from '../../redux/auth/auth-operations';
import style from './LoginView.module.css';
const LoginView = () => {
const dispatch = useDispatch();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleChangeEmail = (e) => setEmail(e.target.value);
const handleChangePassword = (e) => setPassword(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
dispatch(login({ email, password }));
setEmail('');
setPassword('');
};
return (
<div>
<h2>Sign in to Phonebook</h2>
<form onSubmit={handleSubmit} className={style.form}>
<label className={style.label}>
Email address
<input
type="email"
name="email"
placeholder="Email"
value={email}
onChange={handleChangeEmail}
/>
</label>
<label className={style.label}>
Password
<input
type="<PASSWORD>"
name="password"
placeholder="<PASSWORD>"
value={password}
onChange={handleChangePassword}
/>
</label>
<button type="submit">Enter</button>
</form>
</div>
);
};
export default LoginView;
// const [email, setEmail] = useState('<EMAIL>');
// const [password, setPassword] = useState('<PASSWORD>!');
|
6ca1be449abd8e8d2f2c202f6c4418d4bf546cb2
|
[
"JavaScript"
] | 12
|
JavaScript
|
Mharkov/goit-react-hw-09-phonebook
|
f56d4cc9f795ce0e8ff1030743e9856f47032980
|
083076e1b6b4e0ddcce5e5783c7fc28d8a7f258b
|
refs/heads/master
|
<repo_name>ilhemkhlif/AntiThief<file_sep>/app/src/main/java/com/example/autosms/FirstMainActivity.java
package com.example.autosms;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FirstMainActivity extends Activity {
private Button btnDisplay;
private TextView Code;
private static String StrCode;
private static boolean firstRun=false;
public static String GetCode() {
return StrCode;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_first);
addListenerOnButton();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void addListenerOnButton() {
btnDisplay = (Button) findViewById(R.id.button);
Code = (TextView) findViewById(R.id.TxtCode);
btnDisplay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Log.v("button", "test");
if ((Code.getText().toString())!=null) {
StrCode = Code.getText().toString();
Toast.makeText(FirstMainActivity.this, "Registration successfully ", Toast.LENGTH_SHORT).show();
/* firstRun=true;
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
startActivityForResult(myIntent, 0);*/
}
else {
Toast.makeText(FirstMainActivity.this, "Enter your secret code! ", Toast.LENGTH_SHORT).show();
}
}
});
}
}
<file_sep>/app/src/main/java/com/example/autosms/MainActivity.java
package com.example.autosms;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends Activity {
private Switch mySwitch;
private boolean activated=true;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, FirstMainActivity.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
setContentView(R.layout.activity_main);
mySwitch = (Switch) findViewById(R.id.switch1);
//set the switch to ON
mySwitch.setChecked(true);
//attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
boolean activated=SmsReceiver.changeStatus();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
/*SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
FirstMainActivity Fm= new FirstMainActivity();
Intent i= new Intent(this.getApplication(),FirstMainActivity.class);
Fm.startActivity(i);
}*/
}
}
<file_sep>/app/src/main/java/com/example/autosms/PredictifData.java
package com.example.autosms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import android.util.Log;
public class PredictifData {
public static PredictifData instance=null;
public Map<String, String> numDevinette=null;
public Map<String, String> nomQuestion=null;
public static PredictifData getInstance() {
if(instance==null) {
instance=new PredictifData();
}
return instance;
}
PredictifData() {
if(numDevinette==null) {
numDevinette = new HashMap<String, String>();
}
if(nomQuestion==null) {
nomQuestion = new HashMap<String, String>();
}
nomQuestion.put("alicia", "Elle est bruyante,\r\nElle n'est pas très marrante\r\nMais elle est aimante\r\nC'est ce qui la rend si charmante\r\nQui est-ce?");
nomQuestion.put("ada", "Elle es rikiki\r\nElle tricotte comme une mamie\r\nElle cuisine des super biscuits\r\nEt porte plein de couleurs swaggy\r\nQui est-ce?");
nomQuestion.put("yann", "Fé pas tré zenti\r\nLes maths fé la vi\r\nTout le monde me haï\r\nEt je serai une tête de turc toute ma vie\r\nQui est-ce?");
nomQuestion.put("rémi", "Tout le monde l'adore\r\nLes filles en redemandent encore\r\nEt le trouvent tellement fort\r\nPlus tard, il sera plein d'or\r\nQui est-ce?");
nomQuestion.put("robardet", "J'ai les cheveux d'un noir de jais\r\nJe t'ai probablement déjà fait chier\r\nJe ne trouve pas le bon chemin\r\nJe ne suis pas de sexe masculin\r\nQui suis-je?");
nomQuestion.put("jean", "Je te hais a cause des peigne-culs, des couillons, des putains,\r\nEtrange à mes heures\r\nAnéantis, tu es, dans le fumier d’un champ de bataille,\r\nN’oublie jamais qui je suis\r\nQui suis-je?");
nomQuestion.put("camille", "Laisser moi me présenter :\r\nJe fais du très bon risotto\r\nSi je pouvais, je mettrai un chapeau\r\nPour éviter d'attirer les taureaux\r\nQui suis-je?");
nomQuestion.put("alexandre", "Son prénom vient du grec \"repousser\" et \"l'homme, le guerrier, viril\". Son nom voudrait donc dire celui qui protège les hommes et repousse l'ennemi.\r\nQui est-ce?");
nomQuestion.put("amaury", "Si on rend mon premier, alors on est mort !.\r\nMon deuxième est un liquide essentiel à toute vie\r\nMon troisième est l'aliment principal en Asie\r\nEt mon tout est un prénom masculin d'origine gotique\r\nQui suis-je?");
nomQuestion.put("justine", "4A 75 73 74 69 6E 65\r\nQui est-ce?");
nomQuestion.put("moi", "\r\nQui est-ce?");
nomQuestion.put("gustave", "gmsntdv\r\nQui est-ce?");
nomQuestion.put("thomas", "Colle mon prenom avec mon nom.\r\nEnleve une lettre.\r\nAnagramme le tout.\r\nCa donne Housemaster.\r\nQui suis-je?");
}
public String getRandom() {
Random random = new Random();
List<String> keys = new ArrayList<String>(nomQuestion.keySet());
String randomKey = keys.get( random.nextInt(keys.size()) );
Log.v("lll", randomKey);
return randomKey;
}
}
|
b0df050c3fc26c311d08445918c8b469d76e41bf
|
[
"Java"
] | 3
|
Java
|
ilhemkhlif/AntiThief
|
c8364f7d14e635cb165de4455d38c97af0e66367
|
cbc819cd304e170cf5ac709d983efd3a88cee792
|
refs/heads/master
|
<file_sep># android
Aplicación de Android para Senseware 2.0
<file_sep>package la.oja.senseware.Modelo;
/**
* Created by Administrador on 10-05-2016.
*/
public class Project {
private int id_project;
private int id_user;
private String na_project;
private String create;
private int id_tmp;
private int active;
public Project(){}
public Project(int id_project, int id_user, String na_project, String create, int active){
this.id_project = id_project;
this.id_user = id_user;
this.na_project = na_project;
this.create = create;
this.active = active;
}
public int getId_project() {
return this.id_project;
}
public int getId_user() {
return this.id_user;
}
public String getNa_project(){
return this.na_project;
}
public String getCreate(){
return this.create;
}
public int getId_tmp(){
return this.id_tmp;
}
public int getActive(){
return this.active;
}
public void setId_project(int id_project) {
this.id_project = id_project;
return;
}
public void setId_user(int id_user) {
this.id_user = id_user;
return;
}
public void setNa_project(String na_project){
this.na_project = na_project;
return;
}
public void setCreate(String create){
this.create = create;
return;
}
public void setId_tmp(int id_tmp){
this.id_tmp = id_tmp;
return;
}
public void setActive(int active){
this.active = active;
return;
}
}
<file_sep>package la.oja.senseware;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import la.oja.senseware.data.sensewareDataSource;
import la.oja.senseware.data.sensewareDbHelper;
/**
* Created by Administrador on 12-05-2016.
*/
public class EditProjectActivity extends AppCompatActivity {
private EditText mProjectView;
private Button btnEditProject;
private TextView title;
private ImageButton btnClear;
private int id_project;
private String projectOld;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_project);
Typeface ultralight= Typeface.createFromAsset(getAssets(), "fonts/SF-UI-Display-Ultralight.ttf");
Typeface light= Typeface.createFromAsset(getAssets(), "fonts/SF-UI-Text-Light.ttf");
Typeface thin= Typeface.createFromAsset(getAssets(), "fonts/SF-UI-Display-Thin.ttf");
Typeface regular= Typeface.createFromAsset(getAssets(), "fonts/SF-UI-Text-Regular.ttf");
mProjectView = (EditText) findViewById(R.id.name_project);
btnEditProject = (Button) findViewById(R.id.btnEditProject);
title = (TextView) findViewById(R.id.title);
btnClear = (ImageButton) findViewById(R.id.project_clear);
mProjectView.setTypeface(thin);
title.setTypeface(light);
btnEditProject.setTypeface(thin);
projectOld = getIntent().getStringExtra("project");
id_project = getIntent().getIntExtra("id_project", -1);
if(!TextUtils.isEmpty(projectOld)){
TextView tv = (TextView) findViewById(R.id.name_project);
tv.setHint(projectOld);
btnClear.setVisibility(View.VISIBLE);
}
ImageButton close = (ImageButton) findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditProjectActivity.this.finish();
}
});
mProjectView.setCursorVisible(true);
mProjectView.setFocusableInTouchMode(true);
mProjectView.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mProjectView, InputMethodManager.SHOW_FORCED);
mProjectView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
btnClear.setVisibility(View.VISIBLE);
}
@Override
public void afterTextChanged(Editable s) {
}
});
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.name_project);
tv.setText("");
btnClear.setVisibility(View.GONE);
}
});
btnEditProject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editProject();
}
});
}
private void editProject() {
mProjectView.setError(null);
boolean cancel = false;
View focusView = null;
String project = mProjectView.getText().toString();
if (TextUtils.isEmpty(project)) {
mProjectView.setError(getString(R.string.error_edit_project));
focusView = mProjectView;
cancel = true;
}
if(cancel)
focusView.requestFocus();
else
{
SharedPreferences settings = getSharedPreferences("ActivitySharedPreferences_data", 0);
SharedPreferences.Editor editor = settings.edit();
int id_user = settings.getInt("id_user", 0);
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(c.getTime());
String url = Config.URL_API +"project/"+id_project;
String utm_source = settings.getString("utm_source", "");
String utm_medium = settings.getString("utm_medium", "");
String utm_term = settings.getString("utm_term", "");
String utm_content = settings.getString("utm_content", "");
String utm_campaign = settings.getString("utm_campaign", "");
String utms = "'app': 'Android'";
if(utm_source.compareTo("") != 0)
utms += ", 'utm_source': '" + utm_source + "'";
if(utm_medium.compareTo("") != 0)
utms += ", 'utm_medium': '" + utm_medium + "'";
if(utm_term.compareTo("") != 0)
utms += ", 'utm_term': '" + utm_term + "'";
if(utm_content.compareTo("") != 0)
utms += ", 'utm_content': '" + utm_content + "'";
if(utm_campaign.compareTo("") != 0)
utms += ", 'utm_campaign': '" + utm_campaign + "'";
String data = "{'na_project': '"+ project +"' }";
ContentValues values_hook = new ContentValues();
values_hook.put(sensewareDataSource.Hook.COLUMN_NAME_DATA, data);
values_hook.put(sensewareDataSource.Hook.COLUMN_NAME_DATE, date);
values_hook.put(sensewareDataSource.Hook.COLUMN_NAME_HOOK, "editProject");
values_hook.put(sensewareDataSource.Hook.COLUMN_NAME_TYPE, "PUT");
values_hook.put(sensewareDataSource.Hook.COLUMN_NAME_UPLOAD, 0);
values_hook.put(sensewareDataSource.Hook.COLUMN_NAME_URL, url);
sensewareDbHelper sDbHelper = new sensewareDbHelper(getApplicationContext());
SQLiteDatabase db = sDbHelper.getWritableDatabase();
String select = sensewareDataSource.Project.COLUMN_NAME_ID_PROJECT + "=?";
String[] selectArg = {String.valueOf(id_project)};
ContentValues updateProject = new ContentValues();
updateProject.put(sensewareDataSource.Project.COLUMN_NAME_NA_PROJECT, project);
int count = db.update(
sensewareDataSource.Project.TABLE_NAME,
updateProject,
select,
selectArg);
if(count > 0) {
SaveHook obj = new SaveHook(getApplicationContext(), values_hook, settings);
EditProjectActivity.this.finish();
Intent intent = new Intent(EditProjectActivity.this, MyProjectsActivity.class);
startActivity(intent);
}
else
{
mProjectView.setError("Ocurrio un error actualizando el proyecto");
focusView = mProjectView;
focusView.requestFocus();
}
}
}
}
<file_sep>package la.oja.senseware;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import org.json.JSONObject;
import la.oja.senseware.data.sensewareDataSource;
import la.oja.senseware.data.sensewareDbHelper;
/**
* Created by Administrador on 12-05-2016.
*/
public class SaveHook {
Context context;
SharedPreferences settings;
int idTmp = -1;
ApiCall call;
public SaveHook(Context context, ContentValues values_hook, SharedPreferences settings) {
this.context = context;
this.settings = settings;
sensewareDbHelper sDbHelper = new sensewareDbHelper(context);
SQLiteDatabase db = sDbHelper.getWritableDatabase();
long newRowId = db.insert(sensewareDataSource.Hook.TABLE_NAME, null, values_hook);
db.close();
new HttpRequestSendHooks().execute();
}
private class HttpRequestSendHooks extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
sensewareDbHelper sDbHelper = new sensewareDbHelper(context);
SQLiteDatabase db = sDbHelper.getReadableDatabase();
Cursor c = null;
try {
String[] projection = {
sensewareDataSource.Hook._ID,
sensewareDataSource.Hook.COLUMN_NAME_HOOK,
sensewareDataSource.Hook.COLUMN_NAME_DATA,
sensewareDataSource.Hook.COLUMN_NAME_TYPE,
sensewareDataSource.Hook.COLUMN_NAME_DATE,
sensewareDataSource.Hook.COLUMN_NAME_URL,
sensewareDataSource.Hook.COLUMN_NAME_UPLOAD
};
String whereCol = sensewareDataSource.Hook.COLUMN_NAME_UPLOAD + " = 0";
c = db.query(sensewareDataSource.Hook.TABLE_NAME, projection, whereCol, null, null, null, null);
try {
if (c.moveToFirst())
{
int id_project = 0;
do {
int id = c.getInt(0);
String data = c.getString(2);
String method = c.getString(3);
String url = c.getString(5);
String hook = c.getString(1);
if (url.equals(Config.URL_API +"project") && method.equals("POST")) {
data = getNewData(data, true, id_project);
}
else {
data = getNewData(data, false, id_project);
}
try {
call = new ApiCall(context);
String resp = "";
if (method.equals("POST"))
resp = call.callPost(url, data);
if (method.equals("GET"))
resp = call.callGet(url);
if (method.equals("PUT"))
resp = call.callPut(url, data);
//get response obtained of call api
//convert the response from string to JsonObject
JSONObject obj = new JSONObject(resp);
int status = obj.getInt("status");
String message = obj.getString("message");
if (status == 200 && message.equals("OK")) {
// New value for one column
ContentValues values = new ContentValues();
values.put(sensewareDataSource.Hook.COLUMN_NAME_UPLOAD, 1);
// Which row to update, based on the ID
String selection = sensewareDataSource.Hook._ID + "=?";
String[] selectionArgs = {String.valueOf(id)};
int count = db.update(
sensewareDataSource.Hook.TABLE_NAME,
values,
selection,
selectionArgs);
//if the hook to process is new project
if (url.equals(Config.URL_API +"project")) {
JSONObject result = new JSONObject(obj.get("result").toString());
id_project = result.getInt("id_project");
String na_project = result.getString("na_project");
updateProject(id_project, idTmp);
c.close();
db.close();
//new HttpRequestSendHooks();
}
if(url.equals(Config.URL_API +"result")) {
JSONObject result = new JSONObject(obj.get("result").toString());
int id_result = result.getInt("id_result");
int project = result.getInt("id_project");
int id_lesson = result.getInt("id_lesson");
String value = result.getString("result");
int id_source = result.getInt("id_source");
ContentValues valuesResult = new ContentValues();
valuesResult.put(sensewareDataSource.Result.COLUMN_NAME_ID_RESULT, id_result);
valuesResult.put(sensewareDataSource.Result.COLUMN_NAME_ID_SOURCE, id_source);
String where = sensewareDataSource.Result.COLUMN_NAME_ID_RESULT+ "=? AND " +
sensewareDataSource.Result.COLUMN_NAME_ID_PROJECT +" =? AND " +
sensewareDataSource.Result.COLUMN_NAME_ID_LESSON +" =? AND " +
sensewareDataSource.Result.COLUMN_NAME_RESULT +" =?";
String[] args = {String.valueOf(0), String.valueOf(project), String.valueOf(id_lesson), value};
int count2 = db.update(
sensewareDataSource.Result.TABLE_NAME,
valuesResult,
where,
args);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} while (c.moveToNext());
}
}catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null && !c.isClosed()) {
c.close();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c.isClosed()) {
db.close();
}
}
return null;
}
}
private String getNewData(String data, boolean isNewProject, int id_project) {
String aux = data.substring(1,data.length()-1);
String[] valuesData = aux.split(",");
String newData = null;
newData = "{";
for (int i = 0; i < valuesData.length; i++) {
String[] item = valuesData[i].split(":");
if (item[0].equals("'id_tmp'")) {
if(isNewProject)
{
item[1] = item[1].replace(" ", "");
idTmp = Integer.valueOf(item[1]);
}
else {
if(id_project == 0)
{
int idProject = settings.getInt("id_project", 0);
newData += "'id_project' : " + idProject + ",";
}
else
newData += "'id_project' : " + id_project + ",";
}
}else if(item[0].equals("'id_project'"))
{
item[1] = item[1].replace(" ", "");
int id = Integer.valueOf(item[1]);
if(id==0){
int idProject = settings.getInt("id_project", 0);
newData += "'id_project' : " + idProject + ",";
}
else{
newData += "'id_project' : " + id + ",";
}
}
else {
newData += valuesData[i];
if (i < (valuesData.length - 1))
newData += ",";
}
}
newData += "}";
return newData;
}
private void updateProject(int id_project, int idTmp) {
SharedPreferences.Editor editor = settings.edit();
int idProject = settings.getInt("id_project", 0);
if (idProject == idTmp) {
editor.putInt("id_project", id_project);
editor.putBoolean("idTmp", false);
editor.commit();
}
sensewareDbHelper sDbHelper = new sensewareDbHelper(context);
SQLiteDatabase db = sDbHelper.getReadableDatabase();
String select = sensewareDataSource.Project.COLUMN_NAME_ID_TMP + "=?";
String[] selectArg = {String.valueOf(idTmp)};
ContentValues updateProject = new ContentValues();
updateProject.put(sensewareDataSource.Project.COLUMN_NAME_ID_PROJECT, id_project);
int count = db.update(
sensewareDataSource.Project.TABLE_NAME,
updateProject,
select,
selectArg);
String select2 = sensewareDataSource.Result.COLUMN_NAME_ID_PROJECT + "=?";
ContentValues updateResult = new ContentValues();
updateResult.put(sensewareDataSource.Result.COLUMN_NAME_ID_PROJECT, id_project);
int count2 = db.update(
sensewareDataSource.Result.TABLE_NAME,
updateResult,
select2,
selectArg);
String select3 = sensewareDataSource.History.COLUMN_NAME_ID_PROJECT + "=?";
ContentValues updateHistory = new ContentValues();
updateHistory.put(sensewareDataSource.History.COLUMN_NAME_ID_PROJECT, id_project);
int count3 = db.update(
sensewareDataSource.History.TABLE_NAME,
updateHistory,
select3,
selectArg);
db.close();
return;
}
}
<file_sep>package la.oja.senseware.Modelo;
/**
* Created by Administrador on 10-05-2016.
*/
public class Group {
private int id_group;
private String group_name;
private int group_level;
private int active;
public Group(){}
public int getId_group(){
return this.id_group;
}
public String getGroup_name(){
return this.group_name;
}
public int getGroup_level(){
return this.group_level;
}
public int getActive(){
return this.active;
}
}
<file_sep>package la.oja.senseware.Modelo;
/**
* Created by Oja.la on 29/4/2016.
*/
public class Day {
private int id_day;
private int day;
private int visible_clases;
private String title;
private int visible;
public int getId_day() {
return id_day;
}
public int getDay() {
return day;
}
public int getVisible_clases() {
return visible_clases;
}
public String getTitle() {
return title;
}
public int getVisible() {
return visible;
}
public void setId_day(int id_day) {
this.id_day = id_day;
}
public void setDay(int day) {
this.day = day;
}
public void setVisible_clases(int visible_clases) {
this.visible_clases = visible_clases;
}
public void setTitle(String title) {
this.title = title;
}
public void setVisible(int visible) {
this.visible = visible;
}
}
<file_sep>package la.oja.senseware.Modelo;
import java.util.Date;
/**
* Created by Administrador on 10-05-2016.
*/
public class User {
private int id_user;
private int id_utype;
private int last_lesson;
private String name;
private String email;
private String password;
private String phone;
private Date date;
private boolean test;
private int verified;
private String verifcode;
private String last_ip;
private int suscription;
private String adviser;
private String mentor;
private int day_email;
private Date date_email;
private int contacted;
private int unsubscribe;
private int check_email;
private int check_whatsapp;
private boolean hasSuscriptionActive;
public int getId_user() {
return this.id_user;
}
public int getId_utype(){
return this.id_utype;
}
public String getEmail() {
return this.email;
}
public String getPassword() {
return this.password;
}
public String getPhone() {
return this.phone;
}
public String getName(){
return this.name;
}
public Date getDate() {
return this.date;
}
public boolean getTest(){
return this.test;
}
public String getVerifcode(){
return this.verifcode;
}
public String getLast_ip(){
return this.last_ip;
}
public int getSuscription(){
return this.suscription;
}
public String getAdviser(){
return this.adviser;
}
public int getDay_email(){
return this.day_email;
}
public Date getDate_email(){
return this.date_email;
}
public int getLast_lesson(){
return this.last_lesson;
}
public int getVerified(){
return this.verified;
}
public int getUnsubscribe(){
return this.unsubscribe;
}
public int getContacted(){
return this.contacted;
}
public int getCheck_email(){
return this.check_email;
}
public int getCheck_whatsapp(){
return this.check_whatsapp;
}
public String getMentor(){
return this.mentor;
}
public boolean getHasSuscriptionActive() {
return this.hasSuscriptionActive;
}
public void setId_user(int id_user)
{
this.id_user = id_user;
return;
}
public void setEmail(String email)
{
this.email = email;
return;
}
public void setPhone(String phone)
{
this.phone = phone;
return;
}
public void setPassword(String password)
{
this.password = password;
return;
}
public void setId_utype(int id_utype)
{
this.id_utype = id_utype;
return;
}
public void setName(String name){
this.name = name;
return;
}
public void setDate(Date date){
this.date = date;
return;
}
public void setVerifcode(String verifcode){
this.verifcode = verifcode;
return;
}
public void setTest(boolean test){
this.test = test;
return;
}
public void setLast_ip(String last_ip){
this.last_ip = last_ip;
return;
}
public void setSuscription(int suscription){
this.suscription = suscription;
return;
}
public void setAdviser(String adviser){
this.adviser = adviser;
return;
}
public void setDay_email(int day_email){
this.day_email = day_email;
return;
}
public void setDate_email(Date date_email){
this.day_email = day_email;
return;
}
public void setLast_lesson(int last_lesson){
this.last_lesson = last_lesson;
return;
}
public void setVerified(int verified){
this.verified = verified;
return;
}
public void setMentor(String mentor){
this.mentor = mentor;
return;
}
public void setContacted(int contacted){
this.contacted = contacted;
return;
}
public void setUnsubscribe(int unsubscribe){
this.unsubscribe = unsubscribe;
return;
}
public void setCheck_email(int check_email){
this.check_email = check_email;
return;
}
public void setCheck_whatsapp(int check_whatsapp){
this.check_whatsapp = check_whatsapp;
return;
}
public void setHasSuscriptionActive(boolean hasSuscriptionActive){
this.hasSuscriptionActive = hasSuscriptionActive;
return;
}
}
<file_sep>package la.oja.senseware;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import la.oja.senseware.Modelo.Day;
import la.oja.senseware.Modelo.Lesson;
import la.oja.senseware.Modelo.Project;
import la.oja.senseware.Modelo.Subtitulo;
import la.oja.senseware.data.sensewareDataSource;
import la.oja.senseware.data.sensewareDbHelper;
public class AudioClaseActivity extends Activity {
//Elementos layout audio/subtitulo
private ImageButton startButton;
private SeekBar seekbarAudio;
private TextView tx1;
private LinearLayout barraInferiorAudio;
//Elementos layout respuesta
private RelativeLayout barraSuperiorRespueta;
private LinearLayout barraInferiorRespueta;
private EditText respuesta;
private SeekBar seekBarRespuesta;
private ImageButton startButtonRespuesta;
private RelativeLayout respuestaContenedor;
//Variables progreso audio
private double startTime = 0;
private double finalTime = 0;
private Handler myHandler = new Handler();
private TextView tiempoCuenta;
double tiempoCuentaNumero;
public static int oneTimeOnly = 0;
//Player sound
private MediaPlayer mp = null;
//Countdown
private static CountDownTimer countDown;
//Subtitulo
private RelativeLayout subtituloContenedor;
private ArrayList<Subtitulo> subtitulos;
private File myDir;
String fileName, imageUrl, utms;
ProgressDialog progress;
Lesson current;
int count_seconds;
ApiCall call;
//Opciones
SharedPreferences settings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_clase);
settings = getSharedPreferences("ActivitySharedPreferences_data", 0);
call = new ApiCall(getApplicationContext());
getUtms();
//Elementos layout audio
subtituloContenedor = (RelativeLayout) findViewById(R.id.subtituloContenedor);
barraInferiorAudio = (LinearLayout) findViewById(R.id.barraInferiorAudio);
startButton = (ImageButton) findViewById(R.id.button);
tx1=(TextView)findViewById(R.id.textView2);
seekbarAudio =(SeekBar)findViewById(R.id.seekBar);
seekbarAudio.setClickable(true);
//Elementos layout respuesta
barraSuperiorRespueta = (RelativeLayout) findViewById(R.id.barraSuperiorRespuesta);
barraInferiorRespueta = (LinearLayout)findViewById(R.id.barraInferiorRespuesta);
respuesta = (EditText)findViewById(R.id.respuesta);
seekBarRespuesta = (SeekBar) findViewById(R.id.seekBarRespuesta);
ImageView imagenEmprendedor = (ImageView) findViewById(R.id.imagenEmprendedor);
imagenEmprendedor.setImageResource(R.drawable.lock);
startButtonRespuesta = (ImageButton) findViewById(R.id.imageButtonRespuesta);
startButtonRespuesta.setImageResource(R.mipmap.pause_respuesta);
respuestaContenedor = (RelativeLayout) findViewById(R.id.respuestaContenedor);
tiempoCuenta = (TextView) findViewById(R.id.tiempoCuenta);
myDir = new File(getExternalFilesDir(Environment.getExternalStorageDirectory().toString()) + "/senseware_sounds");
this.mp = new MediaPlayer();
//Creando nuevo hilo
//videoThread = new Thread();
//videoThread.start();
setupListeners();
String email = settings.getString("email", "");
int day = settings.getInt("day", 1);
int pos = settings.getInt("current", 1);
this.current = this.getLesson(day, pos);
this.count_seconds = current.getSeconds();
imageUrl = current.getSrc();
String[] bits = imageUrl.split("/");
fileName = bits[bits.length-1];
Toast.makeText(getApplicationContext(), imageUrl, Toast.LENGTH_SHORT).show();
String audioFile = getFile();
//startButton.performClick();
//playFunction();
}
@Override
public void onBackPressed() {
if(mp.isPlaying()){
mp.stop();
closeNotification();
}
super.onBackPressed();
}
private Lesson getLesson(int day, int pos) {
Lesson lesson = new Lesson();
sensewareDbHelper sDbHelper = new sensewareDbHelper(getApplicationContext());
SQLiteDatabase db = sDbHelper.getWritableDatabase();
Cursor c = null;
try{
String[] fields = {
sensewareDataSource.Lesson._ID, //0
sensewareDataSource.Lesson.COLUMN_NAME_ID_LESSON, //1
sensewareDataSource.Lesson.COLUMN_NAME_ID_DAY, //2
sensewareDataSource.Lesson.COLUMN_NAME_TITLE, //3
sensewareDataSource.Lesson.COLUMN_NAME_SUBTITLE, //4
sensewareDataSource.Lesson.COLUMN_NAME_POSITION, //5
sensewareDataSource.Lesson.COLUMN_NAME_SECONDS, //6
sensewareDataSource.Lesson.COLUMN_NAME_SECTITLE, //7
sensewareDataSource.Lesson.COLUMN_NAME_TEXT_AUDIO, //8
sensewareDataSource.Lesson.COLUMN_NAME_SELECT_TEXT, //9
sensewareDataSource.Lesson.COLUMN_NAME_GETBACK, //10
sensewareDataSource.Lesson.COLUMN_NAME_COUNTBACK, //11
sensewareDataSource.Lesson.COLUMN_NAME_TEXTFIELD, //12
sensewareDataSource.Lesson.COLUMN_NAME_ID_LANGUAJE, //13
sensewareDataSource.Lesson.COLUMN_NAME_BACKBUTTON, //14
sensewareDataSource.Lesson.COLUMN_NAME_COPY, //15
sensewareDataSource.Lesson.COLUMN_NAME_SRC, //16
sensewareDataSource.Lesson.COLUMN_NAME_BACKBUTTON, //17
sensewareDataSource.Lesson.COLUMN_NAME_NEXTBUTTON, //18
sensewareDataSource.Lesson.COLUMN_NAME_DATE_UPDATE, //19
sensewareDataSource.Lesson.COLUMN_NAME_GROUP_ALL, //20
sensewareDataSource.Lesson.COLUMN_NAME_SECTEXTFIELD //21
};
String where = sensewareDataSource.Lesson.COLUMN_NAME_ID_DAY + "="+ day +" AND " + sensewareDataSource.Lesson.COLUMN_NAME_POSITION +"="+ pos;
c = db.query(
sensewareDataSource.Lesson.TABLE_NAME, // The table to query
fields, // The columns to return
where, // 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
);
if(c.moveToFirst())
{
//Lesson(String title, String subtitle, String src, int id_lesson, int id_languaje, int id_day, int position, int copy, int seconds, int sectitle, int nextbutton, int backbutton, int textfield, int sectextfield, String date_update, int countback, int group_all, int select_text, String getback, String text_audio)
lesson = new Lesson(c.getString(3), c.getString(4), c.getString(16), c.getInt(1), c.getInt(13), c.getInt(2),
c.getInt(5), c.getInt(15), c.getInt(6), c.getInt(7), c.getInt(18), c.getInt(17), c.getInt(12), c.getInt(21), c.getString(19), c.getInt(11), c.getInt(20), c.getInt(9), c.getString(10), c.getString(8) );
}
}catch(Exception e){
e.printStackTrace();
}
return lesson;
}
private void getUtms(){
String utm_source = settings.getString("utm_source", "");
String utm_medium = settings.getString("utm_medium", "");
String utm_term = settings.getString("utm_term", "");
String utm_content = settings.getString("utm_content", "");
String utm_campaign = settings.getString("utm_campaign", "");
SharedPreferences prefs = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
int version = prefs.getInt("appVersion", 0);
utms = "app : 'Android', ";
utms += "'version': "+version;
if(utm_source.compareTo("") != 0)
utms += ", 'utm_source': '" + utm_source + "'";
if(utm_medium.compareTo("") != 0)
utms += ", 'utm_medium': '" + utm_medium + "'";
if(utm_term.compareTo("") != 0)
utms += ", 'utm_term': '" + utm_term + "'";
if(utm_content.compareTo("") != 0)
utms += ", 'utm_content': '" + utm_content + "'";
if(utm_campaign.compareTo("") != 0)
utms += ", 'utm_campaign': '" + utm_campaign + "'";
}
//Configurando los Listeners para los elementos (Views) de la actividad
public void setupListeners(){
//Listener para el boton Play/Pause de los subtitulos
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playFunction();
}
});
//Listener para el boton Play/Pause de las respuestas
startButtonRespuesta.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp.isPlaying()) {
Toast.makeText(getApplicationContext(), "Pausing sound", Toast.LENGTH_SHORT).show();
mp.pause();
startButtonRespuesta.setImageResource(R.mipmap.play_respuesta);
} else {
Toast.makeText(getApplicationContext(), "Playing sound", Toast.LENGTH_SHORT).show();
mp.start();
startButtonRespuesta.setImageResource(R.mipmap.pause_respuesta);
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if (oneTimeOnly == 0) {
seekbarAudio.setMax((int) finalTime);
oneTimeOnly = 1;
}
tx1.setText(String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime)))
);
seekBarRespuesta.setProgress((int) startTime);
//myHandler.postDelayed(UpdateSongTime, 100);
}
}
});
//Listener para el seekbar de los subtitulos
seekbarAudio.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
if(progress<(int)startTime){
mp.seekTo(progress);
}
else {
mp.seekTo((int)startTime);
}
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//Listener para el seekbar de las respuestas
seekBarRespuesta.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public String getFile() {
int day = settings.getInt("day", 1);
if(day == 1)
{
playFunction();
}
else
{
myDir.mkdirs();
File file = new File(myDir, fileName);
// File file = new File (this.getExternalFilesDir("/senseware_sounds"), fileName);
if (!file.exists()) {
progress = ProgressDialog.show(this, "Senseware", "Descargando clase...", true);
new Thread(new Runnable() {
@Override
public void run() {
try {
long space = myDir.getUsableSpace();
Log.i("space", String.valueOf(space));
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
Log.i("CLASE", myDir + " " + fileName + "_tmp");
File file = new File(myDir, fileName + "_tmp");
URL url = new URL(imageUrl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream is = c.getInputStream();
OutputStream os = new FileOutputStream(file);
long sizeFile = is.available();
Log.i("sizeFile", String.valueOf(sizeFile));
if (space > 0 && space >= sizeFile) {
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
is.close();
os.close();
File file_def = new File(myDir, fileName);
file.renameTo(file_def);
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.dismiss();
playFunction();
}
});
} else {
int day = settings.getInt("day", 0);
if (day > 2) {
deleteAudios();
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(AudioClaseActivity.this).create();
alertDialog.setTitle("Senseware");
alertDialog.setMessage("No se han podido descargar las actividades, debido a que no tienes espacio en tu dispositivo");
alertDialog.setButton(-1, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int POSITIVE) {
startActivity(new Intent(AudioClaseActivity.this, ClasesActivity.class));
dialog.cancel();
finish();
}
});
alertDialog.setIcon(R.mipmap.sw_black);
alertDialog.show();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
progress.dismiss();
int day = settings.getInt("id_day", 0);
if (day > 2) {
deleteAudios();
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(AudioClaseActivity.this).create();
alertDialog.setTitle("Senseware");
alertDialog.setMessage("No se han podido descargar las actividades, debido a que no tienes espacio en tu dispositivo");
alertDialog.setButton(-1, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int POSITIVE) {
startActivity(new Intent(AudioClaseActivity.this, ClasesActivity.class));
dialog.cancel();
finish();
}
});
alertDialog.setIcon(R.mipmap.sw_black);
alertDialog.show();
}
});
}
}
}
}).start();
} else {
playFunction();
}
}
return myDir + "/" + fileName;
}
public void playFunction()
{
if (mp.isPlaying()) {
Toast.makeText(getApplicationContext(), "Pausing sound", Toast.LENGTH_SHORT).show();
mp.pause();
startButton.setImageResource(R.mipmap.play_icon);
} else {
final int day = settings.getInt("day", 0);
final String email = settings.getString("email", "");
final int pos = settings.getInt("current", 0);
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final String date = sdf.format(c.getTime());
if (pos == 1) {
String urlEvent = Config.URL_API + "event/Empezodia" + day;
String dataEvent = "{email: '" + email + "', values: [{" + utms + "}]}";
ContentValues values_event = new ContentValues();
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_DATA, dataEvent);
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_DATE, date);
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_HOOK, "event");
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_TYPE, "POST");
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_UPLOAD, 0);
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_URL, urlEvent);
insertEvent("Hook", values_event);
}
try {
if (day == 1) {
AssetFileDescriptor descriptor = getAssets().openFd("sounds/" + fileName);
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
} else {
mp.setDataSource(myDir + "/" + fileName);
}
mp.prepare();
mp.start();
displayNotification();
Toast.makeText(getApplicationContext(), "Playing sound", Toast.LENGTH_SHORT).show();
startButton.setImageResource(R.mipmap.pause);
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if (oneTimeOnly == 0) {
seekbarAudio.setMax((int) finalTime);
oneTimeOnly = 1;
}
tx1.setText(String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime)))
);
seekbarAudio.setProgress((int) startTime);
//myHandler.postDelayed(UpdateSongTime, 100);
countDown = new CountDownTimer(count_seconds * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
//NUEVOOOO
finalTime=mp.getDuration();
seekbarAudio.setMax((int) finalTime);
seekBarRespuesta.setMax((int)finalTime);
startTime = mp.getCurrentPosition();
long tiempoRespuesta = 30;
seekbarAudio.setProgress((int) startTime);
seekBarRespuesta.setProgress((int) startTime);
//NUEVOOOO
mostrarSubtitulo();
count_seconds--;
int play_seconds = current.getSeconds() - count_seconds;
SharedPreferences settings = getSharedPreferences("ActivitySharedPreferences_data", 0);
final EditText textbox = (EditText) findViewById(R.id.respuesta);
if (play_seconds == current.getSectitle()) {
TextView title = (TextView) findViewById(R.id.title);
title.setText(current.getSubtitle());
}
if (current.getTextfield() == 0 && count_seconds == 1) {
//upgradeCurrent();
if (mp.isPlaying()) {
mp.stop();
closeNotification();
}
//((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, InputMethodManager.HIDE_IMPLICIT_ONLY);
String urlEvent = Config.URL_API + "event/Terminoclase";
String dataEvent = "{email: '" + email + "', values: [{day: '" + day + "', clase: '" + pos + "', " + utms + "}]}";
ContentValues values_event = new ContentValues();
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_DATA, dataEvent);
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_DATE, date);
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_HOOK, "event");
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_TYPE, "POST");
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_UPLOAD, 0);
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_URL, urlEvent);
insertEvent("Hook", values_event);
//Fin del dia
/*if (changeDay) {
urlEvent = getString(Config.URL_API) + "event/Terminodia" + day;
values_event = new ContentValues();
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_DATA, dataEvent);
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_DATE, date);
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_HOOK, "event");
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_TYPE, "POST");
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_UPLOAD, 0);
values_event.put(sensewareDataSource.Hook.COLUMN_NAME_URL, urlEvent);
insertEvent("Hook", values_event);
Intent in = new Intent(AudioClaseActivity.this, ShareActivity.class);
startActivity(in);
}*/
if(mp.getDuration() == mp.getCurrentPosition()){
startButton.setImageResource(R.mipmap.reload);
}
finish();
AudioClaseActivity.this.finish();
}
int textfieltype = current.getTextfield();
int moment = current.getSectextfield();
int select_text = current.getSelect_text();
if (textfieltype > 0 && moment > 2 && play_seconds == moment)
{
///NUEVO
barraInferiorAudio.setVisibility(View.GONE);
barraInferiorRespueta.setVisibility(View.VISIBLE);
subtituloContenedor.setVisibility(View.GONE);
respuestaContenedor.setVisibility(View.VISIBLE);
barraSuperiorRespueta.setVisibility(View.VISIBLE);
tiempoCuentaNumero=finalTime-startTime;
//NUEVO
TextView countdown = (TextView) findViewById(R.id.tiempoCuenta);
/*TextView pos = (TextView) findViewById(R.id.position);
ImageButton play = (ImageButton) findViewById(R.id.play);
ImageButton pause = (ImageButton) findViewById(R.id.pause);
Button finish = (Button) findViewById(R.id.finish);*/
TextView title = (TextView) findViewById(R.id.title);
String titleText = title.getText().toString();
if (select_text == 0 && textfieltype == 1) {
textbox.setHint(titleText);
textbox.setHintTextColor(Color.parseColor("#777777"));
} else if (select_text != 0 && textfieltype == 1) {
textbox.setText(titleText);
}
if (textfieltype > 1) // Muestra el textbox muestro respuesta X
{
String getback = current.getGetback();
//FALTA GENTE
//Consulto localmente si no existe, me traigo remoto
String resp = getResult(getback);
Log.i("resp", resp);
if (select_text == 0) {
textbox.setHint(resp);
textbox.setHintTextColor(Color.parseColor("#777777"));
} else {
textbox.setText(resp);
}
} else if (textfieltype == 1 && current.getId_day() == 1 && current.getPosition() == 7) // Muestra el textbox muestro respuesta X
{
String resumen = getResumen();
textbox.setText(resumen);
textbox.setHintTextColor(Color.parseColor("#777777"));
}
title.setVisibility(View.GONE);
//pos.setVisibility(View.GONE);
countdown.setTextSize(50);
countdown.setTop(-180);
countdown.setVisibility(View.GONE);
//countdown2.setVisibility(View.VISIBLE);
//play.setVisibility(View.GONE);
//pause.setVisibility(View.GONE);
//finish.setVisibility(View.VISIBLE);
textbox.setVisibility(View.VISIBLE);
textbox.setCursorVisible(true);
textbox.setTextIsSelectable(true);
textbox.setFocusableInTouchMode(true);
textbox.requestFocus();
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(textbox, InputMethodManager.SHOW_FORCED);
}
TextView cd = (TextView) findViewById(R.id.textView2);
TextView cd2 = (TextView) findViewById(R.id.tiempoCuenta);
cd.setText(getDurationString(count_seconds));
cd2.setText(getDurationString(count_seconds));
//mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
// InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(textbox, InputMethodManager.SHOW_FORCED);
textbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textbox.setFocusableInTouchMode(true);
textbox.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textbox, InputMethodManager.SHOW_FORCED);
}
});
}
@Override
public void onFinish() {
}
}.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private void mostrarSubtitulo()
{
}
private void deleteAudios() {
sensewareDbHelper sDbHelper = new sensewareDbHelper(getApplicationContext());
SQLiteDatabase db = sDbHelper.getWritableDatabase();
Cursor c = null;
int id_day = settings.getInt("day", 0);
try {
String[] projection = {
sensewareDataSource.Lesson._ID,
sensewareDataSource.Lesson.COLUMN_NAME_ID_DAY,
sensewareDataSource.Lesson.COLUMN_NAME_SRC,
};
String whereCol = sensewareDataSource.Lesson.COLUMN_NAME_ID_DAY + " > 1 AND " +
sensewareDataSource.Lesson.COLUMN_NAME_ID_DAY + " != " + String.valueOf(id_day);
c = db.query(
sensewareDataSource.Lesson.TABLE_NAME, // The table to query
projection, // The columns to return
whereCol, // 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
);
int day_delete;
if (c.moveToFirst()){
day_delete = c.getInt(1);
int count = 0;
Log.i("dayDelete", String.valueOf(day_delete));
do{
int dayDelete = c.getInt(1);
if(day_delete == dayDelete) {
String src = c.getString(2);
String[] bits = src.split("/");
String fileName = bits[bits.length - 1];
File myDir = new File(getExternalFilesDir(Environment.getExternalStorageDirectory().toString()) + "/senseware_sounds");
File file = new File(myDir, fileName);
if (file.exists()) {
file.delete();
count ++;
Log.i("deleteAudio", fileName);
}
}
else{
if(count==0){
day_delete = dayDelete;
}
else{
break;
}
}
}while(c.moveToNext());
}
}catch (Exception e){
e.printStackTrace();
}
finally
{
if(c != null)
c.close();
if(!c.isClosed())
db.close();
}
}
private void insertEvent(String tableName, ContentValues values_hook)
{
sensewareDbHelper sDbHelper = new sensewareDbHelper(getApplicationContext());
SQLiteDatabase db = sDbHelper.getWritableDatabase();
long newRowId;
if(tableName.equals("Hook")) {
SaveHook obj = new SaveHook(getApplicationContext(), values_hook, settings);
}
if(tableName.equals("History")) {
newRowId = db.insert(sensewareDataSource.History.TABLE_NAME, null, values_hook);
}
db.close();
}
private String getResult(String getback)
{
String respuesta = "";
Cursor c = null;
String ids_lesson[] = getback.split(" ");
int id_project = settings.getInt("id_project", 0);
try
{
sensewareDbHelper sDbHelper = new sensewareDbHelper(getApplicationContext());
SQLiteDatabase db = sDbHelper.getWritableDatabase();
for (int i = 0; i < ids_lesson.length; i++) {
final String MY_QUERY = "SELECT " + sensewareDataSource.Result.COLUMN_NAME_RESULT +
" FROM " + sensewareDataSource.Result.TABLE_NAME + " r " +
" WHERE id_lesson=? AND " + sensewareDataSource.Result.COLUMN_NAME_ID_PROJECT +" =? "+
"ORDER BY "+ sensewareDataSource.Result.COLUMN_NAME_DATE +" DESC";
c = db.rawQuery(MY_QUERY, new String[]{ids_lesson[i], String.valueOf(id_project)});
if (c.moveToFirst()) {
Log.i("value", ids_lesson[i]);
if(i > 0 ){
if(Integer.valueOf(ids_lesson[i]) != 392 && Integer.valueOf(ids_lesson[i]) != 394)
respuesta = respuesta + " | ";
else
respuesta = respuesta + ", ";
}
respuesta += c.getString(0);
}
else{
try
{
String url = Config.URL_API + "getResultByLesson/" +ids_lesson[i];
String resp = call.callGet(url);
//convert the response from string to JsonObject
JSONObject obj = new JSONObject(resp);
int status = obj.getInt("status");
String message = obj.getString("message");
if (status == 200 && message.equals("OK")) {
String result = obj.getString("result");
respuesta += " | " + result;
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
c.close();
db.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return respuesta;
}
public void displayNotification(){
// Use NotificationCompat.Builder to set up our notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//icon appears in device notification bar and right hand corner of notification
builder.setSmallIcon(R.mipmap.sw_white);
//sound
// builder.setDefaults(NotificationDefaults.Sound)
// This intent is fired when notification is clicked
Intent intent2 = new Intent(this, AudioClaseActivity.class);
// intent2.addFlags( Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent2, 0);
// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);
// Large icon appears on the left of the notification
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Senseware");
// Content text, which appears in smaller text below the title
builder.setContentText("Actualmente tienes una leccion activa");
// The subtext, which appears under the text on newer devices.
// This will show-up in the devices with Android 4.2 and above only
builder.setSubText("Estas realizando la actividad "+ current.getPosition());
builder.setAutoCancel(true);
Notification notification = builder.build();
// notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(current.getPosition(), notification);
}
public void closeNotification(){
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(current.getPosition());
}
private String getDurationString(int seconds) {
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = seconds % 60;
return twoDigitString(minutes) + ":" + twoDigitString(seconds);
}
private String twoDigitString(int number) {
if (number == 0) {
return "00";
}
if (number / 10 == 0) {
return "0" + number;
}
return String.valueOf(number);
}
private String getResumen()
{
String respuestas[] = new String[5];
sensewareDbHelper sDbHelper = new sensewareDbHelper(getApplicationContext());
SQLiteDatabase db = sDbHelper.getWritableDatabase();
Cursor c = null;
Project[] projectsBD = null;
int i = 0;
try
{
String[] projection = { sensewareDataSource.Result.COLUMN_NAME_ID_LESSON, sensewareDataSource.Result.COLUMN_NAME_RESULT };
String whereColProd = sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 200 OR " +
sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 201 OR " +
sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 202 OR " +
sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 203 OR " +
sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 204";
String whereColPrueba = sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 173 OR " +
sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 174 OR " +
sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 175 OR " +
sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 176 OR " +
sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + " = 177";
String order = sensewareDataSource.Result.COLUMN_NAME_DATE + " DESC";
c = db.query(
sensewareDataSource.Result.TABLE_NAME, // The table to query
projection, // The columns to return
whereColProd, // 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
order // The sort order
);
if (c.moveToFirst())
{
do {
respuestas[i] = c.getString(1);
i++;
if(i == 5)
break;
} while (c.moveToNext());
c.close();
db.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
String resumen = "Debes completar la actividad";
if(i == 5) {
resumen = respuestas[4] + " esta diseñado para " +
respuestas[3] + ", resuelve el problema " +
respuestas[2] + ", " +
respuestas[0] + " para " +
respuestas[1];
}
return resumen;
}
}<file_sep>package la.oja.senseware.Modelo;
/**
* Created by Administrador on 10-05-2016.
*/
public class GroupDay {
private int id_gday;
private int id_group;
private int id_day;
private int group_position;
private int active;
public GroupDay(){}
public int getId_gday(){
return this.id_gday;
}
public int getId_group(){
return this.id_group;
}
public int getId_day(){
return this.id_day;
}
public int getGroup_position(){
return this.group_position;
}
public int getActive(){
return this.active;
}
}
<file_sep>package la.oja.senseware;
/**
* Created by jcoaks on 10/5/2016.
*/
public final class Config {
private Config() {
}
public static final String YOUTUBE_API_KEY = "<KEY>";
public static final String URL_API = "http://ojalab.com/senseware/api2/";
}<file_sep>package la.oja.senseware;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import la.oja.senseware.Modelo.Project;
import la.oja.senseware.R;
import la.oja.senseware.data.sensewareDataSource;
import la.oja.senseware.data.sensewareDbHelper;
/**
* Created by Administrador on 12-05-2016.
*/
public class ProjectListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] itemname;
private final Typeface font;
private final Project[] projects;
public ProjectListAdapter(Activity context, String[] itemname, Typeface font, Project[] projects) {
super(context, R.layout.list_row, itemname);
// TODO Auto-generated constructor stub
this.context = context;
this.itemname = itemname;
this.font = font;
// this.projects = new Project[projects.length];
this.projects = projects;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.list_project_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
txtTitle.setTypeface(font);
txtTitle.setText(itemname[position]);
ImageButton edit = (ImageButton) rowView.findViewById(R.id.edit);
ImageButton next = (ImageButton) rowView.findViewById(R.id.select);
SharedPreferences settings = context.getSharedPreferences("ActivitySharedPreferences_data", 0);
int id_project = settings.getInt("id_project", 0);
if(projects[position].getId_project()==id_project)
{
txtTitle.setTextColor(Color.parseColor("#CC1D1D"));
}
edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, EditProjectActivity.class);
intent.putExtra("project", itemname[position]);
intent.putExtra("id_project", projects[position].getId_project());
context.startActivity(intent);
context.finish();
}
});
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Senseware");
alertDialog.setMessage("Esta seguro de cambiar de proyecto");
alertDialog.setButton(-1, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int POSITIVE) {
changeProject(projects[position].getId_project(), projects[position].getId_tmp());
dialog.cancel();
Intent intent = context.getIntent();
context.finish();
context.startActivity(intent);
}
});
alertDialog.setButton(-2, "Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int NEGATIVE) {
dialog.cancel();
}
});
alertDialog.setIcon(R.mipmap.sw_black);
alertDialog.show();
}
});
return rowView;
}
private void changeProject(int id_project, int idTmp) {
SharedPreferences settings = context.getSharedPreferences("ActivitySharedPreferences_data", 0);
SharedPreferences.Editor editor = settings.edit();
if(id_project != 0)
editor.putInt("id_project", id_project);
else{
editor.putInt("id_project", idTmp);
editor.putBoolean("idTmp", true);
id_project = idTmp;
}
sensewareDbHelper sDbHelper = new sensewareDbHelper(context);
SQLiteDatabase db = sDbHelper.getWritableDatabase();
int current = 1;
int day = 1;
Cursor c = null;
try {
String[] projection = {
"MAX(" + sensewareDataSource.Result.COLUMN_NAME_ID_LESSON + ")",
};
String whereCol = sensewareDataSource.Result.COLUMN_NAME_ID_PROJECT + " = " + id_project;
c = db.query(
sensewareDataSource.Result.TABLE_NAME, // The table to query
projection, // The columns to return
whereCol, // 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
);
if(c.moveToFirst())
{
int id_lesson = c.getInt(0);
Log.i("idLesson", String.valueOf(id_lesson));
String[] projection2 = {
sensewareDataSource.Lesson._ID,
sensewareDataSource.Lesson.COLUMN_NAME_ID_DAY,
sensewareDataSource.Lesson.COLUMN_NAME_POSITION
};
String where = sensewareDataSource.Lesson.COLUMN_NAME_ID_LESSON + " = " + String.valueOf(id_lesson);
Cursor cl = db.query(
sensewareDataSource.Lesson.TABLE_NAME, // The table to query
projection2, // The columns to return
where, // 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
);
if(cl.moveToFirst()){
current = cl.getInt(2)+1;
day = cl.getInt(1);
}
}
else{
current =1;
day = 1;
}
}catch (Exception e){
// e.printStackTrace();
}
finally {
if(c != null && !c.isClosed()){
c.close();
}
}
editor.putInt("current", current);
editor.putInt("day", day);
editor.commit();
}
}
<file_sep>package la.oja.senseware.Modelo;
/**
* Created by Administrador on 10-05-2016.
*/
public class Campaign {
private int id_campaign;
private String campaign;
private String type;
private int active;
public Campaign(){}
public int getId_campaign(){
return this.id_campaign;
}
public String getCampaign(){
return this.campaign;
}
public String getType(){
return this.type;
}
public int getActive(){
return this.active;
}
public void setId_campaign(int id_campaign){
this.id_campaign = id_campaign;
return;
}
public void setCampaign(String campaign){
this.campaign = campaign;
return;
}
public void setType(String type){
this.type = type;
return;
}
public void setActive(int Active){
this.active = active;
return;
}
}
<file_sep>package la.oja.senseware;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import la.oja.senseware.data.sensewareDataSource;
import la.oja.senseware.data.sensewareDbHelper;
public class DBActivity extends AppCompatActivity {
public ArrayList<String> listItems=new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db);
sensewareDbHelper sDbHelper = new sensewareDbHelper(getApplicationContext());
SQLiteDatabase db = sDbHelper.getReadableDatabase();
Cursor c = null;
try
{
String[] projection = {
sensewareDataSource.Lesson._ID,
sensewareDataSource.Lesson.COLUMN_NAME_TITLE,
sensewareDataSource.Lesson.COLUMN_NAME_ID_DAY
};
String whereCol = ""; //sensewareDataSource.Lesson.COLUMN_NAME_ID_DAY + " = "+ String.valueOf(id_day);
String sortOrder = sensewareDataSource.Lesson.COLUMN_NAME_ID_DAY + " ASC";
c = db.query(
sensewareDataSource.Lesson.TABLE_NAME, // The table to query
projection, // The columns to return
whereCol, // 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
sortOrder // The sort order
);
if (c.moveToFirst())
{
int i = 0;
do {
listItems.add(c.getString(1) + " > " + c.getString(2));
i++;
} while (c.moveToNext());
c.close();
db.close();
}
ListView lv =(ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter;
adapter=new ArrayAdapter<String>(DBActivity.this,
android.R.layout.simple_list_item_1,
listItems);
lv.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if(c != null)
c.close();
if(!c.isClosed())
db.close();
}
}
}
<file_sep>package la.oja.senseware;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import org.json.JSONObject;
import org.springframework.http.HttpAuthentication;
import org.springframework.http.HttpBasicAuthentication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import la.oja.senseware.Modelo.Project;
import la.oja.senseware.Modelo.User;
import static android.Manifest.permission.READ_CONTACTS;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
private static final String SHARED_PREFERENCES_KEY = "ActivitySharedPreferences_data";
String PROJECT_NUMBER="586199636323";
String RID = null;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"<EMAIL>:hello", "<EMAIL>:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
private ImageButton btnEmail;
private ImageButton btnPsw;
ApiCall call;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// setupActionBar();
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_ACTION_SEND) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mPasswordView.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
btnEmail = (ImageButton) findViewById(R.id.email_clear);
btnPsw = (ImageButton) findViewById(R.id.password_clear);
TextView mSignInLink = (TextView) findViewById(R.id.textCrearCuenta);
TextView mForgetLink = (TextView) findViewById(R.id.textPasswordRecovery);
Typeface ultralight= Typeface.createFromAsset(getAssets(), "fonts/SF-UI-Display-Ultralight.ttf");
Typeface light= Typeface.createFromAsset(getAssets(), "fonts/SF-UI-Text-Light.ttf");
Typeface thin= Typeface.createFromAsset(getAssets(), "fonts/SF-UI-Display-Thin.ttf");
Typeface regular= Typeface.createFromAsset(getAssets(), "fonts/SF-UI-Text-Regular.ttf");
mEmailView.setTypeface(thin);
mPasswordView.setTypeface(thin);
mSignInLink.setTypeface(ultralight);
mForgetLink.setTypeface(ultralight);
mEmailSignInButton.setTypeface(thin);
GCMClientManager pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
@Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
Log.d("Registration id", registrationId);
//send this registrationId to your server
RID = registrationId;
}
@Override
public void onFailure(String ex) {
super.onFailure(ex);
Log.i("registrationID", "fallo");
}
});
mEmailView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length()==0)
btnEmail.setVisibility(View.GONE);
else
btnEmail.setVisibility(View.VISIBLE);
}
@Override
public void afterTextChanged(Editable s) {
}
});
mEmailView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus && !TextUtils.isEmpty(mEmailView.getText()))
btnEmail.setVisibility(View.VISIBLE);
else
btnEmail.setVisibility(View.GONE);
}
});
mPasswordView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().length() == 0)
btnPsw.setVisibility(View.GONE);
else
btnPsw.setVisibility(View.VISIBLE);
}
@Override
public void afterTextChanged(Editable s) {
}
});
mPasswordView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus && !TextUtils.isEmpty(mPasswordView.getText()))
btnPsw.setVisibility(View.VISIBLE);
else
btnPsw.setVisibility(View.GONE);
}
});
btnEmail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.email);
tv.setText("");
btnEmail.setVisibility(View.GONE);
}
});
btnPsw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.password);
tv.setText("");
btnPsw.setVisibility(View.GONE);
}
});
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
/* @TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
*/
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = <PASSWORD>().<PASSWORD>();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (TextUtils.isEmpty(password)){
mPasswordView.setError(getString(R.string.error_required));
focusView = mPasswordView;
cancel = true;
}else if(!TextUtils.isEmpty(password) && !isPassworShort(password)) {
mPasswordView.setError(getString(R.string.error_pswd_short));
focusView = mPasswordView;
cancel = true;
} else if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_pswd) );
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute();
//Intent intento = new Intent(this, ClasesActivity.class);
// startActivity(intento);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
// return email.contains("@");
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private boolean isPassworShort(String password) {
return password.length() > 4;
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
// return password.length() > 4;
boolean valid = true;
if((password.indexOf('\'') >= 0 || password.indexOf('"') >= 0))
valid = false;
return valid;
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, String> {
private final String mEmail;
private final String mPassword;
private String responseApi;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = <PASSWORD>;
}
@Override
protected String doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
final String url = Config.URL_API + "login";
SharedPreferences prefs = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
boolean newRegisterId = prefs.getBoolean("newRegistrationID", false);
String data = "";
if(newRegisterId)
data = "{'registration_id': '"+RID+"', 'platform': 'Android' }";
HttpAuthentication authHeader = new HttpBasicAuthentication(mEmail, mPassword);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
call = new ApiCall(mEmail, mPassword);
String resp = call.callPost(url, data);
//convert the response from string to JsonObject
JSONObject info = new JSONObject(resp);
int status = info.getInt("status");
String message = info.getString("message");
if (status == 200 && message.equals("OK")) {
String result = info.getString("result");
if(result.equals("Datos incorrectos") || result.equals("Email no registrado")) {
responseApi = result;
}
else
{
responseApi = "success";
JSONObject obj = new JSONObject(info.get("result").toString());
User userData = new User();
userData.setId_user(Integer.parseInt((String) obj.get("id_user")));
userData.setEmail(mEmail);
//userData.setPhone((String) obj.get("phone"));
userData.setPassword((String) obj.get("password"));
userData.setHasSuscriptionActive((boolean) obj.get("hasSuscriptionActive"));
Project project = new Project();
project.setId_project(Integer.parseInt((String) obj.get("id_project")));
project.setId_user(Integer.parseInt((String) obj.get("id_user")));
project.setNa_project((String) obj.get("na_project"));
SharedPreferences settings = getSharedPreferences(SHARED_PREFERENCES_KEY, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("id_user", userData.getId_user());
editor.putString("email", obj.getString("email"));
editor.putString("phone", obj.getString("phone"));
editor.putString("password", obj.<PASSWORD>("<PASSWORD>"));
editor.putInt("id_project", project.getId_project());
editor.putString("na_project", obj.getString("na_project"));
editor.putInt("day", obj.getInt("day"));
editor.putInt("current", obj.getInt("current"));
editor.putInt("max_day", obj.getInt("day"));
editor.putInt("max_current", obj.getInt("current"));
editor.putBoolean("hasSuscriptionActive", userData.getHasSuscriptionActive());
editor.commit();
}
}
else
{
responseApi = "Error de Conexión";
}
} catch (Exception e) {
responseApi = "Error de Conexión";
}
return responseApi;
}
@Override
protected void onPostExecute(final String resp) {
mAuthTask = null;
showProgress(false);
if(!resp.isEmpty() && (resp.equals("Datos incorrectos") || resp.equals("Email no registrado"))) {
mEmailView.setError(resp);
View focusView = null;
focusView = mEmailView;
focusView.requestFocus();
showProgress(false);
}
else if(!resp.isEmpty() && resp.equals("Error de Conexión"))
{
View focusView = null;
focusView = mEmailView;
focusView.requestFocus();
showProgress(false);
Snackbar snackbar = Snackbar
.make(findViewById(android.R.id.content), responseApi, Snackbar.LENGTH_LONG);
snackbar.show();
}
else {
responseApi = null;
finish();
startActivity(new Intent(LoginActivity.this, ClasesActivity.class));
finish();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
<file_sep>package la.oja.senseware.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by jcoaks on 11/12/2015.
*/
public class sensewareDbHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 6;
public static final String DATABASE_NAME = "senseware.db";
public sensewareDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
db.execSQL(sensewareDataSource.SQL_CREATE_USERS);
db.execSQL(sensewareDataSource.SQL_CREATE_LESSONS);
db.execSQL(sensewareDataSource.SQL_CREATE_DAYS);
db.execSQL(sensewareDataSource.SQL_CREATE_HISTORY);
db.execSQL(sensewareDataSource.SQL_CREATE_HOOKS);
db.execSQL(sensewareDataSource.SQL_CREATE_PROJECT);
db.execSQL(sensewareDataSource.SQL_CREATE_CAMPAING);
db.execSQL(sensewareDataSource.SQL_CREATE_USER_CAMPAIGN);
db.execSQL(sensewareDataSource.SQL_CREATE_NOTIFICATION);
db.execSQL(sensewareDataSource.ALTER_LESSONS_COUNTBACK);
db.execSQL(sensewareDataSource.ALTER_LESSON_GROUP);
db.execSQL(sensewareDataSource.SQL_CREATE_RESULT);
db.execSQL(sensewareDataSource.ALTER_LESSON_SELECT_TEXT);
db.execSQL(sensewareDataSource.ALTER_LESSON_GETBACK);
db.execSQL(sensewareDataSource.ALTER_RESULT);
db.execSQL(sensewareDataSource.ALTER_USER);
db.execSQL(sensewareDataSource.ALTER_LESSON_AUDIO);
db.execSQL(sensewareDataSource.ALTER_RESULT_PUBLICO);
db.execSQL(sensewareDataSource.ALTER_PROJECT);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
//db.execSQL(sensewareDataSource.SQL_DELETE_ENTRIES);
// onCreate(db);
if(oldVersion < 2)
{
db.execSQL(sensewareDataSource.ALTER_LESSONS_COUNTBACK);
db.execSQL(sensewareDataSource.ALTER_LESSON_GROUP);
}
if(oldVersion < 3)
{
db.execSQL(sensewareDataSource.SQL_CREATE_RESULT);
}
if(oldVersion < 4) {
db.execSQL(sensewareDataSource.ALTER_LESSON_SELECT_TEXT);
db.execSQL(sensewareDataSource.ALTER_LESSON_GETBACK);
}
if(oldVersion < 5)
db.execSQL(sensewareDataSource.ALTER_RESULT);
if(oldVersion < 6)
{
db.execSQL(sensewareDataSource.ALTER_USER);
db.execSQL(sensewareDataSource.ALTER_LESSON_AUDIO);
db.execSQL(sensewareDataSource.ALTER_RESULT_PUBLICO);
db.execSQL(sensewareDataSource.ALTER_PROJECT);
db.execSQL(sensewareDataSource.SQL_CREATE_CAMPAING);
db.execSQL(sensewareDataSource.SQL_CREATE_USER_CAMPAIGN);
db.execSQL(sensewareDataSource.SQL_CREATE_NOTIFICATION);
}
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}<file_sep>package la.oja.senseware.Modelo;
/**
* Created by Administrador on 10-05-2016.
*/
public class Result {
private int id_result;
private int id_source;
private int id_project;
private int id_lesson;
private String result;
private String date;
private int assigned;
private int hidden;
private int publico;
public Result(){}
public Result(int id_result, int id_project, int id_lesson, int id_source, String result, String date, int assigned, int hidden, int publico){
this.id_result = id_result;
this.id_project = id_project;
this.id_lesson = id_lesson;
this.id_source = id_source;
this.result = result;
this.date = date;
this.assigned = assigned;
this.hidden = hidden;
this.publico = publico;
}
public int getId_result(){
return this.id_result;
}
public int getId_source(){
return this.id_result;
}
public int getId_project(){
return this.id_project;
}
public int getId_lesson(){
return this.id_lesson;
}
public String getResult(){
return this.result;
}
public String getDate(){
return this.date;
}
public int getAssigned(){
return this.assigned;
}
public int getHidden(){
return this.hidden;
}
public int getPublico(){
return this.publico;
}
}
|
11d4588fb356fd6eb87fe1972870bab658f4b8f3
|
[
"Markdown",
"Java"
] | 16
|
Markdown
|
rambardeveloper/Senseware
|
1079d5fb2c4364a09640dafe611f28c780412076
|
6ffe07ceab3747e9029c96503741839e4cc71d5a
|
refs/heads/master
|
<repo_name>ArielARD/pcDuinoNew<file_sep>/src/com/example/pcduino/MainActivity.java
package com.example.pcduino;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import com.codeminders.ardrone.ARDrone;
import com.codeminders.ardrone.ARDrone.ConfigOption;
import com.codeminders.ardrone.NavData;
import com.codeminders.ardrone.NavDataListener;
import com.codeminders.ardrone.data.navdata.vision.VisionTag;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.net.sip.SipAudioCall.Listener;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Time;
import android.text.method.TextKeyListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ARDrone drone = null;
Handler handler;
TextView roll;
TextView pitch;
TextView yaw;
TextView Battery;
TextView FlyingState;
Sensor sensor1;
Sensor sensor2;
Sensor sensor3;
boolean flagData;
boolean flagSensor;
boolean check;
BluetoothAdapter mBluetoothAdapter = null;
BluetoothDevice mmDevice = null;
BluetoothSocket mmSocket = null;
OutputStream mmOutputStream = null;
InputStream mmInputStream = null;
boolean stopWorker = false;
String data;
Canvas canvas;
final int meter = 20; // for distance in canvas
final int center = 150 / 2;
final int barrier = 10;
double dist;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
data = "";
// 20:14:04:14:34:66
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// Note, you will need to change this to match the name of your
// device
// device.getName().equals("HC-06") ||
String btMac = device.getAddress();
if (btMac.equals("20:14:04:14:34:66")) {
mmDevice = device;
break;
}
}
}
try {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // Standard
// SerialPortService
// ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
} catch (Exception exc) {
}
Thread workerThread = new Thread(new Runnable() {
public void run() {
String accumulator = "";
byte separator = (char) '\n';
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
if (packetBytes[i] == separator) {
ProcessArduinoData(accumulator);
accumulator = "";
} else
accumulator += (char) packetBytes[i];
}
}
} catch (Exception exc) {
}
}
try {
mmSocket.close();
mmInputStream.close();
mmOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("BT", "\n\n\n\nKilled !!!\n\n\n\n");
}
});
workerThread.start();
Toast.makeText(this, " ~~~~ NINY Project ~~~~ ", Toast.LENGTH_LONG)
.show();
sensor1 = new Sensor();
sensor2 = new Sensor();
sensor3 = new Sensor();
try {
drone = new ARDrone();
handler = new Handler();
} catch (UnknownHostException e) {
e.printStackTrace();
}
findView();
flagData = false;
flagSensor = false;
check = false;
final Paint paint = new Paint();
paint.setColor(Color.RED);
final Paint paintBorder = new Paint();
paintBorder.setColor(Color.GREEN);
final Paint paintCancel = new Paint();
paintCancel.setColor(Color.WHITE);
Bitmap bg = Bitmap.createBitmap(150, 150, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bg);
canvas.drawLine(0, 0, 150, 0, paintBorder);
canvas.drawLine(0, 0, 0, 150, paintBorder);
canvas.drawLine(0, 149, 149, 149, paintBorder);
canvas.drawLine(149, 0, 149, 149, paintBorder);
canvas.drawPoint(center, center, paint);
LinearLayout ll = (LinearLayout) findViewById(R.id.rect);
ll.setBackgroundDrawable(new BitmapDrawable(bg));
sensor1.DisText = (TextView) findViewById(R.id.Distance1);
final Runnable run = new Runnable() {
@Override
public void run() {
if (dist > 1) {
canvas.drawLine(center - barrier,
(float) (center - meter * dist), center
+ barrier, (float) (center - meter
* dist), paintBorder);
} else {
canvas.drawLine(center - barrier,
(float) (center - meter * dist), center
+ barrier, (float) (center - meter
* dist), paint);
}
}
};
sensor1.DisText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
dist = val2mlarge((int) Double.parseDouble(sensor1.DisText
.getText().toString()));
handler.post(run);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
});
}
public double val2mlarge(int val) {
double tmp = 0;
if (val >= 460 && val < 500) {
tmp = (460 + 500) / val;
return (1.2 + 1) / tmp;
} else if (val > 420 && val <= 460) {
tmp = (420 + 460) / val;
return (1.4 + 1.2) / tmp;
} else if (val > 395 && val <= 420) {
tmp = (395 + 420) / val;
return (1.6 + 1.4) / tmp;
} else if (val > 375 && val <= 395) {
tmp = (375 + 395) / val;
return (1.8 + 1.6) / tmp;
} else if (val > 355 && val <= 375) {
tmp = (355 + 375) / val;
return (2 + 1.8) / tmp;
} else if (val > 325 && val <= 355) {
tmp = (325 + 355) / val;
return (2.5 + 2) / tmp;
} else if (val <= 325) {
tmp = (0 + 325) / val;
return (5 + 2.5) / tmp;
}
return 1;
}
public void findView() {
roll = (TextView) findViewById(R.id.roll);
pitch = (TextView) findViewById(R.id.pitch);
yaw = (TextView) findViewById(R.id.Yaw);
Battery = (TextView) findViewById(R.id.Battery);
FlyingState = (TextView) findViewById(R.id.FlyingState);
sensor1.DisText = (TextView) findViewById(R.id.Distance1);
}
public void setSensor() {
sensor1.adc = new ADC();
sensor1.pin = Integer.parseInt("2");
sensor2.adc = new ADC();
sensor2.pin = Integer.parseInt("3");
sensor3.adc = new ADC();
sensor3.pin = Integer.parseInt("4");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void Connect(View v) {
try {
drone.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
public void trim(View v) {
try {
drone.trim();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disConnect(View v) {
try {
drone.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
public void playLed(View v) {
try {
drone.playLED(1, 10, 3);
} catch (IOException e) {
e.printStackTrace();
}
}
public void clear(View v) {
try {
drone.clearEmergencySignal();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setEmer(View v) {
try {
drone.sendEmergencySignal();
} catch (IOException e) {
e.printStackTrace();
}
}
public void getSensorDis(final Sensor sensor) {
Thread threadSen = new Thread(new Runnable() {
public void run() {
while (flagSensor) {
try {
sensor.pinValue = sensor.adc.analogRead(sensor.pin);
sensor.volts = sensor.pinValue * 0.0012207;
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
threadSen.start();
}
public void takeOff(View v) {
try {
drone.takeOff();
} catch (IOException e) {
e.printStackTrace();
}
}
public void Land(View v) {
try {
drone.land();
} catch (IOException e) {
e.printStackTrace();
}
}
public void OnOffData(View v) {
if (!flagData) {
flagData = true;
} else {
flagData = false;
}
startData();
}
public void startData() {
NavDataListener nd = new NavDataListener() {
@Override
public void navDataReceived(final NavData nd) {
handler.post(new Runnable() {
@Override
public void run() {
roll.setText(nd.getRoll() + "");
pitch.setText(nd.getPitch() + "");
Battery.setText(nd.getBattery() + "");
yaw.setText(nd.getYaw() + "");
FlyingState.setText(nd.getFlyingState() + "");
// sensor1.DisText.setText(Double.toString(sensor1.volts).substring(0,5));
sensor1.DisText.setText(data);
}
});
}
};
if (flagData)
drone.addNavDataListener(nd);
else
drone.removeNavDataListener(nd);
}
public void up() {
try {
drone.move(0, 0, 20, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void down() {
try {
drone.move(0, 0, -20, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void left() {
try {
drone.move(-20, 0, 0, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void right() {
try {
drone.move(20, 0, 0, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void hover(View v) {
try {
drone.hover();
} catch (IOException e) {
e.printStackTrace();
}
}
public void upPit() {
try {
drone.move(0, -20, 0, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void downPit() {
try {
drone.move(0, 20, 0, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void leftYaw() {
try {
drone.move(0, 0, 0, -20);
} catch (IOException e) {
e.printStackTrace();
}
}
public void rightYaw() {
try {
drone.move(0, 0, 0, 20);
} catch (IOException e) {
e.printStackTrace();
}
}
public void GoStraight(final int numOfPress, final int MissionTime) {
Thread thread = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < numOfPress; i++) {
try {
drone.move(0, 0, MissionTime, 0);
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
public void WaitForTask(final int seconds) {
Thread thread = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < seconds; i++) {
try {
drone.hover();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
public void Mis1(View v) {
try {
drone.takeOff();
leftYaw();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void ProcessArduinoData(String data) {
// Log.i("BT",data);
this.data = data;
}
}
|
acceccf95a02c2fa69be1b5ccd37f0dfe503f0e1
|
[
"Java"
] | 1
|
Java
|
ArielARD/pcDuinoNew
|
fdafb0ae3045ed90a6e5dfedc530fc99e83c58ad
|
663e088c6c2eabed1a546d5af7e587575e8352e8
|
refs/heads/master
|
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "phonebook_opt.h"
/* FILL YOUR OWN IMPLEMENTATION HERE! */
entry *findName(char lastName[], entry *pHead)
{
/*
while (pHead != NULL) {
if (strcasecmp(lastName, pHead->lastName) == 0)
return pHead;
pHead = pHead->pNext;
}
return NULL;
*/
unsigned int idx = hash(lastName);
pHead = hash_table[idx];
while (pHead != NULL) {
if (strcasecmp(lastName, pHead->lastName) == 0)
return pHead;
pHead = pHead->pNext;
}
return NULL;
}
entry *hash_table[HASH_TABLE_SIZE] = {NULL};
entry *append(char lastName[], entry *e)
{
/* allocate memory for the new entry and put lastName */
/*
e->pNext = (entry *) malloc(sizeof(entry));
e = e->pNext;
strcpy(e->lastName, lastName);
e->pNext = NULL;
return e;
*/
unsigned int idx = hash(lastName);
if(hash_table[idx] == NULL) {
hash_table[idx] = (entry *) malloc(sizeof(entry));
hash_table[idx]->pNext = NULL;
strcpy(hash_table[idx]->lastName, lastName);
} else {
/*
e = hash_table[idx];
while(e->pNext != NULL) {
e = e->pNext;
}
e->pNext = (entry *) malloc(sizeof(entry));
e = e->pNext;
e->pNext = NULL;
strcpy(e->lastName, lastName);
*/
entry *h;
h = (entry *) malloc(sizeof(entry));
strcpy(h->lastName, lastName);
h->pNext = hash_table[idx];
hash_table[idx] = h;
}
return e;
}
unsigned int hash(char *key)
{
unsigned int hashVal = 0;
while (*key != '\0') {
hashVal = (hashVal << 5) + *key++;
}
return hashVal % HASH_TABLE_SIZE;
}
|
2bd6dc6c7d1164a2eebae84ee5e4ddebbac93b7b
|
[
"C"
] | 1
|
C
|
LittleWhiteYA/phonebook
|
43fb0036989e3e9ade0b5f94eb9be37537e284d8
|
ac306756593a720739e08902e5020740d97c3d6e
|
refs/heads/master
|
<repo_name>jonathansouzal/carFlixMarvelNative<file_sep>/src/services/api.js
import axios from 'axios';
export const api = axios.create({
baseURL: 'https://gateway.marvel.com',
});
export const AUTHENTICATION = {
ts: '1617861202',
apikey: '<KEY>',
hash: '977d040b6bab779a9a8facadaaf2cb54',
};
<file_sep>/__tests__/api_hero.test.js
import { getHeros } from '../src/context/HeroContext';
test('test api all hero', async () => {
return await getHeros().then(response => {
expect(response.data.code).toBe(200);
});
});
test('test api one hero', async () => {
return await getHeros('spider-man (<NAME>)').then(response => {
let result = response.data.data.results[0];
expect(result.name).toBe('Spider-Man (<NAME>)');
});
});<file_sep>/src/interfaces/interfaces.ts
export interface IHeroComic {
id: number;
title: string;
issueNumber: number;
thumbnail: IThumbnail;
prices: IPrices[];
}
export interface IThumbnail {
path: string;
extension: string;
}
export interface IPrices {
type: string;
price: string;
}
export interface IHero {
id: number;
name: string;
thumbnail: IThumbnail;
}
export interface IHeroContext {
heros: IHero[];
reloadHeros: Function;
}
<file_sep>/src/screens/Home/Home.strings.ts
const HomeStrings = {
marvel: 'MARVEL',
welcome: 'Welcome Oowlish!',
heros: "Choose Your Hero's App",
btnHeros: 'Click here to choose your Hero',
textInfo:
'This application aims to have fun, choose your heroes and relive every emotion that only Marvel knows how to provide us.',
};
export default HomeStrings;
<file_sep>/src/screens/Home/Home.styles.ts
import styled from 'styled-components/native';
export const ImageCoverHome = styled.ImageBackground`
height: 100%;
width: 100%;
padding: 8%;
display: flex;
justify-content: flex-end;
align-items: center;
`;
export const CardWelcome = styled.View`
height: auto;
background-color: rgba(255,255,255,0.9);
border-top-right-radius: 10px;
border-top-left-radius: 10px;
padding-top: 20px;
padding-bottom: 10px;
`;
export const HomeText = styled.Text`
font-size: 18px;
text-align: center;
justify-content: center;
align-items: center;
color: #341948;
font-weight: 700;
`;
export const HomeInfo = styled.Text`
font-size: 14px;
text-align: center;
justify-content: center;
align-items: center;
margin: 4px;
color: #000;
font-weight: 400;
padding: 10px;
`;
export const ButtonHome = styled.TouchableOpacity`
background-color: #341948;
height: auto;
width: 100%;
padding: 10px;
color: #fff;
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
`;
export const HomeInfoBottom = styled.Text`
font-size: 16px;
text-align: center;
justify-content: center;
align-items: center;
color: #fff;
font-weight: 700;
padding: 10px;
`;
<file_sep>/src/screens/HeroDetail/HeroDatail.styles.ts
import { StyleSheet } from 'react-native';
import styled from 'styled-components/native';
export const ComicConteiner = styled.ImageBackground`
height: 100%;
background-color: #341948;
padding: 5%;
`;
export const ComicsCards = styled.View`
background-color: rgba(52, 25, 72, 0.9);
border-radius: 10px;
margin-top: 20px;
display: flex;
flex-direction: row;
width: 100%;
height: 160px;
`;
export const ComicsInfos = styled.View`
justify-content: center;
width: 70%;
height: 100%;
display: flex;
flex-direction: column;
padding: 20px;
`;
export const ComicCover = styled.Image`
width: 30%;
height: 100%;
border-radius: 10px;
`;
export const ComicsInfoText = styled.Text`
font-size: 14px;
margin: 2px;
color: #fff;
font-weight: 400;
`;
export const CardInfo = styled.View`
margin-top: 5%;
margin-bottom: 5%;
border-radius: 10px;
background-color: rgba(255, 255, 255, 0.9);
width: 100%;
justify-content: center;
`;
export const HeroInfo = styled.Text`
font-size: 14px;
text-align: center;
justify-content: center;
align-items: center;
margin: 4px;
color: #341948;
font-weight: 700;
padding: 10px;
`;
export const styles = StyleSheet.create({
shadow: {
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.23,
shadowRadius: 2.62,
elevation: 4,
},
});
<file_sep>/src/screens/Search/Search.styles.ts
import styled from 'styled-components/native';
import { StyleSheet } from 'react-native';
export const SearchContainer = styled.ImageBackground`
background-color: #341948;
height: 100%;
padding: 15px;
`;
export const ButtonHero = styled.TouchableOpacity`
background-color: rgba(rgba(52, 25, 72, 1), 0.9);
color: #fff;
border-radius: 10px;
width: 40%;
height: 300px;
margin-bottom: 20px;
margin-left: auto;
margin-right: auto;
`;
export const ButtonHeroOne = styled.TouchableOpacity`
background-color: rgba(rgba(52, 25, 72, 1), 0.5);
color: #fff;
border-radius: 10px;
width: 90%;
height: 300px;
margin-bottom: 20px;
margin-left: auto;
margin-right: auto;
`;
export const ButtonHeroSearch = styled.TouchableOpacity`
width: 37px;
height: 37px;
border-radius: 10px;
justify-content: center;
align-items: center;
background-color: #fff;
`;
export const ImageHeroCover = styled.Image`
height: 80%;
padding: 5%;
border-radius: 10px;
`;
export const ImageHeroCoverOne = styled.Image`
height: 80%;
padding: 5%;
border-radius: 10px;
`;
export const HeroTextContent = styled.View`
height: 20%;
justify-content: center;
align-items: center;
`;
export const HeroName = styled.Text`
font-size: 14px;
text-align: center;
color: #fff;
font-weight: 700;
padding: 10px;
`;
export const SearchInput = styled.TextInput`
width: 80%;
height: 40px;
margin: 10px;
border-width: 1px;
border-radius: 10px;
border-color: #fff;
padding: 8px;
color: #fff;
`;
export const SearchInputContainer = styled.View`
width: 100%;
display: flex;
flex-direction: row;
align-items: center;
margin-top: 10px;
margin-bottom: 20px;
`;
export const SearchFlatList = styled.FlatList`
margin-top: 10px;
`;
export const styles = StyleSheet.create({
shadow: {
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.23,
shadowRadius: 2.62,
elevation: 4,
},
});
|
c3627d405d27615603298b7c8d7f163e14b4f6d9
|
[
"JavaScript",
"TypeScript"
] | 7
|
JavaScript
|
jonathansouzal/carFlixMarvelNative
|
c9aa1e88a9e855ea42e5f329dd00a8e8da93af28
|
777d398e4edabab6956e798f495c76abcd86e0a7
|
refs/heads/main
|
<file_sep>#include <drivers/driver.h>
#include <common/types.h>
using namespace osd::common;
using namespace osd::drivers;
Driver :: Driver()
{}
Driver :: ~Driver()
{}
void Driver :: Activate()
{}
int Driver :: Reset()
{
return 0;
}
void Driver :: Deactivate()
{
}
DriverManager :: DriverManager()
{
numDrivers = 0;
}
void DriverManager :: AddDriver(Driver* drv)
{
// if an index is set with the driver then we go to next
drivers[numDrivers] = drv;
numDrivers++;
}
void DriverManager :: ActivateAll()
{
for(int i = 0; i < numDrivers; i++)
{
drivers[i] -> Activate();
}
// here iterating through and activating all the drivers
}<file_sep>#ifndef __OSD__GUI__WIDGET_H
#define __OSD__GUI__WIDGET_H
#include <common/types.h>
#include <common/graphicscontext.h>
#include <drivers/keyboard.h>
namespace osd
{
namespace gui
{
// we are combining the keyboard and the widget
class Widget : public osd::drivers::KeyboardEventHandler
{
protected:
Widget* parent;
osd::common::int32_t x; // x - axis
osd::common::int32_t y; // y - axis
osd::common::int32_t w; // width
osd::common::int32_t h; // height
osd::common::uint8_t r; // percentage of red
osd::common::uint8_t g; // percentage of green
osd::common::uint8_t b; // percentage of blue
bool Focussable; // on which widget to focus on
// you can make different type of things using widget
// most of the gui is made with the help of this only
public:
// taking the initial values of the variables declared above
Widget(Widget* parent, osd::common::int32_t x, osd::common::int32_t y, osd::common::int32_t w, osd::common::int32_t h, osd::common::uint8_t r, osd::common::uint8_t g, osd::common::uint8_t b);
~Widget();
virtual void GetFocus(Widget* widget); // for more than 1 widget
virtual void ModelToScreen(osd::common::int32_t &x, osd::common::int32_t &y); // to show on screen
virtual bool ContainsCoordinate(common::int32_t x, common::int32_t y);
virtual void Draw(osd::common::GraphicsContext* gc);
virtual void OnMouseDown(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button);
virtual void OnMouseUp(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button);
virtual void OnMouseMove(osd::common::int32_t oldx, osd::common::int32_t oldy, osd::common::int32_t newx, osd::common::int32_t newy);
};
// we are combining the widget and the mouse
class CompositeWidget : public Widget
{
private:
Widget* children[100]; // also same as above but this is for if you want a widget inside a widget
int numChildren;
Widget* focussedChild;
public:
CompositeWidget(Widget* parent, osd::common::int32_t x, osd::common::int32_t y, osd::common::int32_t w, osd::common::int32_t h, osd::common::uint8_t r, osd::common::uint8_t g, osd::common::uint8_t b);
~CompositeWidget();
virtual void GetFocus(Widget* widget);
virtual bool AddChild(Widget* child);
virtual void Draw(osd::common::GraphicsContext* gc);
virtual void OnMouseDown(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button);
virtual void OnMouseUp(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button);
virtual void OnMouseMove(osd::common::int32_t oldx, osd::common::int32_t oldy, osd::common::int32_t newx, osd::common::int32_t newy);
virtual void OnKeyDown(char str);
virtual void OnKeyUp(char str);
};
}
}
#endif<file_sep>#ifndef OSD__HARDWARECOMMUNICATION__INTERRUPTS_H
#define OSD__HARDWARECOMMUNICATION__INTERRUPTS_H
#include <common/types.h>
#include <hardwarecommunication/port.h>
#include <gdt.h>
#include <multitasking.h>
namespace osd
{
namespace hardwarecommunication
{
class InterruptManager;
class InterruptHandler
{
protected:
osd::common::uint8_t interruptNumber;
InterruptManager* interruptManager;
InterruptHandler(osd::common::uint8_t interruptNumber, InterruptManager* interruptManager);
~InterruptHandler();
public:
virtual osd::common::uint32_t HandleInterrupt(osd::common::uint32_t esp);
};
class InterruptManager
{
friend class InterruptHandler;
protected:
static InterruptManager* ActiveInterruptManager;
InterruptHandler* handlers[256];
TaskManager *taskManager;
struct GateDescriptor
{
osd::common::uint16_t handleAddressLowBits;
osd::common::uint16_t gdt_codeSegmentSelector;
osd::common::uint8_t reserved;
osd::common::uint8_t access;
osd::common::uint16_t handleAddressHighBits;
}__attribute__((packed));
static GateDescriptor interruptDescriptorTable[256];
struct InterruptDescriptorTablePointer
{
osd::common::uint16_t size;
osd::common::uint32_t base;
}__attribute__((packed));
static void SetInterruptDescriptorTableEntry(
osd::common::uint8_t interruptNumber,
osd::common::uint16_t codeSegmentSelectorOffset,
void (*handler)(),
osd::common::uint8_t DescriptorPrivilegeLevel,
osd::common::uint8_t DescriptorType
);
osd::hardwarecommunication::Port8bitSlow picMasterCommand;
osd::hardwarecommunication::Port8bitSlow picMasterData;
osd::hardwarecommunication::Port8bitSlow picSlaveCommand;
osd::hardwarecommunication::Port8bitSlow picSlaveData;
public:
InterruptManager(osd::common::uint16_t hardwareInterruptOffset, osd::GlobalDescriptionTable* gdt, osd::TaskManager *taskManager);
~InterruptManager();
void Activate();
void Deactivate();
static osd::common::uint32_t handleInterrupt(osd::common::uint8_t interruptNumber, osd::common::uint32_t esp);
osd::common::uint32_t DoHandleInterrupt(osd::common::uint8_t interruptNumber, osd::common::uint32_t esp);
static void IgnoreInterruptRequest();
static void HandleInterruptRequest0x00();
static void HandleInterruptRequest0x01();
static void HandleInterruptRequest0x0C();
};
}
}
#endif<file_sep>#ifndef __OSD__COMMON__GRAPHICSCONTExT_H
#define __OSD__COMMON__GRAPHICSCONTExT_H
#include <drivers/vga.h>
namespace osd
{
namespace common
{
typedef osd::drivers::VideoGraphicsArray GraphicsContext;
}
}
#endif<file_sep># OS_PROJECT
A Simple Operating System made from Scratch.
<file_sep>#ifndef __OSD__DRIVERS__DRIVER_H
#define __OSD__DRIVERS__DRIVER_H
namespace osd
{
namespace drivers
{
// using drivers class so that we can define many types of drivers
class Driver{
public:
// this is the base class, we will inherit from it
Driver();
~Driver();
virtual void Activate(); // used to activate the driver
virtual int Reset(); // used to reset the driver to default
virtual void Deactivate(); // used to deactivate the driver
};
class DriverManager{
private:
Driver* drivers[255]; // this is the number of drivers that we can put
int numDrivers; // driver that we currently working in
public:
DriverManager();
void AddDriver(Driver* );
void ActivateAll();
// this function will activate all the device drivers
};
}
}
#endif<file_sep>
#ifndef __OSD__GUI__DESKTOP_H
#define __OSD__GUI__DESKTOP_H
#include <gui/widget.h>
#include <drivers/mouse.h>
namespace osd
{
namespace gui
{
class Desktop : public osd::gui::CompositeWidget, public osd::drivers::MouseEventHandler
{
protected:
osd::common::uint32_t MouseX; // this is the mouse position on x-axis
osd::common::uint32_t MouseY; // this is the mouse position on y-axis
public:
Desktop(osd::common::int32_t w, osd::common::int32_t h,
osd::common::uint8_t r, osd::common::uint8_t g, osd::common::uint8_t b);
~Desktop();
void Draw(osd::common::GraphicsContext* gc); // it reference to the Video graphics array
void OnMouseDown(osd::common::uint8_t button); // this is for mouse button clicked
void OnMouseUp(osd::common::uint8_t button); // for mouse button released
void OnMouseMove(int x, int y); // we have to change x - axis and y - axis when mouse is moved
};
}
}
#endif<file_sep>#ifndef OSD__HARDWARECOMMUNICATION__PORT_H
#define OSD__HARDWARECOMMUNICATION__PORT_H
#include <common/types.h>
namespace osd
{
namespace hardwarecommunication
{
class Port
{
protected:
osd::common::uint16_t portnumber;
Port(osd::common::uint16_t portnumber);
~Port();
};
class Port8bit : public Port
{
public:
Port8bit(osd::common::uint16_t portnumber);
~Port8bit();
virtual void Write(osd::common::uint8_t data);
virtual osd::common::uint8_t Read();
};
class Port8bitSlow : public Port8bit
{
public:
Port8bitSlow(osd::common::uint16_t portnumber);
~Port8bitSlow();
virtual void Write(osd::common::uint8_t data);
};
class Port16bit : public Port
{
public:
Port16bit(osd::common::uint16_t portnumber);
~Port16bit();
virtual void Write(osd::common::uint16_t data);
virtual osd::common::uint16_t Read();
};
class Port32bit : public Port
{
public:
Port32bit(osd::common::uint32_t portnumber);
~Port32bit();
virtual void Write(osd::common::uint32_t data);
virtual osd::common::uint32_t Read();
};
}
}
#endif<file_sep>#ifndef __OSD__GUI__WINDOW_H
#define __OSD__GUI__WINDOW_H
#include <gui/widget.h>
#include <drivers/mouse.h>
namespace osd
{
namespace gui
{
// this class is just a child of the composite widget
class Window : public osd::gui::CompositeWidget
{
protected:
bool Dragging; // tells us if the window is currently dragging or not
public:
Window(osd::gui::Widget* parent,
osd::common::int32_t x, osd::common::int32_t y, osd::common::int32_t w, osd::common::int32_t h,
osd::common::uint8_t r, osd::common::uint8_t g, osd::common::uint8_t b);
~Window();
void OnMouseDown(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button);
void OnMouseUp(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button);
void OnMouseMove(osd::common::int32_t oldx, osd::common::int32_t oldy, osd::common::int32_t newx, osd::common::int32_t newy);
};
}
}
#endif<file_sep>#include <drivers/mouse.h>
using namespace osd::common;
using namespace osd::drivers;
using namespace osd::hardwarecommunication;
MouseEventHandler :: MouseEventHandler()
{
}
void MouseEventHandler :: OnActivate()
{
}
void MouseEventHandler :: OnMouseDown(uint8_t button)
{
}
void MouseEventHandler :: OnMouseUp(uint8_t button)
{
}
void MouseEventHandler :: OnMouseMove(int x, int y)
{
}
MouseDriver::MouseDriver(InterruptManager* manager, MouseEventHandler* handler)
: InterruptHandler(0x2C, manager),
dataport(0x60), // initializing the dataport and the commandport
commandport(0x64)
{
this -> handler = handler;
}
MouseDriver :: ~MouseDriver() // destructor
{}
void MouseDriver :: Activate() // the mouse driver is activated
{
// initializing the variables
offset = 0;
buttons = 0;
// we are writing and reading in the dataports and the command ports communicate
commandport.Write(0xA8); //activate interrupts
commandport.Write(0x20); //activate interrupts
uint8_t status = (dataport.Read() | 2);
commandport.Write(0x60);
dataport.Write(status);
commandport.Write(0xD4);
dataport.Write(0xF4);
dataport.Read();
}
void printf(char *);
uint32_t MouseDriver::HandleInterrupt(uint32_t esp)
{
uint8_t status = commandport.Read();
if(!(status & 0x20)) // communicating with the stack pointer
return esp;
static int8_t x = 40, y = 12; // basically the cursor
// this will be the positioning of the mouse cursor we are going to use
buffer[offset] = dataport.Read();
if(handler == 0)
return esp;
offset = (offset + 1) % 3;
if(offset == 0)
{
// this is for changing the position of the mosue
if(buffer[1] != 0 || buffer[2] != 0)
handler -> OnMouseMove((int8_t)buffer[1], - ((int8_t)buffer[2]));
// this code if so that when the cursor go over text its color changes
for(uint8_t i = 0; i < 3; i++)
{
if((buffer[0] & (0x01 << i)) != (buttons & (0x01 << i)))
{
// the below is for inverting the color
if(buttons & (0x1 << i))
handler -> OnMouseUp(i+1);
else
{
handler -> OnMouseDown(i+1);
}
}
}
buttons = buffer[0];
}
return esp; // we are returning the stack pointer
}<file_sep>#include <gui/widget.h>
using namespace osd::common;
using namespace osd::gui;
Widget::Widget(Widget* parent, osd::common::int32_t x, osd::common::int32_t y, osd::common::int32_t w, osd::common::int32_t h, osd::common::uint8_t r, osd::common::uint8_t g, osd::common::uint8_t b)
: KeyboardEventHandler()
{
// we will be making windows which are having child windows in there
this -> parent = parent;
this -> x = x;
this -> y = y;
this -> w = w;
this -> h = h;
this -> r = r;
this -> g = g;
this -> b = b;
}
Widget :: ~Widget()
{
}
void Widget ::GetFocus(Widget* widget)
{
if(parent != 0)
parent -> GetFocus(widget);
}
void Widget ::ModelToScreen(osd::common::int32_t &x, osd::common::int32_t &y)
{
if(parent != 0)
parent -> ModelToScreen(x, y);
x += this -> x;
y += this -> y;
}
void Widget ::Draw(GraphicsContext* gc)
{
int X = 0;
int Y = 0;
ModelToScreen(X, Y);
gc -> FillRectangle(X, Y, w, h, r, g, b);
}
void Widget ::OnMouseDown(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button)
{
if(Focussable)
GetFocus(this);
}
void Widget ::OnMouseUp(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button)
{
}
void Widget ::OnMouseMove(osd::common::int32_t oldx, osd::common::int32_t oldy, osd::common::int32_t newx, osd::common::int32_t newy)
{
}
bool Widget::ContainsCoordinate(common::int32_t x, common::int32_t y)
{
return this->x <= x && x < this->x + this->w
&& this->y <= y && y < this->y + this->h;
}
CompositeWidget::CompositeWidget(Widget* parent, osd::common::int32_t x, osd::common::int32_t y, osd::common::int32_t w, osd::common::int32_t h, osd::common::uint8_t r, osd::common::uint8_t g, osd::common::uint8_t b)
: Widget(parent, x,y,w,h, r,g,b)
{
focussedChild = 0;
numChildren = 0;
}
CompositeWidget::~CompositeWidget()
{
}
void CompositeWidget::GetFocus(Widget* widget)
{
this -> focussedChild = widget;
if(parent != 0)
parent -> GetFocus(this);
}
bool CompositeWidget::AddChild(Widget* child)
{
if(numChildren >= 100)
return false;
children[numChildren++] = child;
return true;
}
void CompositeWidget::Draw(osd::common::GraphicsContext* gc)
{
Widget::Draw(gc);
for(int i = numChildren - 1; i >= 0; i--)
children[i] -> Draw(gc);
}
void CompositeWidget::OnMouseDown(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button)
{
for(int i = 0; i < numChildren; i++)
{
if(children[i] -> ContainsCoordinate(x - this -> x, y - this -> y))
{
children[i] -> OnMouseDown(x - this -> x, y - this -> y, button);
break;
}
}
}
void CompositeWidget::OnMouseUp(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t button)
{
for(int i = 0; i < numChildren; i++)
{
if(children[i] -> ContainsCoordinate(x - this -> x, y - this -> y))
{
children[i] -> OnMouseDown(x - this -> x, y - this -> y, button);
break;
}
}
}
void CompositeWidget::OnMouseMove(osd::common::int32_t oldx, osd::common::int32_t oldy, osd::common::int32_t newx, osd::common::int32_t newy)
{
int firstchild = -1;
for(int i = 0; i < numChildren; i++)
{
if(children[i] -> ContainsCoordinate(oldx - this->x, oldy - this->y))
{
children[i] -> OnMouseMove(oldx - this->x, oldy - this->y, newx - this->x, newy - this->y);
break;
}
}
for(int i = 0; i < numChildren; i++)
{
if(children[i] -> ContainsCoordinate(oldx - this->x, oldy - this->y))
{
if(firstchild != i)
children[i] -> OnMouseMove(oldx - this->x, oldy - this->y, newx - this->x, newy - this->y);
break;
}
}
}
void CompositeWidget::OnKeyDown(char str)
{
if(focussedChild != 0)
focussedChild -> OnKeyDown(str);
}
void CompositeWidget::OnKeyUp(char str)
{
if(focussedChild != 0)
focussedChild -> OnKeyUp(str);
}<file_sep>#ifndef OSD__HARDWARECOMMUNICATION__PCI_H
#define OSD__HARDWARECOMMUNICATION__PCI_H
#include <hardwarecommunication/port.h>
#include <common/types.h>
#include <drivers/driver.h>
#include <hardwarecommunication/interrupts.h>
#include <memorymanagement.h>
namespace osd
{
namespace hardwarecommunication
{
enum BaseAddressRegisterType
{
// this is to tell if below two are present for device
MemoryMapping = 0,
InputOutput = 1
};
class BaseAddressRegister
{
public:
bool prefetchable;
osd::common::uint8_t* address;
osd::common::uint32_t size;
BaseAddressRegisterType type;
};
class PeripheralComponentInterconnectDeviceDescriptor
{
// below are the different information that helps us to differentiate between the devices
public:
osd::common::uint32_t portBase;
osd::common::uint32_t interrupt;
osd::common::uint16_t bus; // multible buses
osd::common::uint16_t device; // multiple devices
osd::common::uint16_t function; // multiple functions
// these ids are used to identify the devices
osd::common::uint16_t vendor_id;
osd::common::uint16_t device_id;
osd::common::uint8_t class_id;
osd::common::uint8_t subclass_id;
osd::common::uint8_t interface_id;
osd::common::uint8_t revision;
PeripheralComponentInterconnectDeviceDescriptor(/* args */);
~PeripheralComponentInterconnectDeviceDescriptor();
};
class PeripheralComponentInterconnectController
{
private:
// these are the common ports that are necessary
osd::hardwarecommunication::Port32bit dataPort;
osd::hardwarecommunication::Port32bit commandPort;
public:
PeripheralComponentInterconnectController(/* args */);
~PeripheralComponentInterconnectController();
// we also pass the offset that we want to read
osd::common::uint32_t Read(osd::common::uint16_t bus, osd::common::uint16_t device, osd::common::uint16_t function, osd::common::uint32_t registeroffset);
// extra here is the value that we are going to write
void Write(osd::common::uint16_t bus, osd::common::uint16_t device, osd::common::uint16_t function, osd::common::uint32_t registeroffset, osd::common::int32_t value);
// this boolean is to check if the device has some functions or not
bool DeviceHasFunctions(osd::common::uint16_t bus, osd::common::uint16_t device);
// this functions selects the drivers on the basis of class, sub_class, window, device_id
void SelectDrivers(osd::drivers::DriverManager* driverManager, osd::hardwarecommunication::InterruptManager* interrupts);
// this function is for getting the details of the device such as the functions it is using and all that
PeripheralComponentInterconnectDeviceDescriptor GetDeviceDescriptor(osd::common::uint16_t bus, osd::common::uint16_t device, osd::common::uint16_t function);
// this gives us the address register of the devices
BaseAddressRegister GetBaseAddressRegister(osd::common::uint16_t bus, osd::common::uint16_t device, osd::common::uint16_t function, osd::common::uint16_t bar);
// this is to get the driver for that paricular device
osd::drivers::Driver* GetDriver(PeripheralComponentInterconnectDeviceDescriptor dev, osd::hardwarecommunication::InterruptManager* interrupts);
};
}
}
#endif<file_sep>#ifndef __OSD__DRIVERS__KEYBOARD_H
#define __OSD__DRIVERS__KEYBOARD_H
#include <common/types.h>
#include <hardwarecommunication/interrupts.h>
#include <drivers/driver.h>
#include <hardwarecommunication/port.h>
namespace osd
{
namespace drivers
{
class KeyboardEventHandler
{
public:
KeyboardEventHandler();
// with this handler we can do anything between when the keys are pressed and when
// it is displayed on the screen
virtual void OnKeyDown(char); // this is the method for when key is pressed
virtual void OnKeyUp(char); // this is the method when the key is left after pressing
};
class KeyboardDriver : public osd::hardwarecommunication::InterruptHandler, public Driver
{
osd::hardwarecommunication::Port8bit dataport; // it is for reading the typed key values
osd::hardwarecommunication::Port8bit commandport; // this is for commanding throught the port to the processor what to do
KeyboardEventHandler* handler; // this handler is for handling the keyboard driver
public:
KeyboardDriver(osd::hardwarecommunication::InterruptManager* manager, KeyboardEventHandler* handler);
~KeyboardDriver();
virtual osd::common::uint32_t HandleInterrupt(osd::common::uint32_t esp); // for handling the keyboard interrupts
virtual void Activate(); // this is for activating the keyboard
};
}
}
#endif<file_sep>#ifndef __OSD__DRIVERS__VGA_H
#define __OSD__DRIVERS__VGA_H
#include <common/types.h>
#include <drivers/driver.h>
#include <hardwarecommunication/port.h>
namespace osd
{
namespace drivers
{
class VideoGraphicsArray
{
// below are all the ports that are needed for putting video grahics to our operating system
protected:
osd::hardwarecommunication::Port8bit miscPort; // miscellaneous port
osd::hardwarecommunication::Port8bit crtcIndexPort; // this is the cathode ray tube index port
osd::hardwarecommunication::Port8bit crtcDataPort; // cathode ray tube data port
osd::hardwarecommunication::Port8bit sequenceIndexPort; // this is the sequencing port
osd::hardwarecommunication::Port8bit sequenceDataPort; // this is the sequencing data port
osd::hardwarecommunication::Port8bit graphicsControllerIndexPort; // graphics controller index port
osd::hardwarecommunication::Port8bit graphiceControllerDataPort; // graphics controller data port
osd::hardwarecommunication::Port8bit attributeControllerIndexPort; // attribute controller reader port
osd::hardwarecommunication::Port8bit attributeControllerReadPort; // attribute controller read port
osd::hardwarecommunication::Port8bit attributeControllerWritePort; // attribute controller writer port
osd::hardwarecommunication::Port8bit attributeControllerResetPort; // attribute controller reset port
void WriteRegisters(osd::common::uint8_t* registers);
osd::common::uint8_t* GetFrameBufferSegment();
virtual osd::common::uint8_t GetColorIndex(osd::common::uint8_t r, osd::common::uint8_t g, osd::common::uint8_t b);
public:
VideoGraphicsArray();
~VideoGraphicsArray();
virtual bool SetMode(osd::common::uint32_t width, osd::common::uint32_t height, osd::common::uint32_t colordepth);
virtual bool SupportsMode(osd::common::uint32_t width, osd::common::uint32_t height, osd::common::uint32_t colordepth);
virtual void PutPixel(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t r, osd::common::uint8_t g, osd::common::uint8_t b);
virtual void PutPixel(osd::common::int32_t x, osd::common::int32_t y, osd::common::uint8_t colorIndex);
virtual void FillRectangle(osd::common::uint32_t x, osd::common::uint32_t w, osd::common::uint32_t h, osd::common::uint32_t y, osd::common::uint8_t r, osd::common::uint8_t g, osd::common::uint8_t b);
};
}
}
#endif<file_sep>
#ifndef __MYOS__MULTITASKING_H
#define __MYOS__MULTITASKING_H
#include <common/types.h>
#include <gdt.h>
namespace osd
{
struct CPUState
{
// the cpu is having many different type of registers which is declared below
osd::common::uint32_t eax; // this is the general purpose register
osd::common::uint32_t ebx; // this is the base register
osd::common::uint32_t ecx; // this is the count register
osd::common::uint32_t edx; // this is the data register
osd::common::uint32_t esi; // stack index
osd::common::uint32_t edi; // data index
osd::common::uint32_t ebp; // stack base pointer
/*
// elemets that are pushed in the stack
// these are the things we pushed in interrupt subs
osd::common::uint32_t gs;
osd::common::uint32_t fs;
osd::common::uint32_t es;
osd::common::uint32_t ds;
*/
osd::common::uint32_t error; // this is for error code
osd::common::uint32_t eip; // instruction pointer
osd::common::uint32_t cs; // code segment
osd::common::uint32_t eflags; // different flags
osd::common::uint32_t esp; // stack pointer
osd::common::uint32_t ss; // stack segment
} __attribute__((packed));
class Task
{
// we have a task manager here to divide the tasks
friend class TaskManager;
private:
// we now have our own reserve stack to send some stacks here
osd::common::uint8_t stack[4096]; // 4 KiB
// this is the cpu state so we can send the task here from cpu
CPUState* cpustate;
public:
Task(osd::GlobalDescriptionTable *gdt, void entrypoint());
~Task();
};
class TaskManager
{
private:
Task* tasks[256]; // this is the array task
int numTasks; // contains the number of tasks in the array above
int currentTask; // contains index of the current task
public:
TaskManager();
~TaskManager();
bool AddTask(Task* task); // this is to add task to the array
CPUState* Schedule(CPUState* cpustate);
// we will here use the round robin scheduling
// we have linear stack of task pointers
// we run into a time interrupt and then we keep on
// doing the tasks until it is over
// after that we start over from the top
};
}
#endif<file_sep>#ifndef __OSD__DRIVERS__MOUSE_H
#define __OSD__DRIVERS__MOUSE_H
#include <common/types.h>
#include <hardwarecommunication/interrupts.h>
#include <drivers/driver.h>
#include <hardwarecommunication/port.h>
namespace osd
{
namespace drivers
{
class MouseEventHandler
{
public:
MouseEventHandler(); // this is the mouse event handler
virtual void OnActivate(); // activating the mouse driver
virtual void OnMouseDown(osd::common:: uint8_t button); // when mouse button is clicked
virtual void OnMouseUp(osd::common::uint8_t button); // when mouse button is relaeased
virtual void OnMouseMove(int x, int y); // this is the co-ordinates of the mouse pointer on the screen
};
// this is the driver for the mouse
class MouseDriver : public osd::hardwarecommunication::InterruptHandler, public Driver
{
osd::hardwarecommunication::Port8bit dataport; // taking the interrupt to the port for the mouse
osd::hardwarecommunication::Port8bit commandport; // commanding the processor what to do
osd::common::uint8_t buffer[3]; // transmission of mouse is through these buffers only
osd::common::uint8_t offset;
osd::common::uint8_t buttons; // this is the right click and the left click
MouseEventHandler* handler; // this is for the handling of the mouse
public:
MouseDriver(osd::hardwarecommunication::InterruptManager* manager, MouseEventHandler* handler); // constructor
~MouseDriver(); // destructor
virtual osd::common::uint32_t HandleInterrupt(osd::common::uint32_t esp); // for handling the interrupts of the mouse
virtual void Activate(); // for activating the driver of the mouse
};
}
}
#endif<file_sep>#include <multitasking.h>
using namespace osd;
using namespace osd::common;
Task::Task(osd::GlobalDescriptionTable *gdt, void entrypoint())
{
// this should be the pointer to the start of the reserved stack memory space
// below it is a pointer to the stack
cpustate = (CPUState*)(stack + 4096 - sizeof(CPUState));
// now we are setting the different registers initially
cpustate -> eax = 0;
cpustate -> ebx = 0;
cpustate -> ecx = 0;
cpustate -> edx = 0;
cpustate -> esi = 0;
cpustate -> edi = 0;
cpustate -> ebp = 0;
/*
cpustate -> gs = 0;
cpustate -> fs = 0;
cpustate -> es = 0;
cpustate -> ds = 0;
*/
// cpustate -> error = 0;
// the below is only needed when we are taking many security levels in account
// here we are not doing such thing
// cpustate -> esp = ;
cpustate -> eip = (uint32_t)entrypoint;
// this should always be the code segment selector from the global descriptor table
cpustate -> cs = gdt->CodeSegmentSelector();
// cpustate -> ss = ;
cpustate -> eflags = 0x202;
}
Task::~Task()
{
}
TaskManager::TaskManager()
{
numTasks = 0; // we have no tasks initially
currentTask = -1; // no current tasks given to it initially
}
TaskManager::~TaskManager()
{
}
bool TaskManager::AddTask(Task* task)
{
if(numTasks >= 256)
return false; // we cannot add if the array is full
tasks[numTasks++] = task; // otherwise we add and return true
return true;
}
CPUState* TaskManager::Schedule(CPUState* cpustate)
{
if(numTasks <= 0)
return cpustate; // case if we don't have any task yet
// if we are doing the scheduling then we should update cpu state
if(currentTask >= 0)
tasks[currentTask]->cpustate = cpustate;
// we are doing the round robin
// if the current taks reach the end array the we start another pointer from the beginning
if(++currentTask >= numTasks)
currentTask %= numTasks;
return tasks[currentTask]->cpustate;
}
<file_sep> #include <gui/desktop.h>
using namespace osd;
using namespace osd::common;
using namespace osd::gui;
Desktop::Desktop(osd::common::int32_t w, osd::common::int32_t h, osd::common::uint8_t r, osd::common::uint8_t g, common::uint8_t b)
: CompositeWidget(0,0,0, w,h,r,g,b),
MouseEventHandler()
{
// w is width and h is the height
MouseX = w/2;
MouseY = h/2;
}
Desktop :: ~Desktop()
{
}
void Desktop::Draw(osd::common::GraphicsContext* gc)
{
// this draw is for drawing the desktop
CompositeWidget::Draw(gc);
// here we are drawing the mouse cursor that will
// be shown on the screen
for(int i = 0; i < 4; i++)
{
gc -> PutPixel(MouseX-i, MouseY, 0xFF, 0xFF, 0xFF);
gc -> PutPixel(MouseX+i, MouseY, 0xFF, 0xFF, 0xFF);
gc -> PutPixel(MouseX, MouseY-i, 0xFF, 0xFF, 0xFF);
gc -> PutPixel(MouseX, MouseY+i, 0xFF, 0xFF, 0xFF);
}
}
void Desktop::OnMouseDown(osd::common::uint8_t button)
{
CompositeWidget::OnMouseDown(MouseX, MouseY, button);
// we are accessing the composite widget's event handler
}
void Desktop::OnMouseUp(osd::common::uint8_t button)
{
CompositeWidget::OnMouseUp(MouseX, MouseY, button);
// we are accessing the composite widget's event handler
}
void Desktop::OnMouseMove(int x, int y)
{
x /= 4;
y /= 4;
int32_t newMouseX = MouseX + x;
if(newMouseX < 0) newMouseX = 0; // constraints so cursor don't get outside
if(newMouseX >= w) newMouseX = w - 1;
int32_t newMouseY = MouseY + y;
if(newMouseY < 0) newMouseY = 0; // constraints so that cursor don't get outside
if(newMouseY >= h) newMouseY = h - 1;
CompositeWidget::OnMouseMove(MouseX, MouseY, newMouseX, newMouseY);
MouseX = newMouseX;
MouseY = newMouseY;
}<file_sep>#include <common/types.h>
#include <gdt.h>
#include <hardwarecommunication/interrupts.h>
#include <hardwarecommunication/pci.h>
#include <drivers/driver.h>
#include <drivers/keyboard.h>
#include <drivers/mouse.h>
#include <drivers/vga.h>
#include <gui/desktop.h>
#include <gui/window.h>
#include <multitasking.h>
#include <memorymanagement.h>
// #define GRAPHICSMODE
using namespace osd;
using namespace osd::common;
using namespace osd::drivers;
using namespace osd::hardwarecommunication;
using namespace osd::gui;
// the print fucntion that has been written explicitly
void printf(char *str)
{
// separated this in arrays of unsigned integers
static uint16_t *VideoMemory = (uint16_t *)0xb8000;
static uint8_t x = 0, y = 0;
for (int i = 0; str[i] != '\0'; i++)
{
switch(str[i])
{
case '\n':
y++;
x = 0;
break;
default:
VideoMemory[80 * y + x] = (VideoMemory[80 * y + x] & 0xFF00) | str[i];
x++;
}
if(x >= 80)
{
y++;
x = 0;
}
if(y >= 25)
{
for(y = 0; y < 25; y++)
{
for(x = 0; x < 80; x++)
{
VideoMemory[80*y*x] = (VideoMemory[80*y*x] & 0xFF00) | ' ';
}
}
x = 0;
y = 0;
}
}
}
// hexadecimal print
void printfHex(uint8_t key)
{
char* foo = "00";
char* hex = "0123456789ABCDEF";
foo[0] = hex[(key >> 4) & 0x0F];
foo[1] = hex[key & 0x0F];
printf(foo);
}
// extending the keyboard event handler class
class PrintfKeyboardEventHandler : public KeyboardEventHandler
{
public:
void OnKeyDown(char c)
{
char* foo = " ";
foo[0] = c;
printf(foo);
}
};
// extending the mouse event handler
class MouseToConsole : public MouseEventHandler
{
int8_t x, y;
public:
MouseToConsole()
{
static uint16_t *VideoMemory = (uint16_t *)0xb8000;
x = 40; y = 12;
VideoMemory[80*y+x] = ((VideoMemory[80*y+x] & 0xF000) >> 4) | ((VideoMemory[80*y+x] & 0x0F00) << 4) | (VideoMemory[80*y+x] & 0x00FF);
}
void OnMouseMove(int xoffset, int yoffset)
{
static uint16_t *VideoMemory = (uint16_t *)0xb8000;
VideoMemory[80*y+x] = ((VideoMemory[80*y+x] & 0xF000) >> 4) | ((VideoMemory[80*y+x] & 0x0F00) << 4) | (VideoMemory[80*y+x] & 0x00FF);
x += xoffset;
// we have to put the constraints so that the cursor don't run out of the screen
if(x < 0) x = 0;
if(x >= 80) x = 79;
y += yoffset;
// constraints for the cursor
if(y < 0) y = 0;
if(y >= 25) y = 24;
// we are changing the color bits in the video memory
VideoMemory[80*y+x] = ((VideoMemory[80*y+x] & 0xF000) >> 4) | ((VideoMemory[80*y+x] & 0x0F00) << 4) | (VideoMemory[80*y+x] & 0x00FF);
}
};
void taskA()
{
while (true)
{
printf("A");
}
}
void taskB()
{
while (true)
{
printf("B");
}
}
typedef void (*constructor)();
extern "C" constructor *start_ctors;
extern "C" constructor *end_ctors;
extern "C" void callConstructors()
{
for (constructor *i = start_ctors; i != end_ctors; i++)
(*i)();
}
extern "C" void kernelMain(void *multiboot_structure, uint32_t /*magicnumber*/)
{
// string that will be showm on the screen when OS starts
printf("This operating system is written by Kaustubh.\n");
GlobalDescriptionTable gdt;
// we are allocating the dynamic memory here
uint32_t* memupper = (uint32_t*)(((size_t)multiboot_structure) + 8);
size_t heap = 10*1024*1024;
// we are also subtracting the heap where the memory space is starting
MemoryManager memoryManager(heap, (*memupper)*1024 - heap - 10*1024);
// we are initializing the memory space
// also adding some values to it
// this will print the hex code of the heap allocated
printf("heap: 0x");
printfHex((heap >> 24) & 0xFF);
printfHex((heap >> 16) & 0xFF);
printfHex((heap >> 8) & 0xFF);
printfHex((heap) & 0xFF);
void* allocated = memoryManager.malloc(1024);
// this will print the hex code of the allocated memory space
printf("\nallocated: 0x");
printfHex(((size_t)allocated >> 24) & 0xFF);
printfHex(((size_t)allocated >> 16) & 0xFF);
printfHex(((size_t)allocated >> 8) & 0xFF);
printfHex(((size_t)allocated) & 0xFF);
printf("\n");
// we are declaring the task manager here
TaskManager taskManager;
// here we are making some tasks
// in this A task will be run infinitely and then B task
Task task1(&gdt, taskA);
Task task2(&gdt, taskB);
// we are adding the task in the task manager
taskManager.AddTask(&task1);
taskManager.AddTask(&task2);
// the interrupt handler need to talk to the task manager for the task
InterruptManager interrupts(0x20, &gdt, &taskManager);
//for some status message
printf("Initializing Hardware, Stage 1\n");
#ifdef GRAPHICSMODE
// we are initializing the drivers above the
Desktop desktop(320, 200, 0x00, 0x00, 0xA8);
#endif
DriverManager drvManager;
//PrintfKeyboardEventHandler kbhandler; // initialzing the keyboard handler
// initiating the keyboard driver
//KeyboardDriver keyboard(&interrupts, &kbhandler);
#ifdef GRAPHICSMODE
KeyboardDriver keyboard(&interrupts, &desktop);
#else
PrintfKeyboardEventHandler kbhandler;
KeyboardDriver keyboard(&interrupts, &kbhandler);
#endif
drvManager.AddDriver(&keyboard);
//MouseToConsole mousehandler; // initializing the mouse handler
// inititating the mouse driver
//MouseDriver mouse(&interrupts, &mousehandler);
#ifdef GRAPHICSMODE
MouseDriver mouse(&interrupts, &desktop);
#else
MouseToConsole mousehandler;
MouseDriver mouse(&interrupts, &mousehandler);
#endif
drvManager.AddDriver(&mouse);
// initializing the PCI
PeripheralComponentInterconnectController PCIController;
PCIController.SelectDrivers(&drvManager, &interrupts);
// initilizing the Video Graphics Mode
#ifdef GRAPHICSMODE
VideoGraphicsArray vga;
#endif
// status message
printf("Initializing Hardware, Stage 2\n");
// this will activate all the drivers
drvManager.ActivateAll();
// status message
printf("Initializing Hardware, Stage 3\n");
#ifdef GRAPHICSMODE
// writing the code for making the screen blue
vga.SetMode(320, 200, 8);
// below I have initialized two windows on the desktop
Window win1(&desktop, 10, 10, 20, 20, 0xA8, 0x00, 0x00);
desktop.AddChild(&win1);// also updating the desktop according to window
Window win2(&desktop, 40, 15, 30, 30, 0x00, 0xA8, 0x00);
desktop.AddChild(&win2);// also updating the desktop according to window
#endif
// activating the iDT and PiC
interrupts.Activate();
/*
for(int32_t y = 0; y < 200; y++)
for(int32_t x = 0; x < 320; x++)
vga.PutPixel(x, y, 0x00, 0x00, 0xA8);
*/
while (1)
{
#ifdef GRAPHICSMODE
// we have put it in the loop so that the desktop is updated again and again
desktop.Draw(&vga);
#endif
}
}
<file_sep>#include <hardwarecommunication/pci.h>
using namespace osd::common;
using namespace osd::hardwarecommunication;
PeripheralComponentInterconnectController :: PeripheralComponentInterconnectController()
: dataPort(0xCFC), // dataports and commandports are assigned
commandPort(0xCF8)
{
// these are the specific hex for the port numbers of pci
}
PeripheralComponentInterconnectController :: ~PeripheralComponentInterconnectController()
{}
uint32_t PeripheralComponentInterconnectController :: Read(osd::common::uint16_t bus, osd::common::uint16_t device, osd::common::uint16_t function, osd::common::uint32_t registeroffset)
{
// here we are writing the different bits of this 32 bit number
uint32_t id = 0x1 << 31 | ((bus & 0xFF) << 16) | ((device & 0x1F) << 11) | ((function & 0x07) << 8) | ((registeroffset & 0xFC));
commandPort.Write(id);
uint32_t result = dataPort.Read();
return result >> (8* (registeroffset % 4));
}
void PeripheralComponentInterconnectController :: Write(osd::common::uint16_t bus, osd::common::uint16_t device, osd::common::uint16_t function, osd::common::uint32_t registeroffset, osd::common::int32_t value){
uint32_t id = 0x1 << 31 | ((bus & 0xFF) << 16) | ((device & 0x1F) << 11) | ((function & 0x07) << 8) | ((registeroffset & 0xFC));
commandPort.Write(id);
dataPort.Write(value);
// we have to ask the device if it has functions or not because if there is no function and we still find then it will consume time.
}
bool PeripheralComponentInterconnectController :: DeviceHasFunctions(osd::common::uint16_t bus, osd::common::uint16_t device){
// the seventh bit tells us if the device has fucntions or not
return Read(bus, device, 0, 0x0E) & (1 << 7);
}
// we want to give the driver manager to the PCI controller and have the PCI talk to the driver
// manager and insert the drivers for the device that are connected to the PCI
void printf(char* str);
void printfHex(uint8_t);
void PeripheralComponentInterconnectController :: SelectDrivers(osd::drivers::DriverManager* driverManager, osd::hardwarecommunication::InterruptManager* interrupts)
{
for(int bus = 0; bus < 8; bus++)
{
for(int device = 0; device < 32; device++)
{
int numFunctions = DeviceHasFunctions(bus, device) ? 8 : 1;
for(int function = 0; function < numFunctions; function++)
{
PeripheralComponentInterconnectDeviceDescriptor dev = GetDeviceDescriptor(bus, device, function);
if(dev.vendor_id == 0x0000 || dev.vendor_id == 0xFFFF)
continue;
for(int barNum = 0; barNum < 6; barNum++)
{
// In the GetBaseAddressRegister method, the "address" will be set to the higher bits of the BAR, which in case of the I/O BARs contain the port number.
BaseAddressRegister bar = GetBaseAddressRegister(bus, device, function, barNum);
if(bar.address && (bar.type == InputOutput))
dev.portBase = (uint32_t)bar.address;
osd::drivers::Driver* driver = GetDriver(dev, interrupts);
if(driver != 0)
driverManager -> AddDriver(driver);
}
// these print statements will tell about the information about the different devices available
printf("PCI BUS ");
printfHex(bus & 0xFF);
printf(", DEVICE ");
printfHex(device & 0xFF);
printf(", FUNCTION ");
printfHex(function & 0xFF);
printf(" = VENDOR ");
printfHex((dev.vendor_id & 0xFF00) >> 8);
printfHex(dev.vendor_id & 0xFF);
printf(", DEVICE ");
printfHex((dev.device_id & 0xFF00) >> 8);
printfHex(dev.device_id & 0xFF);
printf("\n");
}
}
}
}
BaseAddressRegister PeripheralComponentInterconnectController::GetBaseAddressRegister(osd::common::uint16_t bus, osd::common::uint16_t device, osd::common::uint16_t function, osd::common::uint16_t bar)
{
BaseAddressRegister result;
uint32_t headertype = Read(bus, device, function, 0x0E) & 0x07F;
int maxBARs = 6 - (4*headertype);
if(bar >= maxBARs)
return result;
uint32_t bar_value = Read(bus, device, function, 0x10 + 4*bar);
result.type = (bar_value & 0x01) ? InputOutput : MemoryMapping;
uint32_t temp;
if(result.type == MemoryMapping)
{
switch ((bar_value >> 1) & 0x3)
{
case 0: // 32 bit
case 1: // 20 bit
case 2: // 64 bit
default:
break;
}
}
else
{
result.address = (uint8_t*)(bar_value & ~0x3);
result.prefetchable = ((bar_value >> 3) & 0x01) == 0x1;
}
return result;
}
osd::drivers::Driver* PeripheralComponentInterconnectController::GetDriver(PeripheralComponentInterconnectDeviceDescriptor dev, osd::hardwarecommunication::InterruptManager* interrupts){
osd::drivers::Driver *driver = 0;
// we will be using it for the instantiation of the devices
switch (dev.vendor_id)
{
case 0x1022: //AMD
switch(dev.device_id)
{
case 0x2000: //am79c973
printf("AMD am79c973 ");
break;
}
break;
case 0x8086: //Intel
break;
}
switch (dev.class_id)
{
case 0x03: // graphics
switch(dev.subclass_id)
{
case 0x00: // VGA
printf("VGA ");
break;
}
break;
}
return 0;
}
PeripheralComponentInterconnectDeviceDescriptor::PeripheralComponentInterconnectDeviceDescriptor(/* args */)
{
}
PeripheralComponentInterconnectDeviceDescriptor::~PeripheralComponentInterconnectDeviceDescriptor()
{
}
PeripheralComponentInterconnectDeviceDescriptor PeripheralComponentInterconnectController ::GetDeviceDescriptor(osd::common::uint16_t bus, osd::common::uint16_t device, osd::common::uint16_t function)
{
PeripheralComponentInterconnectDeviceDescriptor result;
result.bus = bus;
result.device = device;
result.function = function;
result.vendor_id = Read(bus, device, function, 0x00);
result.device_id = Read(bus, device, function, 0x02);
result.class_id = Read(bus, device, function, 0x0b);
result.subclass_id = Read(bus, device, function, 0x0a);
result.interface_id = Read(bus, device, function, 0x09);
result.revision = Read(bus, device, function, 0x08);
result.interrupt = Read(bus, device, function, 0x3c);
return result;
}
|
6146ef5c2cdf31630e966bbd0beb22e192895cd5
|
[
"Markdown",
"C++"
] | 20
|
C++
|
kaustubh0201/OS_PROJECT
|
6802193568da497d83a5194f4040ae106647a487
|
369fd72da8753752002ee5ec5a059d0ecbf170ad
|
refs/heads/main
|
<repo_name>sudhirp93/Employees-Database<file_sep>/classification of employees.sql
SELECT
d.dept_name, ee.gender, dm.emp_no, dm.from_date, dm.to_date, e.calender_year,
CASE
WHEN YEAR(dm.from_date) <= e.calender_year AND YEAR(dm.to_date) >= e.calender_year THEN '1'
ELSE '0'
END AS 'active'
FROM
(SELECT
YEAR(hire_date) AS calender_year
FROM
t_employees
GROUP BY
calender_year) e
CROSS JOIN
t_dept_manager dm
JOIN
t_departments d
ON dm.dept_no = d.dept_no
JOIN
t_employees ee
ON dm.emp_no = ee.emp_no
ORDER BY dm.emp_no, calender_year;
<file_sep>/breakdown_of_employees.sql
use employees_mod;
SELECT
YEAR(de.from_date) as calendar_year, e.gender, COUNT(de.emp_no)
FROM
t_dept_emp de
JOIN
t_employees e
ON
de.emp_no = e.emp_no
GROUP BY
e.gender, calendar_year
HAVING
calendar_year >= '1990'
ORDER BY
calendar_year;<file_sep>/average salary of employees.sql
SELECT
e.gender,
d.dept_name,
ROUND(AVG(s.salary),2) AS salary,
YEAR(s.from_date) AS calender_year
FROM
t_salaries s
JOIN
t_employees e
ON s.emp_no = e.emp_no
JOIN
t_dept_emp de
ON de.emp_no = e.emp_no
JOIN
t_departments d
ON d.dept_no = de.dept_no
GROUP BY
d.dept_name, e.gender, calender_year
HAVING
calender_year <= 2002
ORDER BY
d.dept_name;
|
91f55421110796558adc8e7437eb223544e7fcd8
|
[
"SQL"
] | 3
|
SQL
|
sudhirp93/Employees-Database
|
82c78efc52bc1e5d4c417d6d4c011d2dbebe2515
|
a6d233d9d475ba7bb0360f2f97053f805b496b06
|
refs/heads/master
|
<file_sep>package com.siddhesh.kharchatracker.SQLite;
public interface Constants {
String FOOD = "food";
String TRAVEL = "travel";
String STATIONARY = "stationary";
String OTHER = "other";
String MISC = "miscellaneous";
String ALL = "all";
}
<file_sep>package com.siddhesh.kharchatracker.SQLite;
public class Expense {
private String category;
private String description;
private int amount;
private String day;
private String month;
private String year;
public Expense(String cat , String desc, int amt , String day, String month, String year){
this.category = cat;
this.description = desc;
this.amount = amt;
this.day = day;
this.month = month;
this.year = year;
}
public String getDescription() {
return description;
}
public String getCategory() {
return category;
}
public String getDay() {
return day;
}
public String getMonth() {
return month;
}
public String getYear() {
return year;
}
public int getAmount() {
return amount;
}
}
<file_sep>package com.siddhesh.kharchatracker.SQLite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
public class SQliteDatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "UserExpensesDB";
// Table names in database
private static final String TABLE_NAME = "Expenses";
// column names
private static final String CATEGORY = "category";
private static final String DESCRIPTION = "description";
private static final String AMOUNT = "amount";
private static final String DAY = "day";
private static final String MONTH = "month";
private static final String YEAR = "year";
private Context context;
public SQliteDatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATION_TABLE = "CREATE TABLE Expenses ( "
+ "category TEXT , " + "description TEXT , " + "amount INTEGER, " + "day TEXT, " + "month TEXT, "
+ "year TEXT )";
try {
db.execSQL(CREATION_TABLE);
Toast toast = Toast.makeText(context, "Tables created", Toast.LENGTH_SHORT);
toast.show();
}catch(Exception e){
Toast toast = Toast.makeText(context, "Error in creating table : "+e.toString(), Toast.LENGTH_LONG);
toast.show();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// you can implement here migration process
this.onCreate(db);
}
//-----------------------------------------------------------------------------------------------------
public void addExpense(Expense expense){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CATEGORY, expense.getCategory());
values.put(DESCRIPTION, expense.getDescription());
values.put(AMOUNT, expense.getAmount());
values.put(DAY, expense.getDay());
values.put(MONTH, expense.getMonth());
values.put(YEAR, expense.getYear());
// insert
db.insert(TABLE_NAME,null, values);
db.close();
}
public ArrayList<Expense> getExpenses(String month, String year){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Expense> expenses = new ArrayList<Expense>();
String query;
if(month.equalsIgnoreCase(Constants.ALL) && year.equalsIgnoreCase(Constants.ALL)){
query = "SELECT * FROM " + TABLE_NAME;
}else if(month.equalsIgnoreCase(Constants.ALL) && !year.equalsIgnoreCase(Constants.ALL)){
query = "SELECT * FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year +"' ";
}else if(!month.equalsIgnoreCase(Constants.ALL) && year.equalsIgnoreCase(Constants.ALL)){
query = "SELECT * FROM " + TABLE_NAME + " WHERE "+ MONTH + " = '" + month +"' ";
}else{
query = "SELECT * FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year + "' AND " + MONTH + " = '" + month + "' ";
}
Cursor cursor = db.rawQuery(query, null);
while(cursor.moveToNext()){
String category = cursor.getString(cursor.getColumnIndexOrThrow(CATEGORY));
String description = cursor.getString(cursor.getColumnIndexOrThrow(DESCRIPTION));
int amount = cursor.getInt(cursor.getColumnIndexOrThrow(AMOUNT));
String day = cursor.getString(cursor.getColumnIndexOrThrow(DAY));
String mon = cursor.getString(cursor.getColumnIndexOrThrow(MONTH));
String yer = cursor.getString(cursor.getColumnIndexOrThrow(YEAR));
expenses.add(new Expense(category, description, amount, day, mon, yer));
}
db.close();
return expenses;
}
public Aggregate getTotal(String month, String year){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor;
Aggregate total = new Aggregate();
String query;
//total food expense
query = "SELECT SUM(amount) sum FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year + "' AND " + MONTH + " = '" + month + "' AND " + CATEGORY + " = '" + Constants.FOOD + "'" ;
cursor = db.rawQuery(query , null);
if(cursor.moveToFirst()){
total.setFood(cursor.getInt(0));
}
//total travel expense
query = "SELECT SUM(amount) FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year + "' AND " + MONTH + " = '" + month + "' AND " + CATEGORY + " = '" + Constants.TRAVEL + "'";
cursor = db.rawQuery(query , null);
if(cursor.moveToFirst()){
total.setTravel(cursor.getInt(0));
}
//total stationary expense
query = "SELECT SUM(amount) FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year + "' AND " + MONTH + " = '" + month + "' AND " + CATEGORY + " = '" + Constants.STATIONARY + "'" ;
cursor = db.rawQuery(query , null);
if(cursor.moveToFirst()){
total.setStationary(cursor.getInt(0));
}
//total other expense
query = "SELECT SUM(amount) FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year + "' AND " + MONTH + " = '" + month + "' AND " + CATEGORY + " = '" + Constants.OTHER + "'" ;
cursor = db.rawQuery(query , null);
if(cursor.moveToFirst()){
total.setOther(cursor.getInt(0));
}
return total;
}
public Aggregate getAvg(String month, String year){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor;
Aggregate avg = new Aggregate();
String query;
//total food expense
query = "SELECT AVG(amount) FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year + "' AND " + MONTH + " = '" + month + "' AND " + CATEGORY + " = '" + Constants.FOOD + "'" ;
cursor = db.rawQuery(query , null);
if(cursor.moveToFirst()){
avg.setFood(cursor.getInt(0));
}
//total travel expense
query = "SELECT AVG(amount) FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year + "' AND " + MONTH + " = '" + month + "' AND " + CATEGORY + " = '" + Constants.TRAVEL + "'" ;
cursor = db.rawQuery(query , null);
if(cursor.moveToFirst()){
avg.setTravel(cursor.getInt(0));
}
//total stationary expense
query = "SELECT AVG(amount) FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year + "' AND " + MONTH + " = '" + month + "' AND " + CATEGORY + " = '" + Constants.STATIONARY + "'" ;
cursor = db.rawQuery(query , null);
if(cursor.moveToFirst()){
avg.setStationary(cursor.getInt(0));
}
//total other expense
query = "SELECT AVG(amount) FROM " + TABLE_NAME + " WHERE "+ YEAR + " = '" + year + "' AND " + MONTH + " = '" + month + "' AND " + CATEGORY + " = '" + Constants.OTHER + "'" ;
cursor = db.rawQuery(query , null);
if(cursor.moveToFirst()){
avg.setOther(cursor.getInt(0));
}
return avg;
}
}
|
fae93d125577a629abaf10e505094b2bebd030a8
|
[
"Java"
] | 3
|
Java
|
sidgangan/KharchaTracker
|
91b3791a9344776179cd9a93d4b3af484cdfe527
|
cbe2a9f3763b9558f21cebf135a8bb2cffae65b5
|
refs/heads/master
|
<file_sep><?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.
*/
namespace Controllers;
/**
* Description of Constants
*
* @author yongquizheng
*/
class Constants {
//put your code here
public $business_table="business";
public $state_table="state";
public $deal_table="deal";
public $deal_types_table="deal_types";
public function __construct(){
}
}
<file_sep><?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.
*/
namespace Controllers;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Interop\Container\ContainerInterface as ContainerInterface;
/**
* Description of DealController
*
* @author yongquizheng
*/
class DealController {
//put your code here
protected $container;
public function __construct(ContainerInterface $container) {
$this->container =$container;
}
public function createDeal($request, $response, $args){
$bid = $args['bid'];
$request -> getBody();
// create deal base on business id
}
}
<file_sep><?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 business
*
* @author yongquizheng
*/
namespace Controllers;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Interop\Container\ContainerInterface as ContainerInterface;
class BusinessController {
//put your code here
protected $container;
protected $contstants;
protected $business_table="business";
protected $state_table="state";
protected $deal_table="deal";
public function __construct(ContainerInterface $container) {
$this->container = $container;
$this->contstants = $container['constants'];
}
public function getBusinessBaseOnLocation($request, $response, $args){
$db = $this->container['db'];
$lat = $args['lat'];
$lon = $args['lon'];
$distance = $args['distance'];
$business_table=$this->contstants->business_table;
$state_table=$this->contstants->state_table;
$queryStatement ="SELECT b.* , (((acos(sin(($lat * pi()/180)) * "
. "sin((`latitude` * pi()/180)) + cos(($lat * pi()/180)) * "
. "cos((`latitude` * pi()/180)) * cos((($lon - `longitude` ) * "
. "pi()/180)))) * 180/pi()) * 60 * 1.1515) as distance, s.state_abbr "
. "FROM `$business_table` as b LEFT JOIN `$state_table` as s "
. "ON b.state=s.id HAVING distance <= $distance";
$query =$db->query($queryStatement);
$resp = array();
foreach($query as $row){
$bid = $row['id'];
$deals= $this->getDealsFromBusiness($bid);
array_push($resp, array("address"=>$row['address'],
'dba'=>$row['dba'],
'state'=>$row['state_abbr'],
'zipcode'=>$row['zipcode'],
'address2'=>$row['address2'],
'city'=>$row['city'],
'distance'=> floatval($row['distance']),
'deals'=>$deals));
}
return $response->withJson($resp,200,JSON_UNESCAPED_UNICODE);
}
private function getDealsFromBusiness($id){
$db = $this->container['db'];
$deal_table=$this->contstants->deal_table;
$deal_type_table=$this->contstants->deal_types_table;
$query = $db->query("SELECT * FROM $deal_table as "
. "d LEFT JOIN $deal_type_table as dt ON d.type=dt.id WHERE business_fk=$id ");
$deals = array();
foreach($query as $row){
$expiredTs = $row['expired_time'];
$createdTs = $row['created_time'];
$message = $row['message'];
$deal_type=$row['type_name'];
array_push($deals, array('messsage'=>$message,'deal_type'=>$deal_type,'expiredTimestamp'=>$expiredTs,'createdTimestamp'=>$createdTs));
}
return $deals;
}
}
|
2791aee3a97e0644fb44bd556daa1f517b5c9b13
|
[
"PHP"
] | 3
|
PHP
|
zheng4uga/kudodeal
|
0cc886e636b702e0e1f8ff3e6a5b2d0f2cf064ad
|
f6688ff78c456ed1db1e9a0a63fbcdcf1f4e54f2
|
refs/heads/master
|
<file_sep>const fs=require('fs'); //fs is file system
const http = require('http');
const url = require('url');
const json = fs.readFileSync(`${__dirname}/data/data.json`,'utf-8'); //here we use synchrous version bcoz it happens only once when we start the app
const laptopData = JSON.parse(json); //laptopData is an array of 5 objects from data.json //parse converts a Javascript object Notation(JSON) string into an object
const server = http.createServer((req,res) => { //req ->request res->response
const pathName=url.parse(req.url , true).pathname;
const id = url.parse(req.url, true).query.id; //console log this " url.parse(req.url, true) " there u will see query in that id
//PRODUCTS OVERVIEW
if(pathName === '/products' || pathName === '/'){ //this is routing
res.writeHead(200, { 'Content-type': 'text/html' } ); //here 200 is Requst succesfull code
//res.end('this is a Products page'); //sending response to server
fs.readFile(`${__dirname}/templates/template-overview.html`, 'utf-8' , (err, data) => { //here we pass the filename ie template which we have created
let overviewOutput = data;
fs.readFile(`${__dirname}/templates/templates-card.html`, 'utf-8' , (err, data) => {
const cardsOutput = laptopData.map( el => replaceTemplate(data, el)).join(''); //now this is in form of array so we make it in string by join method
overviewOutput = overviewOutput.replace('{%CARDS%}',cardsOutput);
res.end(overviewOutput);
});
//data contains the data in form of string from template-overview file
});
}
//LAPTOP DETAILS
else if( pathName === '/laptop' && id < laptopData.length){
res.writeHead(200, { 'Content-type': 'text/html' } );
fs.readFile(`${__dirname}/templates/template-laptop.html`, 'utf-8' , (err, data) => {
const laptop = laptopData[id];
const output = replaceTemplate(data,laptop); //this function replaces all placeholder in string with actual laptop data
res.end(output); //and prints this on screen
});
}
//URL NOT FOUND
else {
res.writeHead(404, { 'Content-type': 'text/html' } ); //here 404 is error processing server
res.end('Page not Found');
}
});
server.listen(1337,'127.0.0.1', () => { //to see results go to this link instead of live server
console.log('listening started');
});
function replaceTemplate(orginalHTML,laptop) {
let output = orginalHTML.replace('{%PRODUCTNAME%}',laptop.productName);
output = output.replace('{%IMAGE%}',laptop.image);
output = output.replace('{%CPU%}',laptop.cpu);
output = output.replace('{%RAM%}',laptop.ram);
output = output.replace('{%STORAGE%}',laptop.storage);
output = output.replace('{%SCREEN%}',laptop.screen);
output = output.replace('{%PRICE%}',laptop.price);
output = output.replace('{%DESCRIPTION%}',laptop.description);
output = output.replace('{%ID%}',laptop.id);
return output;
}
|
37de0e31f893677a7172ceb13ecc8d700cf31646
|
[
"JavaScript"
] | 1
|
JavaScript
|
Gaurav-Gaikwad-1/Laptop-Galaxy
|
60041c008bbdb840c3a4045994cef9747193161c
|
8736754b2e0ebf3363d86c0f225f5aa3520c036f
|
refs/heads/master
|
<repo_name>sthdmahoneydad/KnockKnock-WebSite<file_sep>/modules/beacons/server/models/beacon.server.model.js
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Beacon Schema
*/
var BeaconSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Beacon name',
trim: true
},
uuid: {
type: String,
default: '',
required: 'Please fill Beacon UUID',
trim: true
},
major: {
type: Number,
default: '',
required: 'Please fill Beacon major',
trim: true,
min: 0,
max: 65535
},
minor: {
type: Number,
default: '',
required: 'Please fill Beacon minor',
trim: true,
min: 0,
max: 65535
},
signaldistance: {
type: Number,
default: '',
required: 'Please fill Beacon signal distance(# between 55-59) ',
trim: true,
min: 55,
max: 59
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Beacon', BeaconSchema);
<file_sep>/CustomerMovementManager.js
/* CustomerMovementManager.js */
function getCustomerMovements() {
var custMovements = [
{ cx: 600, cy: 500, customerID: 'c00002', firstName:'Jane', lastName:'Doe'},
{ cx: 350, cy: 450, customerID: 'c00002', firstName:'Jane', lastName:'Doe'},
{ cx: 450, cy: 10, customerID: 'c00003', firstName:'Scott', lastName:'Mahoney'},
{ cx: 700, cy: 100, customerID: 'c00003', firstName:'Scott', lastName:'Mahoney'},
{ cx: 400, cy: 400, customerID: 'c00002', firstName:'Jane', lastName:'Doe'},
{ cx: 150, cy: 250, customerID: 'c00001', firstName:'John', lastName:'Doe'},
{ cx: 250, cy: 250, customerID: 'c00001', firstName:'John', lastName:'Doe'},
{ cx: 700, cy: 150, customerID: 'c00003', firstName:'Scott', lastName:'Mahoney'},
{ cx: 350, cy: 325, customerID: 'c00001', firstName:'John', lastName:'Doe'},
{ cx: 500, cy: 450, customerID: 'c00002', firstName:'Jane', lastName:'Doe'},
{ cx: 550, cy: 450, customerID: 'c00002', firstName:'Jane', lastName:'Doe'},
{ cx: 580, cy: 450, customerID: 'c00002', firstName:'Jane', lastName:'Doe'},
{ cx: 700, cy: 350, customerID: 'c00003', firstName:'Scott', lastName:'Mahoney'},
{ cx: 450, cy: -30, customerID: 'c00002', firstName:'Jane', lastName:'Doe'},
{ cx: 750, cy: 400, customerID: 'c00002', firstName:'Jane', lastName:'Doe'},
{ cx: 300, cy: 400, customerID: 'c00001', firstName:'John', lastName:'Doe'},
{ cx: 450, cy: -30, customerID: 'c00001', firstName:'John', lastName:'Doe'},
{ cx: 450, cy: -30, customerID: 'c00003', firstName:'Scott', lastName:'Mahoney'}
]; // should have array of beacon Responses...
return custMovements;
}
function getCustomers(){
var custList=[
{customerID: 'c00001' , cx: 100, cy: 100, cxPrev: 90, cyPrev: 90, firstName:'John', lastName:'Doe',
beaconsInRange: [
{ uuid: "000001", major: 0, minor:0, name :"ibc2", defaultRSSI: 60, lastRSSI: 0 },
{ uuid: "000002", major: 0, minor:0, name :"ibc1", defaultRSSI: 60, lastRSSI: 0 },
{ uuid: "000003", major: 0, minor:0, name :"ibc3", defaultRSSI: 60, lastRSSI: 0 }
],
nearestBeacons: [
{ uuid: "000003", major: 0, minor:0, name :"ibc3", defaultRSSI: 60, lastRSSI: 0 },
{ uuid: "000002", major: 0, minor:0, name :"ibc1", defaultRSSI: 60, lastRSSI: 0 },
{ uuid: "000001", major: 0, minor:0, name :"ibc2", defaultRSSI: 60, lastRSSI: 0 }
],
shoppingExperience:[]
},
{customerID: 'c00002' , cx: 300, cy: 400, cxPrev: 290, cyPrev: 390, firstName:'Jane', lastName:'Doe',
beaconsInRange: [
{ uuid: "000001", major: 0, minor:0, name :"ibc2", defaultRSSI: 60, lastRSSI: 0 },
{ uuid: "000002", major: 0, minor:0, name :"ibc1", defaultRSSI: 60, lastRSSI: 0 },
{ uuid: "000003", major: 0, minor:0, name :"ibc3", defaultRSSI: 60, lastRSSI: 0 }
],
nearestBeacons: [
{ uuid: "000003", major: 0, minor:0, name :"ibc3", defaultRSSI: 60, lastRSSI: 0 },
{ uuid: "000002", major: 0, minor:0, name :"ibc1", defaultRSSI: 60, lastRSSI: 0 },
{ uuid: "000001", major: 0, minor:0, name :"ibc2", defaultRSSI: 60, lastRSSI: 0 }
],
shoppingExperience:[]
}
];
return custList;
}
function processCustomerMovementData() {
var data = getCustomerTrackingData();
applyCustomerMovementDataToActiveShoppingExperiences(data, getMainAreaOfInterest() ) ;
return data;
}
// HACK !!!! UPDATE Movement data
var currentIdx = 0; // used for dummy positional data...
function getCustomerTrackingData(){
var data = custMovementList.slice(currentIdx, currentIdx+1);
if (currentIdx > 3)
{
data = custMovementList.slice(currentIdx-2, currentIdx+1);
}
// used to populate dummy data for movements.
currentIdx ++;
if (currentIdx > custMovementList.length-1) {
currentIdx =0;
}
var clonedArray = JSON.parse(JSON.stringify(data));
return data;
//return clonedArray;
}
//Add Customers to Active Shoppers list getMainAreaOfInterest()
function applyCustomerMovementDataToActiveShoppingExperiences(data, storeArea){
console.log("# active shoppers before movements: " + activeShopperList.length)
var numberCustomersInSet = data== null? 0: data.length;
for (var idx=0; idx < numberCustomersInSet; idx++){
if (!isActiveShopper(data[idx], activeShopperList ) && withinAreaOfInterest(data[idx], storeArea) ) {
data[idx].startTime = new Date();
activeShopperList.push(data[idx]);
}
if (!isActiveShopper(data[idx], activeShopperExperienceList ) && withinAreaOfInterest(data[idx], storeArea) ) {
data[idx].startTime = new Date();
data[idx].shoppingExperience = [];
activeShopperExperienceList.push(data[idx]);
}
handleCustomerMovements(data);
if (isActiveShopper(data[idx], activeShopperList ) && !withinAreaOfInterest(data[idx], storeArea) ) {
data[idx].EndTime = new Date();
// should update DB... with this info.
removeCustomerFromActiveShopperList(data[idx], activeShopperList);
}
if (isActiveShopper(data[idx], activeShopperExperienceList ) && !withinAreaOfInterest(data[idx], storeArea) ) {
data[idx].EndTime = new Date();
// should update DB... with this info.
removeCustomerFromActiveShopperList(data[idx], activeShopperExperienceList);
}
}
console.log("# active shoppers After movements: " + activeShopperList.length)
}
function handleCustomerMovements(customer){
var activeShopper = getActiveShopperExperienceByCustomer(customer);
if (activeShopper == null){
if (withinAreaOfInterest(customer, getMainAreaOfInterest())){
activeShopper = customer;
activeShopperExperienceList.push(customer);
}else{
/// May NEED to update end time...
return;
}
}
activeShopper.cx = customer.cx;
activeShopper.cy = customer.cy;
if (activeShopper.startMovementTime == null){
activeShopper.startMovementTime = new Date();
}
activeShopper.lastMovementTime = new Date();
for (var idx = 0; idx < areasOfInterestList.length; idx++){
if (areasOfInterestList[idx].type == 'store')
continue;
if (withinAreaOfInterest(customer, areasOfInterestList[idx])){
console.log(customer.firstName +' ' + customer.lastName + ' is in area: ' + areasOfInterestList[idx].name );
if (customer.shoppingExperience == null) {
customer.shoppingExperience = [];
}
var shopExpCustomer = getActiveShopperExperienceByCustomer(customer);
if (shopExpCustomer == null){
var area = areasOfInterestList[idx];
area.startTime = new Date();
customer.shoppingExperience.push(area);
activeShopperExperienceList.push(customer);
}else
{
var area = areasOfInterestList[idx];
area.startTime = new Date();
if (! isAreaOfInterestInList(shopExpCustomer.shoppingExperience, areasOfInterestList[idx])) {
shopExpCustomer.shoppingExperience.push(area);
}else{
if (shopExpCustomer.shoppingExperience.length>0 &&
shopExpCustomer.shoppingExperience[shopExpCustomer.shoppingExperience.length-1].areaOfInterestId != areasOfInterestList[idx].areaOfInterestId ){
shopExpCustomer.shoppingExperience[shopExpCustomer.shoppingExperience.length-1].lastMovementTime = new Date();
shopExpCustomer.shoppingExperience.push(area);
}
else{
shopExpCustomer.shoppingExperience[shopExpCustomer.shoppingExperience.length-1].lastMovementTime = new Date();
}
/*
// Update experience....
for (ceIndx = 0; ceIndx < shopExpCustomer.shoppingExperience.length; ceIndx++){
if (shopExpCustomer.shoppingExperience[ceIndx].areaOfInterestId == areasOfInterestList[idx].areaOfInterestId ){
shopExpCustomer.cx = customer.cx;
shopExpCustomer.cy = customer.cy;
shopExpCustomer.shoppingExperience.endTime = new Date();
}
}
*/
}
}
}
}
}
<file_sep>/modules/beacons/server/routes/beacons.server.routes.js
'use strict';
/**
* Module dependencies
*/
var beaconsPolicy = require('../policies/beacons.server.policy'),
beacons = require('../controllers/beacons.server.controller');
module.exports = function(app) {
// Beacons Routes
app.route('/api/beacons').all(beaconsPolicy.isAllowed)
.get(beacons.list)
.post(beacons.create);
app.route('/api/beacons/:beaconId').all(beaconsPolicy.isAllowed)
.get(beacons.read)
.put(beacons.update)
.delete(beacons.delete);
// Finish by binding the Beacon middleware
app.param('beaconId', beacons.beaconByID);
};
<file_sep>/modules/beacons/tests/server/beacon.server.routes.tests.js
'use strict';
var should = require('should'),
request = require('supertest'),
path = require('path'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Beacon = mongoose.model('Beacon'),
express = require(path.resolve('./config/lib/express'));
/**
* Globals
*/
var app,
agent,
credentials,
user,
beacon;
/**
* Beacon routes tests
*/
describe('Beacon CRUD tests', function () {
before(function (done) {
// Get application
app = express.init(mongoose);
agent = request.agent(app);
done();
});
beforeEach(function (done) {
// Create user credentials
credentials = {
username: 'username',
password: '<PASSWORD>'
};
// Create a new user
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: '<EMAIL>',
username: credentials.username,
password: <PASSWORD>,
provider: 'local'
});
// Save a user to the test db and create new Beacon
user.save(function () {
beacon = {
name: 'Beacon name'
};
done();
});
});
it('should be able to save a Beacon if logged in', function (done) {
agent.post('/api/auth/signin')
.send(credentials)
.expect(200)
.end(function (signinErr, signinRes) {
// Handle signin error
if (signinErr) {
return done(signinErr);
}
// Get the userId
var userId = user.id;
// Save a new Beacon
agent.post('/api/beacons')
.send(beacon)
.expect(200)
.end(function (beaconSaveErr, beaconSaveRes) {
// Handle Beacon save error
if (beaconSaveErr) {
return done(beaconSaveErr);
}
// Get a list of Beacons
agent.get('/api/beacons')
.end(function (beaconsGetErr, beaconsGetRes) {
// Handle Beacons save error
if (beaconsGetErr) {
return done(beaconsGetErr);
}
// Get Beacons list
var beacons = beaconsGetRes.body;
// Set assertions
(beacons[0].user._id).should.equal(userId);
(beacons[0].name).should.match('Beacon name');
// Call the assertion callback
done();
});
});
});
});
it('should not be able to save an Beacon if not logged in', function (done) {
agent.post('/api/beacons')
.send(beacon)
.expect(403)
.end(function (beaconSaveErr, beaconSaveRes) {
// Call the assertion callback
done(beaconSaveErr);
});
});
it('should not be able to save an Beacon if no name is provided', function (done) {
// Invalidate name field
beacon.name = '';
agent.post('/api/auth/signin')
.send(credentials)
.expect(200)
.end(function (signinErr, signinRes) {
// Handle signin error
if (signinErr) {
return done(signinErr);
}
// Get the userId
var userId = user.id;
// Save a new Beacon
agent.post('/api/beacons')
.send(beacon)
.expect(400)
.end(function (beaconSaveErr, beaconSaveRes) {
// Set message assertion
(beaconSaveRes.body.message).should.match('Please fill Beacon name');
// Handle Beacon save error
done(beaconSaveErr);
});
});
});
it('should be able to update an Beacon if signed in', function (done) {
agent.post('/api/auth/signin')
.send(credentials)
.expect(200)
.end(function (signinErr, signinRes) {
// Handle signin error
if (signinErr) {
return done(signinErr);
}
// Get the userId
var userId = user.id;
// Save a new Beacon
agent.post('/api/beacons')
.send(beacon)
.expect(200)
.end(function (beaconSaveErr, beaconSaveRes) {
// Handle Beacon save error
if (beaconSaveErr) {
return done(beaconSaveErr);
}
// Update Beacon name
beacon.name = 'WHY YOU GOTTA BE SO MEAN?';
// Update an existing Beacon
agent.put('/api/beacons/' + beaconSaveRes.body._id)
.send(beacon)
.expect(200)
.end(function (beaconUpdateErr, beaconUpdateRes) {
// Handle Beacon update error
if (beaconUpdateErr) {
return done(beaconUpdateErr);
}
// Set assertions
(beaconUpdateRes.body._id).should.equal(beaconSaveRes.body._id);
(beaconUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback
done();
});
});
});
});
it('should be able to get a list of Beacons if not signed in', function (done) {
// Create new Beacon model instance
var beaconObj = new Beacon(beacon);
// Save the beacon
beaconObj.save(function () {
// Request Beacons
request(app).get('/api/beacons')
.end(function (req, res) {
// Set assertion
res.body.should.be.instanceof(Array).and.have.lengthOf(1);
// Call the assertion callback
done();
});
});
});
it('should be able to get a single Beacon if not signed in', function (done) {
// Create new Beacon model instance
var beaconObj = new Beacon(beacon);
// Save the Beacon
beaconObj.save(function () {
request(app).get('/api/beacons/' + beaconObj._id)
.end(function (req, res) {
// Set assertion
res.body.should.be.instanceof(Object).and.have.property('name', beacon.name);
// Call the assertion callback
done();
});
});
});
it('should return proper error for single Beacon with an invalid Id, if not signed in', function (done) {
// test is not a valid mongoose Id
request(app).get('/api/beacons/test')
.end(function (req, res) {
// Set assertion
res.body.should.be.instanceof(Object).and.have.property('message', 'Beacon is invalid');
// Call the assertion callback
done();
});
});
it('should return proper error for single Beacon which doesnt exist, if not signed in', function (done) {
// This is a valid mongoose Id but a non-existent Beacon
request(app).get('/api/beacons/559e9cd815f80b4c256a8f41')
.end(function (req, res) {
// Set assertion
res.body.should.be.instanceof(Object).and.have.property('message', 'No Beacon with that identifier has been found');
// Call the assertion callback
done();
});
});
it('should be able to delete an Beacon if signed in', function (done) {
agent.post('/api/auth/signin')
.send(credentials)
.expect(200)
.end(function (signinErr, signinRes) {
// Handle signin error
if (signinErr) {
return done(signinErr);
}
// Get the userId
var userId = user.id;
// Save a new Beacon
agent.post('/api/beacons')
.send(beacon)
.expect(200)
.end(function (beaconSaveErr, beaconSaveRes) {
// Handle Beacon save error
if (beaconSaveErr) {
return done(beaconSaveErr);
}
// Delete an existing Beacon
agent.delete('/api/beacons/' + beaconSaveRes.body._id)
.send(beacon)
.expect(200)
.end(function (beaconDeleteErr, beaconDeleteRes) {
// Handle beacon error error
if (beaconDeleteErr) {
return done(beaconDeleteErr);
}
// Set assertions
(beaconDeleteRes.body._id).should.equal(beaconSaveRes.body._id);
// Call the assertion callback
done();
});
});
});
});
it('should not be able to delete an Beacon if not signed in', function (done) {
// Set Beacon user
beacon.user = user;
// Create new Beacon model instance
var beaconObj = new Beacon(beacon);
// Save the Beacon
beaconObj.save(function () {
// Try deleting Beacon
request(app).delete('/api/beacons/' + beaconObj._id)
.expect(403)
.end(function (beaconDeleteErr, beaconDeleteRes) {
// Set message assertion
(beaconDeleteRes.body.message).should.match('User is not authorized');
// Handle Beacon error error
done(beaconDeleteErr);
});
});
});
it('should be able to get a single Beacon that has an orphaned user reference', function (done) {
// Create orphan user creds
var _creds = {
username: 'orphan',
password: '<PASSWORD>'
};
// Create orphan user
var _orphan = new User({
firstName: 'Full',
lastName: 'Name',
displayName: '<NAME>',
email: '<EMAIL>',
username: _creds.username,
password: _<PASSWORD>,
provider: 'local'
});
_orphan.save(function (err, orphan) {
// Handle save error
if (err) {
return done(err);
}
agent.post('/api/auth/signin')
.send(_creds)
.expect(200)
.end(function (signinErr, signinRes) {
// Handle signin error
if (signinErr) {
return done(signinErr);
}
// Get the userId
var orphanId = orphan._id;
// Save a new Beacon
agent.post('/api/beacons')
.send(beacon)
.expect(200)
.end(function (beaconSaveErr, beaconSaveRes) {
// Handle Beacon save error
if (beaconSaveErr) {
return done(beaconSaveErr);
}
// Set assertions on new Beacon
(beaconSaveRes.body.name).should.equal(beacon.name);
should.exist(beaconSaveRes.body.user);
should.equal(beaconSaveRes.body.user._id, orphanId);
// force the Beacon to have an orphaned user reference
orphan.remove(function () {
// now signin with valid user
agent.post('/api/auth/signin')
.send(credentials)
.expect(200)
.end(function (err, res) {
// Handle signin error
if (err) {
return done(err);
}
// Get the Beacon
agent.get('/api/beacons/' + beaconSaveRes.body._id)
.expect(200)
.end(function (beaconInfoErr, beaconInfoRes) {
// Handle Beacon error
if (beaconInfoErr) {
return done(beaconInfoErr);
}
// Set assertions
(beaconInfoRes.body._id).should.equal(beaconSaveRes.body._id);
(beaconInfoRes.body.name).should.equal(beacon.name);
should.equal(beaconInfoRes.body.user, undefined);
// Call the assertion callback
done();
});
});
});
});
});
});
});
afterEach(function (done) {
User.remove().exec(function () {
Beacon.remove().exec(done);
});
});
});
<file_sep>/RoomLayoutManager.js
// RoomLayoutManager.js
var areasOfInterestList =getAreasOfInterest();
var physicalObjectList = getPhysicalObjectsForRoom();
var roomDimensions = function() {var dim = { width : 20, height : 10}; return dim; }();
var pxPerFoot = function() {var pixelPerFoot = 50; return pixelPerFoot;}();
var pxBuffer = 200;
var pxOffset = pxBuffer / 2;
function getPhysicalObjectsForRoom() {
var physObjList = [
{ physicalObjectId: 'p00001', name:'Front Door', type: 'wall', shape:'rect', 'x':450, 'y':0, width:100, height:10, excludesOtherObjects:'Y' },
{ physicalObjectId: 'p00002', name:'Windows Phones', type: 'shelf', shape:'rect', 'x':75, 'y':75, width:100, height:150, excludesOtherObjects:'N' },
{ physicalObjectId: 'p00003', name:'Android Phones', type: 'shelf', shape:'rect', 'x':225, 'y':75, width:100, height:150, excludesOtherObjects:'N' },
{ physicalObjectId: 'p00004', name:'iPhones', type: 'shelf', shape:'rect', 'x':375, 'y':75, width:100, height:150, excludesOtherObjects:'N' },
{ physicalObjectId: 'p00005', name:'Phone Accessories', type: 'shelf', shape:'rect', 'x':550, 'y':275, width:100, height:175, excludesOtherObjects:'Y' },
{ physicalObjectId: 'p00010', name:'Car Accessories', type: 'shelf', shape:'rect', 'x':700, 'y':275, width:100, height:175, excludesOtherObjects:'Y' },
{ physicalObjectId: 'p00009', name:'Smart Home Acc', type: 'shelf', shape:'rect', 'x':850, 'y':275, width:100, height:175, excludesOtherObjects:'Y' },
{ physicalObjectId: 'p00006', name:'Windows Tablets', type: 'counter', shape:'circle', 'cx':75, 'cy':400, r:60, excludesOtherObjects:'Y' },
{ physicalObjectId: 'p00007', name:'Samsung Tablets', type: 'counter', shape:'circle', 'cx':225, 'cy':400, r:60, excludesOtherObjects:'Y' },
{ physicalObjectId: 'p00008', name:'iPad Tablets', type: 'counter', shape:'circle', 'cx':375, 'cy':400, r:60, excludesOtherObjects:'Y' },
{ physicalObjectId: 'p00011', name:'Checkout Counter', type: 'counter', shape:'rect', 'x':600, 'y':25, width:300, height:60, excludesOtherObjects:'Y' },
{ physicalObjectId: 'p00012', name:'FIOS TV', type: 'display', shape:'rect', 'x':975, 'y':100, width:25, height:125, excludesOtherObjects:'Y' },
];
return physObjList;
}
function buildRoomDimensions(rm, px){
var layoutDim = {
pixelWidth: rm.width * px,
pixelHeight: rm.height * px,
width: rm.width ,
height: rm.height ,
signalBeacons: [
{ uuid: "000001", major: 0, minor:0, name :"ibc2", defaultRSSI: 60, lastRSSI: 0, cx: rm.width * px / 2 , cy: 0 * px },
{ uuid: "000002", major: 0, minor:0, name :"ibc1", defaultRSSI: 60, lastRSSI: 0, cx: 0 * px, cy: rm.height * px },
{ uuid: "000003", major: 0, minor:0, name :"ibc3", defaultRSSI: 60, lastRSSI: 0, cx: rm.width * px , cy: rm.height * px }
] };
return layoutDim;
}(roomDimensions, pxPerFoot);
function addRoomToSVGContainer(svgContainer, rm, pxBuf){
svgContainer.attr("width", rm.pixelWidth + pxBuf)
svgContainer.attr("height", rm.pixelHeight + pxBuf);
}
function renderFloorLayout ( rm, px) {
var floorLayout = d3.select("svg")
.append("g")
.attr('transform', 'translate(' + px+', '+px+')')
.append('rect')
.attr("width",rm.pixelWidth)
.attr("height",rm.pixelHeight);
d3.select("svg").append('text')
.attr('transform', 'translate(' + px+', '+px+')')
.attr('id', 'rmWdithLabel')
.attr('style', 'font-weight:bold;width: 100px')
.attr('x', (rm.pixelWidth -100 ) /2 + 'px')
.attr('y', - 25 + 'px')
.text( 'Room Width(ft) : ' + rm.width);
d3.select("svg").append('text')
.attr('transform', 'translate(' + px+', '+px+')')
.attr('transform','rotate( -90, ' + 75 + ', ' + ((rm.pixelHeight - 100 ) /2 ) +')')
.attr('id', 'rmHeightLabel')
.attr('style', 'font-weight:bold;width: 100px')
.attr('x', -(rm.pixelHeight /2) + 100 + 'px')
.attr('y', 100 + px + 'px')
.text( 'Room Height(ft) : ' + rm.height);
var areasOfInterestGroup = function() {
var grp = d3.select("svg")
.append('g')
.attr('id', 'areasOfInterestGroup')
.attr('transform', 'translate(' + pxOffset +', '+pxOffset+')')
return grp;
}();
var physicalObjectGroup = function() {
var grp = d3.select("svg")
.append('g')
.attr('id', 'physicalObjectGroup')
.attr('transform', 'translate(' + pxOffset +', '+pxOffset+')')
return grp;
}();
var customersGroup = function() {
var grp = d3.select("svg")
.append('g')
.attr('id', 'customerGroup')
.attr('transform', 'translate(' + pxOffset +', '+pxOffset+')')
return grp;
}();
}
// Render Beacons
function renderBeaconsForLayout(rm, px){
var container = d3.select("svg");
var bg = function(container) {
var grp = container.append('g')
.attr('id','beaconGroup')
.attr('transform', 'translate(' + px+', '+px+')')
return grp;
}(container);
var beaconGroup = bg.selectAll("circle").data(rm.signalBeacons ,
function(d, i ) { return d ? "B-" + d.uuid : this.id });
// Enter
beaconGroup.enter().append('circle')
.attr('cx', function(d){ return d.cx; })
.attr('cy', function(d){ return d.cy; })
.attr('id', function(d) { return "B-" + d.uuid;})
.attr('class', 'beacon')
.attr('test', function(d,i) {
// Enter
pulse( "B-" +d.uuid);
console.log('Initial ENTER -> Beacon ID : B-' + d.uuid + 'updating cx position to: ', d.cx + ' cy position to : ' + d.cy)
});
// Update
beaconGroup.transition().duration(1000)
.attr('cx', function(d){ return d.cx; })
.attr('cy', function(d){ return d.cy; })
.attr('id', function(d) { return "B-" + d.uuid; })
.attr('class', 'beacon')
.attr('test', function(d, i) {
pulse( "B-" +d.uuid);
console.log('update-> Beacon UUID: B-' + d.uuid + 'updating cx position to: ' + d.cx + ' cy position to : ' + d.cy);
});
function pulse(beaconId) {
var bg = d3.select("#beaconGroup");
var circle = bg.select("#" + beaconId);
(function repeat() {
circle = circle.transition()
.duration(2000)
.attr('stroke-width', .25)
.attr("r", 2)
.transition()
.duration(2000)
.attr('stroke-width', 0.1)
.attr("r", 10)
.ease('sine')
.each("end", repeat)
})();
}
/*
* Attach a context menu to a beacon
*/
contextMenuShowing = false;
bg.selectAll("circle").on('click', function (d, i) {
d3.event.preventDefault();
if (contextMenuShowing) {
d3.select('.popup').remove();
} else {
popup = d3.select('.canvas')
.append('div')
.attr('class', 'popup')
.style('left', event.pageX + 'px')
.style('top', event.pageY + 'px');
popup.append('h2').text(d.name);
popup.append('p').text('UUID: ' + d.uuid )
popup.append('p').text('Major: ' + d.major )
popup.append('p').text('Minor: ' + d.minor )
popup.append('p').text('RSSI Strength: ' + d.defaultRSSI)
popup.append('p')
.append('a')
.attr('href','http://www.knockknockretail.com' )
.text(d.name);
}
contextMenuShowing = !contextMenuShowing;
});
}
function renderPhysicalObjectsInLayout(svgContainer, physicalObjectData){
console.log("Rendering Objects in Floor Layout...");
var container = d3.select("#physicalObjectGroup");
var myRectData = physicalObjectData.filter(function(d){return d.shape === 'rect'});
var physicalRectGroup = container.selectAll("rect").data( myRectData,
function(d, i ) { return d ? d.physicalObjectId : this.id })
//.filter(function(d){return d.type === 'rect'})
;
var myCircleData = physicalObjectData.filter(function(d){return d.shape === 'circle'});
var physicalCircleGroup = container.selectAll("circle").data(myCircleData ,
function(d, i ) { return d ? d.physicalObjectId : this.id }) ;
// Enter - create grouping for object/text to show
var physGroup = physicalRectGroup.enter()
.append('g')
.attr('id', function(d) { return "grp-" + d.physicalObjectId;});
physGroup.append('rect')
.attr('id', function(d) { return d.physicalObjectId;})
.attr('class', 'physicalObject')
.attr('test', function(d,i) {
// Enter called 2 times only
console.log('Initial ENTER -> PhysObjectID: ' + d.physicalObjectId + 'updating x position to: ', d.x + ' y position to : ' + d.y)}
)
.attr('x', function(d){ return d.x; })
.attr('y', function(d){ return d.y; })
.attr('height', function(d) { return d.height;})
.attr('width', function(d) { return d.width; });
// need to know length of text use it for calc offset(not just 75px)
physGroup.append('text')
.attr('style', 'font-weight:normal;width: 100px')
.attr('width', function(d) { return 75; })
.attr('x', function(d) { return d.x })
.attr('y', function(d) { return (d.width< 75 && d.height>=75) ?d.y + d.height: d.y })
.attr('transform', function(d){ return (d.width< 75 && d.height>=75) ? 'rotate(270,' + d.x +',' + (parseFloat(d.y) + parseFloat(d.height)) + ')': '' } )
.text( function(d) { return d.name});
// Update
// Not dynamic list, don't think we need update here...
// now Draw Shapes for circles....
physGroup = physicalCircleGroup.enter()
.append('g')
.attr('id', function(d) { return "grp-" + d.physicalObjectId;});
physGroup.append('circle')
.attr('id', function(d) { return d.physicalObjectId;})
.attr('class', 'physicalObject')
.attr('test', function(d,i) {
// Enter called 2 times only
console.log('Initial ENTER -> PhysObjectID: ' + d.physicalObjectId + 'updating x position to: ', d.x + ' y position to : ' + d.y)}
)
//.style("fill", "red")
.attr("r", function(d) { return d.r; })
.attr("cx", function(d) { return d.cx; })
.attr("cy", function(d) { return d.cy; })
// need to know length of text use it for calc offset(not just 75px)
physGroup.append('text')
.attr('style', 'font-weight:normal;width: 100px')
.attr('width', function(d) { return 75; })
.attr('x', function(d) { return d.cx - 75/2 })
.attr('y', function(d) { return d.cy })
.text( function(d) { return d.name})
;
}
function renderAreasOfInterestInLayout(svgContainer, areaOfInterestObjectData){
console.log("Rendering Objects in Floor Layout...");
var container = d3.select("#areasOfInterestGroup");
var myRectData = areaOfInterestObjectData.filter(function(d){return d.shape === 'rect'});
var areaOfInterestRectGroup = container.selectAll("rect").data( myRectData,
function(d, i ) { return d ? d.areaOfInterestId : this.id })
//.filter(function(d){return d.type === 'rect'})
;
var myCircleData = areaOfInterestObjectData.filter(function(d){return d.shape === 'circle'});
var areaOfInterestCircleGroup = container.selectAll("circle").data(myCircleData ,
function(d, i ) { return d ? d.areaOfInterestId : this.id }) ;
// Enter - create grouping for object/text to show
var areaOfInteresetGroup = areaOfInterestRectGroup.enter()
.append('g')
.attr('id', function(d) { return "grp-" + d.areaOfInterestId;});
areaOfInteresetGroup.append('rect')
.attr('id', function(d) { return d.areaOfInterestId;})
.attr('class', 'areaOfInterest')
.attr('test', function(d,i) {
// Enter called 2 times only
console.log('Initial ENTER -> PhysObjectID: ' + d.areaOfInterestId + 'updating x position to: ', d.x + ' y position to : ' + d.y)
}
)
.attr('x', function(d){ return d.x; })
.attr('y', function(d){ return d.y; })
.attr('height', function(d) { return d.height;})
.attr('width', function(d) { return d.width; });
// need to know length of text use it for calc offset(not just 75px)
areaOfInteresetGroup.append('text')
.attr('style', 'font-weight:normal;width: 100px')
.attr('width', function(d) { return 75; })
.attr('x', function(d) { return d.x })
.attr('y', function(d) { return (d.width< 75 && d.height>=75) ?d.y + d.height: d.y })
.attr('transform', function(d){ return (d.width< 75 && d.height>=75) ? 'rotate(270,' + d.x +',' + d.y + d.height + ')': '' } )
.text( function(d) { return d.name});
// Update
// Not dynamic list, don't think we need update here...
// now Draw Shapes for circles....
areaOfInteresetGroup = areaOfInterestCircleGroup.enter()
.append('g')
.attr('id', function(d) { return "grp-" + d.areaOfInterestId;});
areaOfInteresetGroup.append('circle')
.attr('id', function(d) { return d.areaOfInterestId;})
.attr('class', 'areaOfInterest')
.attr('test', function(d,i) {
// Enter called 2 times only
console.log('Initial ENTER -> PhysObjectID: ' + d.areaOfInterestId + 'updating x position to: ', d.x + ' y position to : ' + d.y)}
)
.attr("r", function(d) { return d.r; })
.attr("cx", function(d) { return d.cx; })
.attr("cy", function(d) { return d.cy; })
// need to know length of text use it for calc offset(not just 75px)
areaOfInteresetGroup.append('text')
.attr('style', 'font-weight:normal;width: 100px')
.attr('width', function(d) { return 75; })
.attr('x', function(d) { return d.cx - 75/2 })
.attr('y', function(d) { return d.cy })
.text( function(d) { return d.name})
;
}
//x -> width
// y |
// > height
function renderCustomersInLayout( svg, customerData ) {
console.log("Rendering Customers in Floor Layout...");
var container = d3.select("#customerGroup");
var custGroup = container.selectAll("circle").data(customerData ,
function(d, i ) { return d ? d.customerID : this.id });
// Enter
custGroup.enter().append('circle')
.attr('cx', function(d){ return d.cx; })
.attr('cy', function(d){ return d.cy; })
.attr('id', function(d) { return d.cutomerID;})
.attr('class', 'customer')
.attr('checkForAreasOfInterest', function(d,i) {
console.log('checkForAreasOfInterest - Initial ENTER -> CustID: ' + d.customerID + 'updating cx position to: ', d.cx + ' cy position to : ' + d.cy)
handleCustomerMovements(d);
});
// Update
custGroup.transition().duration(1000)
.attr('cx', function(d){ return d.cx; })
.attr('cy', function(d){ return d.cy; })
.attr('id', function(d) { return d.customerID;})
.attr('class', 'customer')
.attr('test', function(d, i) {
// update every data change
console.log('update-> CustID: ' + d.customerID + 'updating cx position to: ' + d.cx + ' cy position to : ' + d.cy)
});
container.selectAll("circle").on('click', function (d, i) {
d3.event.preventDefault();
if (contextMenuShowing) {
d3.select('.popup').remove();
} else {
popup = d3.select('.canvas')
.append('div')
.attr('class', 'popup')
.style('left', event.pageX + 'px')
.style('top', event.pageY + 'px');
popup.append('h2').text(d.customerID);
popup.append('p').text('Name: ' + d.firstName + ' ' + d.lastName )
popup.append('p').text('cx: ' + d.cx )
popup.append('p').text('cy: ' + d.cy )
popup.append('p')
.append('a')
.attr('href','http://www.knockknockretail.com/customer/' + d.customerID )
.text(d.customerID);
}
contextMenuShowing = !contextMenuShowing;
});
// Remove
custGroup.exit().remove();
}
function getMainAreaOfInterest(){
var storeArea ;
// var extract storeAreaOfInterest
for (var aIdx =0; aIdx< areasOfInterestList.length; aIdx++) {
if (areasOfInterestList[aIdx].type == "store" ) {
storeArea = areasOfInterestList[aIdx];
break;
}
}
return storeArea;
}
function getAreasOfInterest(){
var areasOfInterest = [
{ areaOfInterestId: 'a00000', type:'store', name:'Store Layout', shape:'rect', 'x':0, 'y':0, width:1000, height:500, excludesOtherObjects:'N' },
{ areaOfInterestId: 'a00001', type:'department', name:'SmartPhones Department', shape:'rect', 'x':37, 'y':37, width:475, height:225, excludesOtherObjects:'N' },
{ areaOfInterestId: 'a00002', type:'department', name:'Tablets Department', shape:'rect', 'x':0, 'y':325, width:475, height:150, excludesOtherObjects:'N' },
{ areaOfInterestId: 'a00003', type:'department', name:'Internet/Home', shape:'rect', 'x':825, 'y':100, width:150, height:125, excludesOtherObjects:'N' },
{ areaOfInterestId: 'a00004', type:'department', name:'Gadgets/Accessories', shape:'rect', 'x':525, 'y':250, width:475, height:225, excludesOtherObjects:'N' }
];
return areasOfInterest;
}
function withinAreaOfInterest(customer, areaOfInterest){
var result = false;
if (areaOfInterest.shape == 'circle')
{
var radius = areaOfInterest.r;
var d = Math.pow(radius,2) - ( Math.pow((areaOfInterest.cx - customer.cx), 2) + Math.pow((areaOfInterest.cy - customer.cy), 2) );
if ( d > 0)
result = true;
else if(d==0)
result = true;
else
result = false;
}
else {
var cx = Math.max(Math.min(customer.cx, areaOfInterest.x + areaOfInterest.width ), areaOfInterest.x);
var cy = Math.max(Math.min(customer.cy, areaOfInterest.y + areaOfInterest.height), areaOfInterest.y);
var result = Math.sqrt( (customer.cx-cx)*(customer.cx-cx) + (customer.cy-cy)*(customer.cy-cy) )<= 0;
}
return result;
}
function isAreaOfInterestInList(list, areaOfInterest){
var found = false;
for (var idx =0; idx< list.length; idx++){
if (list[idx].areaOfInterestId == areaOfInterest.areaOfInterestId){
found = true;
break;
}
}
return found;
}
function renderRoomLayout(svgContainerForPage ) {
// determine layout based on customer's / reporting beacons
var rmLayout = buildRoomDimensions(roomDimensions, pxPerFoot);
// Create SVG Container
addRoomToSVGContainer(svgContainerForPage, rmLayout, pxBuffer)
// Render Floor layout as basic rectangle for now
renderFloorLayout( rmLayout, pxOffset);
renderAreasOfInterestInLayout(svgContainerForPage, areasOfInterestList);
renderPhysicalObjectsInLayout(svgContainerForPage, physicalObjectList);
renderBeaconsForLayout(rmLayout, pxOffset);
}
<file_sep>/modules/beacons/client/config/beacons.client.routes.js
(function () {
'use strict';
angular
.module('beacons')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) {
$stateProvider
.state('beacons', {
abstract: true,
url: '/beacons',
template: '<ui-view/>'
})
.state('beacons.list', {
url: '',
templateUrl: 'modules/beacons/client/views/list-beacons.client.view.html',
controller: 'BeaconsListController',
controllerAs: 'vm',
data: {
pageTitle: 'Beacons List'
}
})
.state('beacons.create', {
url: '/create',
templateUrl: 'modules/beacons/client/views/form-beacon.client.view.html',
controller: 'BeaconsController',
controllerAs: 'vm',
resolve: {
beaconResolve: newBeacon
},
data: {
roles: ['user', 'admin'],
pageTitle: 'Beacons Create'
}
})
.state('beacons.edit', {
url: '/:beaconId/edit',
templateUrl: 'modules/beacons/client/views/form-beacon.client.view.html',
controller: 'BeaconsController',
controllerAs: 'vm',
resolve: {
beaconResolve: getBeacon
},
data: {
roles: ['user', 'admin'],
pageTitle: 'Edit Beacon {{ beaconResolve.name }}'
}
})
.state('beacons.view', {
url: '/:beaconId',
templateUrl: 'modules/beacons/client/views/view-beacon.client.view.html',
controller: 'BeaconsController',
controllerAs: 'vm',
resolve: {
beaconResolve: getBeacon
},
data: {
pageTitle: 'Beacon {{ beaconResolve.name }}'
}
});
}
getBeacon.$inject = ['$stateParams', 'BeaconsService'];
function getBeacon($stateParams, BeaconsService) {
return BeaconsService.get({
beaconId: $stateParams.beaconId
}).$promise;
}
newBeacon.$inject = ['BeaconsService'];
function newBeacon(BeaconsService) {
return new BeaconsService();
}
}());
<file_sep>/modules/beacons/client/controllers/beacons.client.controller.js
(function () {
'use strict';
// Beacons controller
angular
.module('beacons')
.controller('BeaconsController', BeaconsController);
BeaconsController.$inject = ['$scope', '$state', '$window', 'Authentication', 'beaconResolve'];
function BeaconsController ($scope, $state, $window, Authentication, beacon) {
var vm = this;
vm.authentication = Authentication;
vm.beacon = beacon;
vm.error = null;
vm.form = {};
vm.remove = remove;
vm.save = save;
// Remove existing Beacon
function remove() {
if ($window.confirm('Are you sure you want to delete this beacon?')) {
vm.beacon.$remove($state.go('beacons.list'));
}
}
// Save Beacon
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.beaconForm');
return false;
}
// TODO: move create/update logic to service
if (vm.beacon._id) {
vm.beacon.$update(successCallback, errorCallback);
} else {
vm.beacon.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('beacons.view', {
beaconId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
}
}());
<file_sep>/d3SVGManager.js
/* d3SVGManager.js */
function renderActiveShopperList(svg){
d3.select("#activeShopperList").append("div").text('Active Shopper List').attr("class", "activeShopperListTitle");
}
function renderActiveShopperExperienceList(svg){
d3.select("#activeShopperExperienceList").append("div").text('Active Shopper Experience List').attr("class", "activeShopperExperienceListTitle");
}
function addSVGContainerToPage(divElementId){
//"MyRoomLayoutPlaceHolder"
var placeHolderElement = d3.select("#" + divElementId)
var svg = d3.select("#" + divElementId)
.append("div")
.attr("id", "svgWrapperDiv")
.attr("width", "1000px")
.append("div")
.attr("class", "canvas")
.attr("width", "100%")
.append("svg")
.attr("id", "svgElem")
d3.select("#svgWrapperDiv").append("div")
.append("ul")
.attr("class", "activeShopperList")
.attr('id', 'activeShopperList');
d3.select("#svgWrapperDiv").append("div")
.append("ul")
.attr("class", "activeShopperExperienceList")
.attr('id', 'activeShopperExperienceList');
return svg;
}
function getSVGContainer(divElementId){
//"MyRoomLayoutPlaceHolder"
var svg = d3.select("#svgElem");
if (svg == null || svg[0][0] == null){
svg = addSVGContainerToPage(divElementId);
}
return svg;
}
//x -> width
// y |
// > height
function trackCustomerShoppingExperience( svg, customerDataSet, areasOfInterest ) {
console.log("Rendering Active Shopper List");
var activeShopperContainer = d3.select("#activeShopperList");
var activeShopperGroup = activeShopperContainer.selectAll("li").data(customerDataSet,
function(d, i ) { return d ? d.customerID : this.id });
var storeArea = getMainAreaOfInterest();
// update function to add shoppers to global list for experiences....
activeShopperGroup.attr('test', function(d,i) {
var myNode = activeShopperContainer.selectAll("li").data(customerDataSet, function(d, i ) { return d ? d.customerID : this.id })
myNode.text(function(d){return d.lastName +', ' + d.firstName + ' ' + d.startMovementTime.toTimeString().split(' ')[0] + ' - ' + d.lastMovementTime.toTimeString().split(' ')[0] })
});
// Enter
activeShopperGroup.enter().append('li')
.attr('id', function(d){ return 'activeShopperId-' + d.customerID})
.attr('class', 'activeShopper')
.text(function(d){return d.lastName +', ' + d.firstName})
.attr('test', function(d,i) {
});
// Remove
activeShopperGroup.exit().remove()
.attr('test', function(d,i) {
console.log(d.lastName +', ' + d.firstName + ' has left the store');
activeShopperList = removeCustomerFromActiveShopperList(d, activeShopperList);
});
}
//x -> width
// y |
// > height
function trackCustomerShoppingExperiences( svg, customerDataSet, areasOfInterest ) {
console.log("Rendering Active Shopper Experience List");
var activeShopperContainer = d3.select("#activeShopperExperienceList");
var activeShopperExperienceGroup = activeShopperContainer.selectAll("li").data(customerDataSet,
function(d, i ) { return d ? d.customerID : this.id });
// update function to add shoppers to global list for experiences....
// Enter
activeShopperExperienceGroup.enter().append('li')
.attr('id', function(d){ return 'activeShopperExperienceGroupId-' + d.customerID})
.attr('class', 'activeShopperExperience')
.text(function(d){return d.lastName +', ' + d.firstName})
.append('ul')
.attr('id', function(d){ return 'ul-activeShopperExperienceGroupId-' + d.customerID})
.attr('test', function(d,i) {
var experienceContainer = d3.select('#ul-activeShopperExperienceGroupId-' + d.customerID);
//experienceContainer.append('ul')
console.log('# of experiences is: ' + d.shoppingExperience.length );
var experienceContainerGroup = experienceContainer.selectAll("li").data(d.shoppingExperience,
function(d, i ) { return d ? d.areaOfInterestId : this.id });
experienceContainerGroup.enter().append('li')
.attr('id', function(da){
console.log('areaOfInterestId: ' + da.areaOfInterestId);
return 'li-' + d.customerID + '-areaOfInterestId-' + da.areaOfInterestId })
.text(function(d){return d.name});
} );
// Updates
activeShopperExperienceGroup
.attr('test', function(d,i) {
var experienceContainer = d3.select('#ul-activeShopperExperienceGroupId-' + d.customerID);
//experienceContainer.append('ul')
var experienceContainerGroup = experienceContainer.selectAll("li").data(d.shoppingExperience,
function(d2, i ) {
console.log('areaOfInterestId: ' + d2.areaOfInterestId);
return d2 ? 'li-' + d.customerID + '-areaOfInterestId-' + d2.areaOfInterestId : this.id });
experienceContainerGroup.enter().append('li')
.attr('id', function(da){ return 'li-' + d.customerID + '-areaOfInterestId-' + da.areaOfInterestId })
.text(function(d){return d.name});
} );
// Remove
/*
activeShopperExperienceGroup.exit().remove()
.attr('test', function(d,i) {
console.log('No longer in area ' + d.name );
// activeShopperList = removeCustomerFromActiveShopperList(d, activeShopperList);
});
*/
}
function trackCustomersInLayout(svgContainer, data, areas){
renderCustomersInLayout(svgContainer, data );
}
|
5fbb524d8f4b3d928db81ea89b1c167af270f29f
|
[
"JavaScript"
] | 8
|
JavaScript
|
sthdmahoneydad/KnockKnock-WebSite
|
d10dd708836f85a972573a05a9790f4f83fad1f1
|
7dadc91af8c12f9003aa2fd05e1e3f502bb1a1df
|
refs/heads/master
|
<repo_name>leckzilla/Hack-From-Home<file_sep>/README.md
# Ani-Mate
## Motivation
Ani-Mate is a virtual pet designed with self care in mind. Currently large parts of the world are experiencing lockdown and social distancing due to the COVID-19 pandemic and a lot of people will feel particularly distressed and those with existing mental health issues may be struggling to adjust. Our team wanted to create something to help combat depression and anxiety for what will be for many a traumatic time.
## Overview
Ani is your new companion, and encourages the user to exercise self care by reminding them to eat, wash, exercise as well as asking them how they are doing.
There are three targets in the form of "HP bars" representing health (exercise, grooming), hunger (eating) and happiness (general feeling) and the user can increase these by confirming if they have done those things with Ani. You take a shower, Ani grooms. You eat, so does Ani!
Importantly there's no penalisation for not doing those tasks as we felt this would not incentivise the user to keep on engaging with Ani, but the user can defer things if they want for her to ask later.
If the user hasn't interacted for some time Ani sends a push notification to gently ask if they're okay? We'd also like to include something whereby if the user is not positively engaging to suggest ways they can reach out and get help (e.g. call a friend or family member, or any other form of support including mental health services).
## Tech Used
React Native
## Installation
Git clone the repo and npm i to install dependencies. Npm start to run the App.
## Built by
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
As part of the Code First Girls Hack from Home 2020
<file_sep>/Components/Info/index.js
import React, { useState } from "react";
import { Button, Modal } from "react-bootstrap";
import { Image } from "react-native";
import i from "./icon.svg";
function InfoIcon() {
const [show, setShow] = useState(false);
return (
<>
<Image
source={i}
style={{ width: 30, height: 30, marginTop: -70, marginLeft: 200 }}
onClick={() => setShow(true)}
/>
<Modal
size="lg"
show={show}
onHide={() => setShow(false)}
aria-labelledby="lg"
>
<Modal.Header closeButton>
<Modal.Title id="lgModal">Welcome to AniMate!</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
Ani is your own virtual pet and companion designed to take care of
you. With your Ani you can do daily activities including eating
meals, having a wash and doing exercise - and with Ani's
company, you will never feel lonely again. As a caring empathic companion, Ani will also ask you
about your overall feeling and happiness each day.
</p>
<p>
<strong>
If you eat, so does Ani. If you are happy, so is Ani!
</strong>
</p>
<p>
<strong>Features:</strong>
</p>
<p>
The health bar tracks daily exercise, sleep, self-care and showers.{" "}
</p>
<p>
The hunger bar tracks the number of meals you've had in a day. It
also auto updates the health bar for every meal you've had.
</p>
<p>
The happiness bar tracks if you've done an activity you really
enjoy. It also increases every time you caress Ani.{" "}
</p>
</Modal.Body>
</Modal>
</>
);
}
export default InfoIcon;
|
4c7ae8e816e1a7a108c074f74e34e5891cff2fa1
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
leckzilla/Hack-From-Home
|
2ac6dd56932e1fce6676ad547fab1e18f8466d5a
|
49330f41220d47b1e0a77a48e62b2108130731fc
|
refs/heads/master
|
<file_sep>// rf95_client.pde
#include <SPI.h>
#include <RH_RF95.h>
#include<DFRobotHighTemperatureSensor.h>
#include "LowPower.h"
const float voltageRef = 5.000; //Set reference voltage,you need test your IOREF voltage.
//const float voltageRef = 3.300;
int HighTemperaturePin = A1; //Setting pin
DFRobotHighTemperature PT100 = DFRobotHighTemperature(voltageRef); //Define an PT100 object
RH_RF95 rf95;
int led = 8;
int state = 0;
int rssimax;
int SoLanNhanRssiTinHieuThap = 0;
uint8_t id[] = "005";
uint8_t idnodecon[30][4];
uint8_t idnodecha[3];
int dem = 0;
int solangui = 0;
int solannhan = 0;
unsigned long time = 0;
unsigned long time1 = 0;
unsigned long time2 = 0;
unsigned long time3 = 0;
unsigned long time4 = 0;
int idgateway;
int bac;
int idcha;
int idnode;
int sonodecon = 1;
void setup()
{
Serial.begin(9600);
if (!rf95.init())
Serial.println("init failed");
// khoi tao ban dau id
for (int i = 0; i <= 29; i++)
{
for (int j = 0; j <= 3; j++)
{
idnodecon[i][j] = '0';
}
}
}
void loop()
{
if (state == 0)
{
ketnoi();
}
else if (state == 1)
{
ketnoimuc1();
}
else if (state == 2)
{
ketnoimuc2();
}
else if (state == 3)
{
nodetrunggian();
}
else
{
Serial.println("the end");
}
}
void ketnoi()
{
if (millis() - time1 > 10000)
{
time1 = millis();
}
else if (millis() - time1 == 10000)
{
Serial.println("gui tin hieu yeu cau ket noi voi node cha");
// Send a message to rf95_server
uint8_t data[7] = "kn0"; //kn yeu cau ket noi
data[3] = id[0];
data[4] = id[1];
data[5] = id[2];
rf95.send(data, sizeof(data));
rf95.waitPacketSent();
time1 = millis();
}
if (rf95.available())
{
// Should be a message for us now
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);
if (rf95.recv(buf, &len))
{
digitalWrite(led, HIGH);
Serial.print("tin hieu nhan duoc: ");
Serial.println((char*)buf);
uint8_t* a = (uint8_t*)buf;
//for (int i = 0; i < 15; i++)
//{
// Serial.print(a[i]);
// Serial.print(" ");
//}
Serial.println(" ");
Serial.print("RSSI: ");
int rssi = rf95.lastRssi();
Serial.println(rssi);
if (a[0] == 'k' && a[1] == 't' && a[2] == '1' && a[6] == id[0] && a[7] == id[1] && a[8] == id[2]) // ket noi tin hieu muc cao
{
Serial.println("thuc hien ket noi muc 1");
delay(700);
kt(a);
state = 1;
}
else if (a[0] == 'k' && a[1] == 't' && a[2] == '2' && a[6] == id[0] && a[7] == id[1] && a[8] == id[2]) //ket noi tin hieu muc thap
{
Serial.println("thuc hien ket noi muc 2");
delay(700);
kt(a);
state = 2;
}
else if (a[0] == 'k' && a[1] == 't' && a[2] == '3' && a[6] == id[0] && a[7] == id[1] && a[8] == id[2]) //ket noi tin hieu
{
if (rssi > -52 || SoLanNhanRssiTinHieuThap > 10)
{
Serial.println("thuc hien ket noi muc 3");
delay(700);
kt(a);
delay(700);
state = 3;
}
else {
SoLanNhanRssiTinHieuThap = SoLanNhanRssiTinHieuThap + 1;
Serial.print("so lan dem: ");
Serial.println(SoLanNhanRssiTinHieuThap);
}
}
digitalWrite(led, LOW);
}
else
{
Serial.println("recv failed");
}
}
}
void ketnoimuc1()
{
if (rf95.available())
{
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);
if (rf95.recv(buf, &len))
{
digitalWrite(led, HIGH);
Serial.print("tin hieu gui den: ");
Serial.println((char*)buf);
uint8_t* a = (uint8_t*)buf;
Serial.print("RSSI : ");
int rssi = rf95.lastRssi();
Serial.println(rssi);
if (a[0] == 'k' && a[1] == 'n' && a[2] == '0' && rssi > -52)
{
Serial.println("node con co the ket noi voi tin hieu muc cao");
uint8_t data[30] = "kt1"; //kt1 la cho ket noi voi cac node co tin hieu muc cao
kn0(data, a);
digitalWrite(led, LOW);
}
else if (a[0] == 't' && a[1] == 'c' && a[2] == '0' && a[3] == id[0] && a[4] == id[1] && a[5] == id[2])
{
delay(600);
tc0(a);
}
else if (a[0] == 't' && a[1] == 'c' && a[2] == '1' && a[3] == id[0] && a[4] == id[1] && a[5] == id[2])
{
delay(600);
tc1(a);
}
else if (a[0] == 'k' && a[1] == 't' && a[2] == '2' && a[3] == idnodecha[0] && a[4] == idnodecha[1] && a[5] == idnodecha[2])
{
state = 2;
Serial.println("thuc hien ket noi buc 2");
}
}
else
{
Serial.println("recv failed");
}
}
}
void ketnoimuc2()
{
if (millis() - time1 > 15000)
{
time1 = millis();
}
else if (millis() - time1 == 15000)
{
Serial.println("gui du lieu yeu cau node con ket noi muc 2");
uint8_t data[7] = "kt2"; //kt2 la cho ket noi voi cac node co tin hieu muc thap
data[3] = id[0];
data[4] = id[1];
data[5] = id[2];
rf95.send(data, sizeof(data));
rf95.waitPacketSent();
time1 = millis();
}
if (rf95.available())
{
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);
if (rf95.recv(buf, &len))
{
digitalWrite(led, HIGH);
Serial.print("tin hieu gui den: ");
Serial.println((char*)buf);
uint8_t* a = (uint8_t*)buf;
Serial.print("RSSI: ");
int rssi = rf95.lastRssi();
Serial.println(rssi);
if (a[0] == 'k' && a[1] == 'n' && a[2] == '0' && rssi < -52)
{
Serial.println("thuc hien ket noi muc 2");
Serial.println("node con co the ket noi voi tin hieu muc thap");
uint8_t data[30] = "kt2"; //kt2 la cho ket noi voi cac node co tin hieu muc thap
kn0(data, a);
digitalWrite(led, LOW);
}
else if (a[0] == 't' && a[1] == 'c' && a[2] == '0' && a[3] == id[0] && a[4] == id[1] && a[5] == id[2])
{
tc0(a);
}
else if (a[0] == 't' && a[1] == 'c' && a[2] == '1' && a[3] == id[0] && a[4] == id[1] && a[5] == id[2])
{
tc1(a);
}
else if (a[0] == 'k' && a[1] == 'g' && a[2] == '0' && a[3] == idnodecha[0] && a[4] == idnodecha[1] && a[5] == idnodecha[2])
{
state = 3;
}
}
else
{
Serial.println("recv failed");
}
}
}
void nodetrunggian()
{
if (dem <= 1)
{
if (millis() - time3 > 10000)
{
time3 = millis();
}
else if (millis() - time3 == 10000)
{
Serial.println("gui du lieu yeu cau node con gui du lieu");
// Send a message to rf95_server
uint8_t data[7] = "kg0"; // kg0 yeu cau node con bat dau gui du lieu len node cha
data[3] = id[0];
data[4] = id[1];
data[5] = id[2];
rf95.send(data, sizeof(data));
rf95.waitPacketSent();
time3 = millis();
dem = dem + 1;
}
}
///chuong trinh gui du lieu do duoc cua node
if (millis() - time4 > 15000)
{
time4 = millis();
}
else if (millis() - time4 == 15000)
{
Serial.println("gui du lieu do duoc");
int temperature = PT100.readTemperature(HighTemperaturePin); //Get temperature
char nhietdo[5];
itoa(temperature, nhietdo, 10);
Serial.print("temperature1: ");
Serial.print(temperature);
Serial.println(" ^C");
// Send a message to rf95_server
uint8_t data[15] = "kg1"; //kg1 thuc hien gui du lieu len node cha
data[3] = idnodecha[0]; //data[3] -> data[4] dia chi node cha
data[4] = idnodecha[1];
data[5] = idnodecha[2];
data[6] = id[0]; //data[6]->data[8] dia chia node con
data[7] = id[1];
data[8] = id[2];
data[9] = id[0]; //data[9]->data[11] dia chi node gui du lieu ban dau
data[10] = id[1];
data[11] = id[2];
// data[12] = (uint8_t)(temperature);
//data[12] = nhietdo[0];
//data[13] = nhietdo[1];
data[12] = '2';
data[13] = '7';
Serial.print("data: ");
Serial.println(sizeof(data));
Serial.println((char*)data);
delay(600);
rf95.send(data, sizeof(data));
rf95.waitPacketSent();
time4 = millis();
solangui = solangui + 1;
Serial.print("so lan gui: ");
Serial.println(solangui);
}
///////////////////////////////////////////////
/// chuong trinh gui du lieu tu node con
if (rf95.available())
{
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);
if (rf95.recv(buf, &len))
{
digitalWrite(led, HIGH);
Serial.print("tin hieu gui den: ");
Serial.println((char*)buf);
uint8_t* a = (uint8_t*)buf;
if (a[0] == 'k' && a[1] == 'g' && a[2] == '1')
{
Serial.print(a[12]);
Serial.println(" ^C");
for (int i = 0; i <= 29; i++)
{
if (idnodecon[i][0] == '1')
{
if (a[3] == id[0] && a[4] == id[1] && a[5] == id[2] && a[6] == (idnodecon[i][1]) && a[7] == (idnodecon[i][2]) && a[8] == (idnodecon[i][3]))
{
uint8_t data[15] = "kg1"; //kg1 thuc hien gui du lieu len node cha
data[3] = idnodecha[0];
data[4] = idnodecha[1];
data[5] = idnodecha[2];
data[6] = id[0];
data[7] = id[1];
data[8] = id[2];
data[9] = a[9];
data[10] = a[10];
data[11] = a[11];
data[12] = a[12];
data[13] = a[13];
Serial.print("gui du lieu len node cha: ");
Serial.println((char*)data);
delay(700);
rf95.send(data, sizeof(data));
rf95.waitPacketSent();
solangui = solangui + 1;
Serial.print("so lan gui: ");
Serial.println(solangui);
uint8_t data1[10] = "dn1"; //dn1 gui hieu phan roi da nhan cho node con
data1[3] = id[0];
data1[4] = id[1];
data1[5] = id[2];
data1[6] = a[6];
data1[7] = a[7];
data1[8] = a[8];
delay(700);
rf95.send(data1, sizeof(data1));
rf95.waitPacketSent();
i = 101;
}
}
}
}
else if (a[0] == 'k' && a[1] == 'n' && a[2] == '0')
{
Serial.println("thuc hien ket noi kn0 ");
uint8_t data[30] = "kt3"; //kt3 cho ket noi voi cac node
kn0(data, a);
digitalWrite(led, LOW);
Serial.print("du lieu truyen di: ");
Serial.println((char*)data);
}
else if (a[0] == 't' && a[1] == 'c' && a[2] == '0' && a[3] == id[0] && a[4] == id[1] && a[5] == id[2])
{
tc0(a);
}
else if (a[0] == 't' && a[1] == 'c' && a[2] == '1' && a[3] == id[0] && a[4] == id[1] && a[5] == id[2])
{
tc1(a);
}
else if (a[0] == 'd' && a[1] == 'n' && a[2] == '1' && a[3] == idnodecha[0] && a[4] == idnodecha[1] && a[5] == idnodecha[2] && a[6] == id[0] && a[7] == id[1] && a[8] == id[2])
{
solannhan = solannhan + 1;
Serial.print("so lan nhan: ");
Serial.println(solannhan);
}
else if (a[0] == 'n' && a[1] == 'g' && a[2] == 'u' && a[3] == idnodecha[0] && a[4] == idnodecha[1] && a[5] == idnodecha[2])
{
Serial.println("thuc hien ngu");
delay(10000);
solangui = 0;
solannhan = 0;
Serial.println("thuc day");
nodetrunggian();
}
digitalWrite(led, LOW);
}
else
{
Serial.println("recv failed");
}
}
if (solangui == 10)
{
if (solangui - solannhan < 5)
{
solangui = 0;
solannhan = -1;
}
else
{
state = 0;
idnodecha[0] = '0';
idnodecha[1] = '0';
idnodecha[2] = '0';
solangui = 0;
solannhan = 0;
}
}
}
void kt(uint8_t a[])
{
idnodecha[0] = a[3];
idnodecha[1] = a[4];
idnodecha[2] = a[5];
idgateway = (int)a[9];
bac = (int)a[10] + 1;
idcha = (int)a[11];
idnode = (int)a[12];
uint8_t data[17] = "tc0"; //tc0 chap nhan ket noi
data[3] = a[3];
data[4] = a[4];
data[5] = a[5];
data[6] = id[0];
data[7] = id[1];
data[8] = id[2];
data[9] = (uint8_t)idgateway;
data[10] = (uint8_t)bac;
data[11] = (uint8_t)idcha;
data[12] = (uint8_t)idnode;
data[13] = id[0];
data[14] = id[1];
data[15] = id[2];
rf95.send(data, sizeof(data));
rf95.waitPacketSent();
Serial.println((char*)(data));
Serial.println("Sent kt");
}
void kn0(uint8_t data[], uint8_t a[])
{
uint8_t data1[14];
data1[0] = data[0];
data1[1] = data[1];
data1[2] = data[2];
data1[3] = id[0];
data1[4] = id[1];
data1[5] = id[2];
data1[6] = a[3];
data1[7] = a[4];
data1[8] = a[5];
data1[9] = (uint8_t)idgateway;
data1[10] = (uint8_t)bac;
data1[11] = (uint8_t)idnode;
data1[12] = (uint8_t)sonodecon;
rf95.send(data1, sizeof(data1));
rf95.waitPacketSent();
Serial.println("Sent a reply");
}
void tc0(uint8_t a[])
{
for (int i = 0; i <= 29; i++)
{
if (idnodecon[i][0] == '0')
{
idnodecon[i][0] = '1';
idnodecon[i][1] = a[6];
idnodecon[i][2] = a[7];
idnodecon[i][3] = a[8];
Serial.println("luu id node con");
sonodecon = sonodecon + 1;
uint8_t data[17] = "tc1";
data[3] = idnodecha[0]; //data[3] -> data[4] dia chi node cha
data[4] = idnodecha[1];
data[5] = idnodecha[2];
data[6] = id[0]; //data[6]->data[8] dia chia node con
data[7] = id[1];
data[8] = id[2];
//for (int i = 9; i <= 15; i++)
//{
// data[i] = a[i];
//}
data[9] = a[6];
data[10] = a[7];
data[11] = a[8];
data[12] = id[0];
data[13] = id[1];
data[14] = id[2];
delay(650);
rf95.send(data, sizeof(data));
rf95.waitPacketSent();
Serial.print("du lieu da gui: ");
Serial.println((char*)(data));
i = 101;
}
}
}
void tc1(uint8_t a[])
{
uint8_t data[17];
data[0] = a[0];
data[1] = a[1];
data[2] = a[2];
data[3] = idnodecha[0];
data[4] = idnodecha[1];
data[5] = idnodecha[2];
data[6] = id[0];
data[7] = id[1];
data[8] = id[2];
for (int i = 9; i <= 15; i++)
{
data[i] = a[i];
}
delay(400);
rf95.send(data, sizeof(data));
rf95.waitPacketSent();
}
|
00dbee4efce5c6c2208a564bd57841a8964bd28d
|
[
"C++"
] | 1
|
C++
|
phuongnam0907/SourceArduino
|
73e06a2ed90ca1f78462e779191f12bfa516e0fc
|
b15de3ad5f7751bc4c391bc17aef74b52ccf2194
|
refs/heads/master
|
<repo_name>piotrrepetowski/service-double<file_sep>/spec/ServiceDouble/FacadeSpec.php
<?php
namespace spec\ServiceDouble;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use \Zend\Http\Request as HttpRequest;
class FacadeSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('\ServiceDouble\Facade');
}
/**
* @param \ServiceDouble\Request\Handler $handler
* @param \ServiceDouble\Response\Fake $response
*/
function it_provides_fluent_interface_for_register_handle_method($handler, $response)
{
$handler->getResponse()->willReturn($response);
$this->registerHandler($handler)->shouldReturnAnInstanceOf('\ServiceDouble\Facade');
}
/**
* @param \Zend\Http\Request $request
* @param \Zend\Stdlib\ParametersInterface $parameters
* @param \ServiceDouble\Request\Handler $handler
* @param \ServiceDouble\Response\Fake $response
*/
function it_is_able_to_register_handler($request, $parameters, $handler, $response)
{
$methodName = 'foo';
$handler->getResponse()->willReturn($response);
$handler->match(array('request.jsonrpc.method' => $methodName, 'request.method' => 'POST'))->willReturn(true);
$request->getContent()->willReturn("{\"method\":\"{$methodName}\"}");
$parameters->toArray()->willReturn(array());
$request->getQuery()->willReturn($parameters);
$request->getMethod()->willReturn(HttpRequest::METHOD_POST);
$this->registerHandler($handler);
$response->send()->shouldBeCalled();
$this->handle($request);
}
/**
* @param \Zend\Http\Request $request
* @param \Zend\Stdlib\ParametersInterface $parameters
* @param \ServiceDouble\Request\Handler $handler
* @param \ServiceDouble\Response\Fake $response
*/
function it_throws_exception_when_handler_do_not_have_a_match($request, $parameters, $handler, $response)
{
$requestMethod = 'foo2';
$handler->getResponse()->willReturn($response);
$handler->match(array('request.jsonrpc.method' => $requestMethod, 'request.method' => 'POST'))->willReturn(false);
$this->registerHandler($handler);
$request->getContent()->willReturn("{\"method\":\"{$requestMethod}\"}");
$parameters->toArray()->willReturn(array());
$request->getQuery()->willReturn($parameters);
$request->getMethod()->willReturn(HttpRequest::METHOD_POST);
$this->shouldThrow(new \LogicException("Request does not have a handler."))->duringHandle($request);
}
/**
* @param \Zend\Http\Request $request
* @param \Zend\Stdlib\ParametersInterface $parameters
* @param \ServiceDouble\Request\Handler $firstHandler
* @param \ServiceDouble\Response\Fake $firstResponse
* @param \ServiceDouble\Request\Handler $secondHandler
* @param \ServiceDouble\Response\Fake $secondResponse
*/
function it_search_handler_for_the_first_match($request, $parameters, $firstHandler, $firstResponse, $secondHandler, $secondResponse)
{
$method = 'foo';
$firstHandler->getResponse()->willReturn($firstResponse)->shouldBeCalled();
$firstHandler->match(array('request.jsonrpc.method' => $method, 'request.method' => 'POST'))->willReturn(true)->shouldBeCalled();
$this->registerHandler($firstHandler);
$firstResponse->send()->shouldBeCalled();
$secondHandler->getResponse()->willReturn($secondResponse)->shouldNotBeCalled();
$secondHandler->match(array('request.jsonrpc.method' => $method, 'request.method' => 'POST'))->willReturn(true)->shouldNotBeCalled();
$this->registerHandler($secondHandler);
$secondResponse->send()->shouldNotBeCalled();
$request->getContent()->willReturn("{\"method\":\"{$method}\"}");
$parameters->toArray()->willReturn(array());
$request->getQuery()->willReturn($parameters);
$request->getMethod()->willReturn(HttpRequest::METHOD_POST);
$this->handle($request);
}
}
<file_sep>/spec/ServiceDouble/Matcher/LogicalAndSpec.php
<?php
namespace spec\ServiceDouble\Matcher;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class LogicalAndSpec extends ObjectBehavior
{
/**
* @var \ServiceDouble\Matcher
**/
private $_firstMatcher;
/**
* @var \ServiceDouble\Matcher
**/
private $_secondMatcher;
/**
* @param \ServiceDouble\Matcher $firstMatcher
* @param \ServiceDouble\Matcher $secondMatcher
*/
function let($firstMatcher, $secondMatcher)
{
$this->_firstMatcher = $firstMatcher;
$this->_secondMatcher = $secondMatcher;
$this->beConstructedWith($this->_firstMatcher, $this->_secondMatcher);
}
function it_is_initializable()
{
$this->shouldHaveType('ServiceDouble\Matcher\LogicalAnd');
}
function it_implements_matcher_interface()
{
$this->shouldHaveType('ServiceDouble\Matcher');
}
function it_returns_true_when_both_submatchers_return_true()
{
$data = array();
$this->_firstMatcher->match($data)->willReturn(true);
$this->_secondMatcher->match($data)->willReturn(true);
$this->match($data)->shouldReturn(true);
}
function it_returns_false_when_both_submatchers_return_false()
{
$data = array();
$this->_firstMatcher->match($data)->willReturn(false);
$this->_secondMatcher->match($data)->willReturn(false);
$this->match(array())->shouldReturn(false);
}
function it_returns_false_when_ths_first_submatcher_returns_true_and_the_second_returns_false()
{
$data = array();
$this->_firstMatcher->match($data)->willReturn(true);
$this->_secondMatcher->match($data)->willReturn(false);
$this->match(array())->shouldReturn(false);
}
function it_returns_false_when_ths_first_submatcher_returns_false_and_the_second_returns_true()
{
$data = array();
$this->_firstMatcher->match($data)->willReturn(false);
$this->_secondMatcher->match($data)->willReturn(true);
$this->match(array())->shouldReturn(false);
}
}
<file_sep>/src/ServiceDouble/Request/Parameters.php
<?php
namespace ServiceDouble\Request;
use \Zend\Http\Request as HttpRequest;
use \ServiceDouble\Request\Parameters\Reader;
class Parameters
{
/**
* @var array
*/
private $_params = array();
/**
*
* @param \Zend\Http\Request $request
*/
public function __construct(HttpRequest $request)
{
$this->_params['request.method'] = $request->getMethod();
$this->_parseRequestVariables($request->getQuery()->toArray(), $this->_params, 'request.get');
$reader = new Reader();
$this->_parseRequestVariables($reader->read($request), $this->_params, 'request.jsonrpc');
}
/**
*
* @param string $name
* @return mixed|null
*/
public function get($name)
{
return $this->_params[$name];
}
/**
*
* @return array
*/
public function getAll()
{
return $this->_params;
}
/**
*
* @param array $data
* @param array &$result
* @param string $prefix
* @return array
*/
private function _parseRequestVariables($data, array &$result, $prefix)
{
foreach ($data as $name => $value)
{
$complexName = $prefix . '.' . $name;
if ($this->_isScalar($value))
$result[$complexName] = $value;
else
$this->_parseRequestVariables($value, $result, $complexName);
}
return $result;
}
/**
*
* @param mixed $value
* @return boolean
*/
private function _isScalar($value)
{
return is_bool($value) || is_int($value) || is_float($value) || is_string($value);
}
}
<file_sep>/spec/ServiceDouble/Response/FakeSpec.php
<?php
namespace spec\ServiceDouble\Response;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class FakeSpec extends ObjectBehavior
{
private $_requestParams;
/**
* @param \ServiceDouble\Request\Parameters $requestParams
*/
function let($requestParams)
{
$this->_requestParams = $requestParams;
$this->_requestParams->getAll()->willReturn(array());
libxml_use_internal_errors(false);
$this->beConstructedWith($this->_getFileName('response.xml'), $this->_requestParams);
}
function it_is_initializable()
{
$this->shouldHaveType('\ServiceDouble\Response\Fake');
}
function it_extends_response_interface()
{
$this->shouldHaveType('Zend\Http\PhpEnvironment\Response');
}
function it_return_empty_string_body_by_default()
{
$this->beConstructedWith($this->_getFileName('without_body.xml'), $this->_requestParams);
$this->getContent()->shouldReturn('');
}
function it_returns_the_body_tag_content()
{
$expected = "FooBar\nCC\nF";
$this->getContent()->shouldReturn($expected);
}
function it_throws_exception_when_file_does_not_exist()
{
$path = md5('foo');
$this->shouldThrow(new \InvalidArgumentException("File \"{$path}\" is not readable."))->during('__construct', array($path, $this->_requestParams));
}
function it_throws_exception_when_file_is_not_xml()
{
$path = $this->_getFileName('invalid.xml');
$this->shouldThrow(new \InvalidArgumentException("Unable to parse \"{$path}\"."))->during('__construct', array($path, $this->_requestParams));
}
function it_returns_http_ok_status_by_default()
{
$this->beConstructedWith($this->_getFileName('without_status.xml'), $this->_requestParams);
$this->getStatusCode()->shouldReturn(\Zend\Http\Response::STATUS_CODE_200);
}
function it_returns_the_status_code_tag_content_if_specified()
{
$this->getStatusCode()->shouldReturn(\Zend\Http\Response::STATUS_CODE_500);
}
function it_returns_no_headers_by_default()
{
$this->beConstructedWith($this->_getFileName('without_status.xml'), $this->_requestParams);
$this->getHeaders()->shouldHaveCount(0);
}
function it_returns_headers_content_if_specified()
{
$headers = $this->getHeaders()->has('Content-type')->shouldEqual(true);
$headers = $this->getHeaders()->has('Cache-Control')->shouldEqual(true);
}
/**
* @param \ServiceDouble\Request\Parameters $requestParams
*/
function it_replaces_placeholders_in_response_with_specified_value($requestParams)
{
$value = 'BAZ';
$requestParams->getAll()->willReturn(array('request.jsonrpc.foo' => $value));
$this->beConstructedWith($this->_getFileName('with_placeholder.xml'), $requestParams);
$this->getContent()->shouldReturn("FooBar\nCC\nF\n" . $value);
}
/**
* @param \ServiceDouble\Request\Parameters $requestParams
*/
function it_do_not_replace_placeholder_when_value_is_not_specified($requestParams)
{
$requestParams->getAll()->willReturn(array());
$this->beConstructedWith($this->_getFileName('with_placeholder.xml'), $requestParams);
$this->getContent()->shouldReturn("FooBar\nCC\nF\n@request.jsonrpc.foo@");
}
private function _getFileName($filename)
{
return __DIR__ . '/../../fixtures/' . $filename;
}
}
<file_sep>/spec/ServiceDouble/Request/ParametersSpec.php
<?php
namespace spec\ServiceDouble\Request;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use \Zend\Http\Request as HttpRequest;
class ParametersSpec extends ObjectBehavior
{
/**
* @var \Zend\Http\Request
*/
private $_request;
/**
* @param \Zend\Http\Request $request
* @param \Zend\Stdlib\ParametersInterface $params
*/
function let($request, $params)
{
$this->_request = $request;
$this->_request->getContent()->willReturn("{\"method\":\"foo\", \"result\":{\"id\": 12}}");
$params->toArray()->willReturn(array());
$this->_request->getQuery()->willReturn($params)->shouldBeCalled();
$this->_request->getMethod()->willReturn(HttpRequest::METHOD_POST)->shouldBeCalled();
$this->beConstructedWith($this->_request);
}
function it_is_initializable()
{
$this->shouldHaveType('ServiceDouble\Request\Parameters');
}
function it_returns_request_parameters()
{
$this->get('request.jsonrpc.method')->shouldReturn('foo');
$this->get('request.jsonrpc.result.id')->shouldReturn(12);
}
function it_returns_all_request_parameters()
{
$this->getAll()->shouldReturn(array(
'request.method' => HttpRequest::METHOD_POST,
'request.jsonrpc.method' => 'foo',
'request.jsonrpc.result.id' => 12,
));
}
function it_returns_request_method()
{
$this->get('request.method')->shouldReturn(HttpRequest::METHOD_POST);
}
function it_can_parse_json_from_request()
{
$this->_request->getContent()->willReturn("{\"method\":\"foo\",\"id\":5}");
$this->beConstructedWith($this->_request);
$this->getAll()->shouldReturn(array(
'request.method' => HttpRequest::METHOD_POST,
'request.jsonrpc.method' => 'foo',
'request.jsonrpc.id' => 5,
));
}
function it_ignores_empty_json_string()
{
$this->_request->getContent()->willReturn("");
$this->beConstructedWith($this->_request);
$this->getAll()->shouldReturn(array(
'request.method' => HttpRequest::METHOD_POST
));
}
function it_ignores_invalid_json_string()
{
$this->_request->getContent()->willReturn("{\"method\":\"foo\"");
$this->beConstructedWith($this->_request);
$this->getAll()->shouldReturn(array(
'request.method' => HttpRequest::METHOD_POST
));
}
/**
* @param \Zend\Stdlib\ParametersInterface $params
*/
function it_can_parse_query_string($params)
{
$params->toArray()->willReturn(array(
'id' => '5',
'name' => 'foo',
));
$this->_request->getMethod()->willReturn(HttpRequest::METHOD_GET)->shouldBeCalled();
$this->_request->getQuery()->willReturn($params)->shouldBeCalled();
$this->_request->getContent()->willReturn("");
$this->beConstructedWith($this->_request);
$this->getAll()->shouldReturn(array(
'request.method' => HttpRequest::METHOD_GET,
'request.get.id' => '5',
'request.get.name' => 'foo',
));
}
}
<file_sep>/src/ServiceDouble/Request/Handler.php
<?php
namespace ServiceDouble\Request;
use \ServiceDouble\Response\Fake;
use \ServiceDouble\Request\Handler\AbstractHandler;
class Handler extends AbstractHandler
{
/**
* @var \ServiceDouble\Response\Fake
*/
private $_response;
/**
*
* @param \ServiceDouble\Response\Fake $response
*/
public function __construct(Fake $response)
{
$this->_response = $response;
}
public function getResponse()
{
return $this->_response;
}
}
<file_sep>/spec/ServiceDouble/Matcher/AnySpec.php
<?php
namespace spec\ServiceDouble\Matcher;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class AnySpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('ServiceDouble\Matcher\Any');
}
function it_always_returns_true()
{
$this->match(array())->shouldReturn(true);
}
function it_implements_matcher_interface()
{
$this->shouldHaveType('ServiceDouble\Matcher');
}
}
<file_sep>/src/ServiceDouble/Request/Handler/Proxy.php
<?php
namespace ServiceDouble\Request\Handler;
use \Zend\Http\Client;
use \Zend\Http\PhpEnvironment\Response;
use \Zend\Http\Request;
use \ServiceDouble\Matcher;
use \ServiceDouble\Matcher\None;
use \ServiceDouble\Request\Parameters;
class Proxy extends AbstractHandler
{
/**
* @var \Zend\Http\Request
*/
private $_request;
/**
* @var \Zend\Http\Client
*/
private $_client;
/**
*
* @param \Zend\Http\Request $request
* @param \Zend\Http\Client $client
*/
public function __construct(Request $request, Client $client)
{
$this->_request = $request;
$this->_client = $client;
}
public function getResponse()
{
$response = $this->_client->dispatch($this->_request);
return Response::fromString($response->toString());
}
}
<file_sep>/bin/service_double.sh
#!/bin/bash
HOSTNAME="localhost:8051"
SELF=`realpath $0`
BASEDIR=`dirname $SELF`
PUBLIC_DIR=`realpath $BASEDIR/../public`
LOG_DIR=`realpath $BASEDIR/../log`
LOG_FILE=$LOG_DIR/service_double.log
PID_FILE=$LOG_DIR/service_double.pid
mkdir -p $LOG_DIR
case "${1:-''}" in
'start')
if [ -f $PID_FILE ]
then
echo "Service Double is already running."
exit 1
fi;
php -S $HOSTNAME -t $PUBLIC_DIR >> $LOG_FILE 2>&1 & echo $! > $PID_FILE
error=$?
if [ $error -eq 0 ]
then
echo "Service Double started on $HOSTNAME"
else
echo "Error during starting Service Double server."
exit 2
fi
;;
'stop')
if [ -f $PID_FILE ]
then
echo "Stopping Service Double..."
pid=`cat $PID_FILE`
if kill -9 $pid ;
then
sleep 2
test -f $PID_FILE && rm -f $PID_FILE
else
echo "Service Double could not be stopped..."
exit 2
fi
else
echo "Service Double is not running."
exit 1
fi
;;
'status')
if [ -f $PID_FILE ]
then
echo "Service Double is running."
else
echo "Service Double is not running."
fi;
;;
esac
<file_sep>/spec/ServiceDouble/Request/Handler/ProxySpec.php
<?php
namespace spec\ServiceDouble\Request\Handler;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ProxySpec extends ObjectBehavior
{
/**
* @var \Zend\Http\Request
*/
private $_request;
/**
* @var \Zend\Http\Client
*/
private $_client;
/**
* @param \Zend\Http\Request $request
* @param \Zend\Http\Client $client
*/
function let($request, $client)
{
$this->_request = $request;
$this->_client = $client;
$this->beConstructedWith($this->_request, $this->_client);
}
function it_is_initializable()
{
$this->shouldHaveType('ServiceDouble\Request\Handler\Proxy');
}
/**
* @param \ServiceDouble\Request\Parameters $requestParams
* @param \Zend\Http\Response $response
*/
function it_calls_http_client_for_response($requestParams, $response)
{
$body = "HTTP/1.1 200 OK\r\n"
. "Date: Thu, 20 Dec 2001 12:04:30 GMT\r\n"
. "Server: Apache/2.0.50 (Unix) DAV/2\r\n"
. "Transfer-Encoding: chunked\r\n"
. "Content-Type: application/xhtml+xml; charset=utf-8\r\n"
. "\r\n"
. "AAAAA";
$response->toString()->willReturn($body);
$this->_client->dispatch($this->_request)->shouldBeCalled()->willReturn($response);
$requestParams->getAll()->willReturn(array());
$this->getResponse($requestParams);
}
/**
* @param \ServiceDouble\Request\Parameters $requestParams
* @param \Zend\Http\Response $response
*/
function it_returns_response_from_service($requestParams, $response)
{
$body = "HTTP/1.1 200 OK\r\n"
. "Date: Thu, 20 Dec 2001 12:04:30 GMT\r\n"
. "Server: Apache/2.0.50 (Unix) DAV/2\r\n"
. "Transfer-Encoding: chunked\r\n"
. "Content-Type: application/xhtml+xml; charset=utf-8\r\n"
. "\r\n"
. "AAAAA";
$response->toString()->willReturn($body);
$this->_client->dispatch($this->_request)->willReturn($response);
$requestParams->getAll()->willReturn(array());
$this->getResponse($requestParams)->shouldBeAnInstanceOf('\Zend\Http\PhpEnvironment\Response');
}
/**
* @param \ServiceDouble\Request\Parameters $requestParams
* @param \Zend\Http\Response $response
*/
function it_returns_clients_response($requestParams, $response)
{
$body = "HTTP/1.1 200 OK\r\n"
. "Date: Thu, 20 Dec 2001 12:04:30 GMT\r\n"
. "Server: Apache/2.0.50 (Unix) DAV/2\r\n"
. "Transfer-Encoding: chunked\r\n"
. "Content-Type: application/xhtml+xml; charset=utf-8\r\n"
. "\r\n"
. "AAAAA";
$response->toString()->willReturn($body);
$this->_client->dispatch($this->_request)->willReturn($response);
$requestParams->getAll()->willReturn(array());
$this->getResponse($requestParams)->toString()->shouldReturn($body);
}
function it_does_not_match_anything_by_default()
{
$requestData = array('request.method' => 'foo');
$this->match($requestData)->shouldReturn(false);
}
/**
* @param \ServiceDouble\Matcher $matcher
*/
function it_has_a_matcher($matcher)
{
$requestData = array('request.method' => 'foo');
$matcher->match($requestData)->shouldBeCalled()->willReturn(true);
$this->setMatcher($matcher);
$this->match($requestData)->shouldReturn(true);
}
}
<file_sep>/src/ServiceDouble/Matcher/Equals.php
<?php
namespace ServiceDouble\Matcher;
use ServiceDouble\Matcher;
class Equals implements Matcher
{
/**
* @var string
*/
private $_name;
/**
* @var mixed
*/
private $_value;
/**
*
* @param string $name
* @param mixed $value
* @throws \InvalidArgumentException
*/
public function __construct($name, $value)
{
if (!is_string($name) || empty($name))
throw new \InvalidArgumentException("Name must be a non empty string but \"" . gettype($name) . "\" given.");
if (!is_string($value))
throw new \InvalidArgumentException("Value must be a string but \"" . gettype($value) . "\" given.");
$this->_name = $name;
$this->_value = $value;
}
/**
*
* @param array $data
* @return boolean
*/
public function match(array $data)
{
return isset($data[$this->_name]) && $data[$this->_name] === $this->_value;
}
}
<file_sep>/src/ServiceDouble/Request/Handler/AbstractHandler.php
<?php
namespace ServiceDouble\Request\Handler;
use \ServiceDouble\Matcher;
use \ServiceDouble\Matcher\None;
abstract class AbstractHandler
{
/**
* @var \ServiceDouble\Matcher
*/
private $_matcher = null;
/**
*
* @return \Zend\Http\PhpEnvironment\Response
*/
public abstract function getResponse();
/**
*
* @param array $data
* @return boolean
*/
public function match($data)
{
return $this->_getMatcher()->match($data);
}
/**
* @param \ServiceDouble\Matcher $matcher
*/
public function setMatcher(Matcher $matcher)
{
$this->_matcher = $matcher;
}
/**
* @param \ServiceDouble\Matcher $matcher
*/
private function _getMatcher()
{
if (is_null($this->_matcher))
$this->_matcher = new None();
return $this->_matcher;
}
}
<file_sep>/src/ServiceDouble/Matcher/Factory.php
<?php
namespace ServiceDouble\Matcher;
class Factory
{
/**
*
* @param string $configuration
* @thrown \InvalidArgumentException
* @return \ServiceDouble\Matcher $matcher
*/
public function get($configuration)
{
if (!is_string($configuration) || empty($configuration))
throw new \InvalidArgumentException('Configuration must be a non empty string.');
libxml_use_internal_errors(true);
$matcher = simplexml_load_string($configuration);
if ($matcher === false)
throw new \InvalidArgumentException("Configuration is not valid xml.");
switch ($matcher['type'])
{
case 'equals':
return new Equals((string) $matcher['name'], (string) $matcher['value']);
case 'and':
return new LogicalAnd($this->get($matcher->matcher[0]->asXML()), $this->get($matcher->matcher[1]->asXML()));
case 'any':
return new Any();
default:
throw new \InvalidArgumentException("Matcher type \"" . $matcher['type'] . "\" is not supported.");
}
}
}
<file_sep>/spec/ServiceDouble/Request/HandlerSpec.php
<?php
namespace spec\ServiceDouble\Request;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Zend\Http\Request;
class HandlerSpec extends ObjectBehavior
{
private $_firstResponse;
/**
* @param \ServiceDouble\Response\Fake $firstResponse
*/
function let($firstResponse)
{
$this->_firstResponse = $firstResponse;
$this->beConstructedWith($this->_firstResponse);
}
function it_is_initializable()
{
$this->shouldHaveType('ServiceDouble\Request\Handler');
}
function it_does_not_match_anything_by_default()
{
$requestData = array('request.method' => 'foo');
$this->match($requestData)->shouldReturn(false);
}
/**
* @param \ServiceDouble\Matcher $matcher
*/
function it_has_a_matcher($matcher)
{
$requestData = array('request.method' => 'foo');
$matcher->match($requestData)->shouldBeCalled()->willReturn(true);
$this->setMatcher($matcher);
$this->match($requestData)->shouldReturn(true);
}
}
<file_sep>/src/ServiceDouble/Matcher.php
<?php
namespace ServiceDouble;
interface Matcher
{
/**
*
* @param array $data
* @return boolean
*/
public function match(array $data);
}
<file_sep>/spec/ServiceDouble/Matcher/FactorySpec.php
<?php
namespace spec\ServiceDouble\Matcher;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class FactorySpec extends ObjectBehavior
{
function let()
{
libxml_use_internal_errors(false);
}
function it_is_initializable()
{
$this->shouldHaveType('ServiceDouble\Matcher\Factory');
}
function it_throws_exception_when_type_does_not_exists()
{
$this->shouldThrow(new \InvalidArgumentException("Matcher type \"foobarr\" is not supported."))->during('get', array($this->_getConfigFromFile('notdefined.xml')));
}
function it_throws_exception_when_configuration_is_non_empty_string()
{
$configurations = array(
1,
new \stdClass(),
array(),
''
);
foreach ($configurations as $configuration)
{
$this->shouldThrow(new \InvalidArgumentException("Configuration must be a non empty string."))->during('get', array($configuration));
}
}
function it_throws_exception_when_configuration_is_not_a_xml()
{
$this->shouldThrow(new \InvalidArgumentException("Configuration is not valid xml."))->during('get', array('fooo bar'));
}
function it_can_create_equals_matcher()
{
$this->get($this->_getConfigFromFile('equals.xml'))->shouldHaveType('\ServiceDouble\Matcher\Equals');
}
function it_reads_equals_matcher_properties()
{
$matcher = $this->get($this->_getConfigFromFile('equals.xml'));
$matcher->match(array('request.method' => 'foo'))->shouldReturn(true);
$matcher->match(array('request.method' => 'bar'))->shouldReturn(false);
$matcher = $this->get($this->_getConfigFromFile('equals-2.xml'));
$matcher->match(array('request.result.id' => '6'))->shouldReturn(true);
$matcher->match(array('request.result.id' => '4'))->shouldReturn(false);
}
function it_can_create_logical_and_matcher()
{
$this->get($this->_getConfigFromFile('and.xml'))->shouldHaveType('\ServiceDouble\Matcher\LogicalAnd');
}
function it_reads_and_matcher_properties()
{
$matcher = $this->get($this->_getConfigFromFile('and.xml'));
$matcher->match(array('request.method' => 'foo', 'request.result.id' => '8'))->shouldReturn(true);
$matcher->match(array('request.method' => 'foo'))->shouldReturn(false);
$matcher->match(array('request.result.id' => '8'))->shouldReturn(false);
}
function it_reads_any_matcher_properties()
{
$matcher = $this->get($this->_getConfigFromFile('any.xml'));
$matcher->shouldHaveType('\ServiceDouble\Matcher\Any');
}
private function _getConfigFromFile($filename)
{
return file_get_contents(realpath(__DIR__ . '/../../fixtures/matchers/' . $filename));
}
}
<file_sep>/README.md
Service Double <img src="https://travis-ci.org/piotrrepetowski/service-double.png?branch=master" />
===========
Tool that simplifies creation of fake http based services.
Example - fake implementation of JSONRpc service:
1. Define which method should be mocked:
```xml
<?xml version="1.0" encoding="utf-8"?>
<!-- config/config.xml -->
<handlers>
<handler response="foo_response.xml">
<matcher type="equals" name="request.method" value="foo" />
</handler>
...
</handlers>
```
Response attributes tell where is stored information about response.
Matcher tells when this response should be returned.
Currently supported matchers:
- any - always true,
- none - always false,
- equals - matches whether specified attribute (see below for more details) has specified value,
- logical and - true when submatchers returns true, false otherwise.
Currently supported attributes:
- request.method - represents http method used in request,
- request.jsonrpc - represents jsonrpc attributes,
- request.get - represents query string attributes.
Request attributes may be nested e.g.:
```json
{
"result": {
"name": "foo"
},
"errors": null,
"id": 12
}
```
To use value of name in matcher definition reference to it with result.data.name.
```xml
<matcher type="equals" name="request.jsonrpc.result.name" value="foo" />
```
2. Define proxy to use original service for other calls:
```xml
<?xml version="1.0" encoding="utf-8"?>
<!-- config/config.xml -->
<handlers>
...
<handler url="http://localhost:3500">
<matcher type="any" />
</handler>
</handlers>
```
3. Define response
```xml
<?xml version="1.0" encoding="utf-8"?>
<!-- config/foo_response.xml -->
<response>
<body><![CDATA[FOO]]></body>
</response>
```
This response will return "FOO".
4. Run Service Double server:
```bash
bin/service_double.sh start
```
and use your new service.
<file_sep>/public/index.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
$request = new \Zend\Http\PhpEnvironment\Request();
$loader = new \ServiceDouble\Request\Handler\Loader();
$facade = new \ServiceDouble\Facade();
foreach ($loader->get(__DIR__ . '/../config/config.xml', $request) as $handler)
{
$facade->registerHandler($handler);
}
try
{
$facade->handle($request);
}
catch (Exception $e)
{
echo $e->getMessage();
}
<file_sep>/src/ServiceDouble/Request/Parameters/Reader.php
<?php
namespace ServiceDouble\Request\Parameters;
use \Zend\Http\Request;
class Reader
{
/**
*
* @param \Zend\Http\Request $request
* @return array
*/
public function read(Request $request)
{
$data = json_decode($request->getContent(), true);
return is_array($data) ? $data : array();
}
}
<file_sep>/src/ServiceDouble/Facade.php
<?php
namespace ServiceDouble;
class Facade
{
/**
* @var \ServiceDouble\RequestHandler\Handler[]
*/
private $_handlers = array();
/**
*
* @param \ServiceDouble\RequestHandler\Handler $handler
*/
public function registerHandler($handler)
{
$this->_handlers[] = $handler;
return $this;
}
/**
*
* @param \Zend\Http\Request $request
*/
public function handle(\Zend\Http\Request $request)
{
$requestParams = new Request\Parameters($request);
$response = $this->_getResponse($requestParams);
if (!isset($response))
throw new \LogicException("Request does not have a handler.");
$response->send();
}
/**
*
* @param \ServiceDouble\Request\Parameters $request
* @return \ServiceDouble\Response\Fake|null
*/
private function _getResponse(Request\Parameters $requestParams)
{
foreach ($this->_handlers as $handler)
{
if ($handler->match($requestParams->getAll()))
return $handler->getResponse();
}
return null;
}
}
<file_sep>/spec/ServiceDouble/Request/Parameters/ReaderSpec.php
<?php
namespace spec\ServiceDouble\Request\Parameters;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ReaderSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('ServiceDouble\Request\Parameters\Reader');
}
/**
* @param \Zend\Http\Request $request
*/
function it_reads_jsonrpc_request($request)
{
$request->getContent()->willReturn("{\"method\":\"foo\", \"result\":[]}");
$this->read($request)->shouldReturn(array(
'method' => 'foo',
'result' => array()
));
}
}
<file_sep>/src/ServiceDouble/Response/Fake.php
<?php
namespace ServiceDouble\Response;
use Zend\Http\PhpEnvironment\Response;
use Zend\Http\Headers;
use ServiceDouble\Request\Parameters;
class Fake extends Response
{
/**
* @var SimpleXMLElement
*/
private $_response;
/**
* @var int
*/
private $_sleep = 0;
/**
* @var array
*/
private $_placeholders = array();
/**
*
* @param string $path
* @param \ServiceDouble\Request\Parameters $requestParams
* @throws InvalidArgumentException
*/
public function __construct($path, Parameters $requestParams)
{
if (!is_readable($path))
throw new \InvalidArgumentException("File \"{$path}\" is not readable.");
libxml_use_internal_errors(true);
$response = simplexml_load_file($path);
if ($response === false)
throw new \InvalidArgumentException("Unable to parse \"{$path}\".");
$this->_response = $response;
$this->setContent(trim($this->_response->body));
if (isset($this->_response->statusCode))
$this->setStatusCode((int) $this->_response->statusCode);
if (isset($this->_response->headers))
{
$headers = new Headers();
foreach ($this->_response->headers->header as $header)
{
$headers->addHeaderLine(trim($header->name), trim($header->value));
}
$this->setHeaders($headers);
}
if (isset($this->_response->sleep))
$this->_sleep = (int) $this->_response->sleep;
foreach ($requestParams->getAll() as $name => $value)
$this->_placeholders[$name] = $value;
}
public function getContent()
{
$content = parent::getContent();
return $this->_replacePlaceholders($content);
}
public function send()
{
if ($this->_sleep > 0)
sleep($this->_sleep);
return parent::send();
}
/**
*
* @param string $body
* @return string
*/
private function _replacePlaceholders($body)
{
$keys = array();
foreach (array_keys($this->_placeholders) as $name)
{
$keys[] = '@' . $name . '@';
}
return str_replace($keys, array_values($this->_placeholders), $body);
}
}
<file_sep>/spec/ServiceDouble/Matcher/EqualsSpec.php
<?php
namespace spec\ServiceDouble\Matcher;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class EqualsSpec extends ObjectBehavior
{
private $_name;
private $_value;
function let()
{
$this->_name = 'foo';
$this->_value = '1';
$this->beConstructedWith($this->_name, $this->_value);
}
function it_is_initializable()
{
$this->shouldHaveType('ServiceDouble\Matcher\Equals');
}
function it_implements_matcher_interface()
{
$this->shouldHaveType('ServiceDouble\Matcher');
}
function it_match_when_array_contains_name_with_identical_value_as_value()
{
$data = array(
$this->_name => $this->_value,
'bar' => '23',
);
$this->match($data)->shouldReturn(true);
}
function it_do_not_match_when_values_are_not_identical()
{
$data = array(
$this->_name => 1,
);
$this->match($data)->shouldReturn(false);
}
function it_do_not_match_when_values_is_not_present()
{
$data = array(
'foo.test.baz' => 1,
);
$this->match($data)->shouldReturn(false);
}
function it_throws_exception_when_name_is_not_non_empty_stirng()
{
$names = array(
1,
new \stdClass(),
array(),
'',
1.5
);
foreach ($names as $name)
{
$this->shouldThrow(new \InvalidArgumentException("Name must be a non empty string but \"" . gettype($name) . "\" given."))->during('__construct', array($name, 'foo'));
}
}
function it_throws_exception_when_value_is_not_stirng()
{
$values = array(
1,
new \stdClass(),
array(),
1.5
);
foreach ($values as $value)
{
$this->shouldThrow(new \InvalidArgumentException("Value must be a string but \"" . gettype($value) . "\" given."))->during('__construct', array('foo', $value));
}
}
}
<file_sep>/spec/fixtures/config.ini
foo:foo_response.xml
bar:bar_response.xml
<file_sep>/spec/ServiceDouble/Request/Handler/LoaderSpec.php
<?php
namespace spec\ServiceDouble\Request\Handler;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Zend\Http\Request;
class LoaderSpec extends ObjectBehavior
{
function let()
{
libxml_use_internal_errors(false);
}
function it_is_initializable()
{
$this->shouldHaveType('ServiceDouble\Request\Handler\Loader');
}
/**
* @param \Zend\Http\Request $request
*/
function it_throws_exception_when_file_does_not_exist($request)
{
$path = md5('bar');
$this->shouldThrow(new \InvalidArgumentException("File \"{$path}\" is not readable."))->duringGet($path, $request);
}
/**
* @param \Zend\Http\Request $request
* @param \Zend\Stdlib\ParametersInterface $parameters
*/
function it_reads_all_definitions_from_file($request, $parameters)
{
$request->getContent()->willReturn("{\"method\":\"foo\"}");
$parameters->toArray()->willReturn(array());
$request->getQuery()->willReturn($parameters);
$request->getMethod()->willReturn(Request::METHOD_POST);
$result = $this->get($this->_getPath(), $request);
$result->shouldHaveCount(2);
}
/**
* @param \Zend\Http\Request $request
* @param \Zend\Stdlib\ParametersInterface $parameters
*/
function it_creates_handlers_from_config($request, $parameters)
{
$request->getContent()->willReturn("{\"method\":\"foo\"}");
$parameters->toArray()->willReturn(array());
$request->getQuery()->willReturn($parameters);
$request->getMethod()->willReturn(Request::METHOD_POST);
$result = $this->get($this->_getPath(), $request);
$result[0]->shouldBeAnInstanceOf('\ServiceDouble\Request\Handler');
$result[1]->shouldBeAnInstanceOf('\ServiceDouble\Request\Handler');
}
/**
* @param \Zend\Http\Request $request
* @param \Zend\Stdlib\ParametersInterface $parameters
*/
function it_reads_response_data($request, $parameters)
{
$request->getContent()->willReturn("{\"method\":\"foo\"}");
$parameters->toArray()->willReturn(array());
$request->getQuery()->willReturn($parameters);
$request->getMethod()->willReturn(Request::METHOD_POST);
$result = $this->get($this->_getPath(), $request);
$result[1]->getResponse()->getBody()->shouldReturn('BAR');
}
/**
* @param \Zend\Http\Request $request
*/
function it_returns_empty_array_when_config_is_empty($request)
{
$result = $this->get($this->_getPath('empty_config.xml'), $request);
$result->shouldHaveCount(0);
}
/**
* @param \Zend\Http\Request $request
* @param \Zend\Stdlib\ParametersInterface $parameters
*/
function it_sets_placeholders_in_responses($request, $parameters)
{
$request->getContent()->willReturn("{\"foo\":\"FOBABZ\"}");
$parameters->toArray()->willReturn(array());
$request->getQuery()->willReturn($parameters);
$request->getMethod()->willReturn(Request::METHOD_POST);
$result = $this->get($this->_getPath('placeholders_config.xml'), $request);
$result[0]->getResponse()->getBody()->shouldReturn("FooBar\nCC\nF\nFOBABZ");
}
/**
* @param \Zend\Http\Request $request
* @param \Zend\Stdlib\ParametersInterface $parameters
* @param \Zend\Uri\Uri $uri
*/
function it_reads_proxy_handlers($request, $parameters, $uri)
{
$request->getContent()->willReturn("");
$parameters->toArray()->willReturn(array());
$request->getQuery()->willReturn($parameters);
$request->getMethod()->willReturn(Request::METHOD_POST);
$uri->getPath()->willReturn('')->shouldBeCalled();
$uri->getQuery()->willReturn('')->shouldBeCalled();
$request->getUri()->willReturn($uri);
$request->setUri(Argument::type('\Zend\Uri\Uri'))->willReturn($request)->shouldBeCalled();
$result = $this->get($this->_getPath('config_with_proxy.xml'), $request);
$result->shouldHaveCount(1);
$result[0]->shouldBeAnInstanceOf('\ServiceDouble\Request\Handler\Proxy');
}
/**
*
* @param string $file
* @return string
*/
private function _getPath($file = 'config.xml')
{
return __DIR__ . '/../../../fixtures/' . $file;
}
}
<file_sep>/src/ServiceDouble/Matcher/None.php
<?php
namespace ServiceDouble\Matcher;
use \ServiceDouble\Matcher;
class None implements Matcher
{
public function match(array $data)
{
return false;
}
}
<file_sep>/config/config.ini
add_monitor:../responses/InternalServerError.xml
<file_sep>/src/ServiceDouble/Matcher/LogicalAnd.php
<?php
namespace ServiceDouble\Matcher;
use ServiceDouble\Matcher;
class LogicalAnd implements Matcher
{
/**
* @var \ServiceDouble\RequestHandler\Matcher
**/
private $_firstMatcher;
/**
* @var \ServiceDouble\RequestHandler\Matcher
**/
private $_secondMatcher;
/**
*
* @param \ServiceDouble\RequestHandler\Matcher $firstMatcher
* @param \ServiceDouble\RequestHandler\Matcher $secondMatcher
**/
public function __construct(Matcher $firstMatcher, Matcher $secondMatcher)
{
$this->_firstMatcher = $firstMatcher;
$this->_secondMatcher = $secondMatcher;
}
/**
*
* @param array $data
* @return boolean
*/
public function match(array $data)
{
return $this->_firstMatcher->match($data) && $this->_secondMatcher->match($data);
}
}
<file_sep>/src/ServiceDouble/Matcher/Any.php
<?php
namespace ServiceDouble\Matcher;
use \ServiceDouble\Matcher;
class Any implements Matcher
{
public function match(array $data)
{
return true;
}
}
<file_sep>/src/ServiceDouble/Request/Handler/Loader.php
<?php
namespace ServiceDouble\Request\Handler;
use Zend\Http\Client;
use Zend\Http\Request;
use ServiceDouble\Request\Parameters;
class Loader
{
/**
*
* @param string $path
* @param \Zend\Http\Request $request
* @return array
*/
public static function get($path, Request $request)
{
if (!is_readable($path))
throw new \InvalidArgumentException("File \"{$path}\" is not readable.");
$currentDir = getcwd();
chdir(dirname($path));
$result = array();
libxml_use_internal_errors(true);
$handlers = simplexml_load_file($path);
if (isset($handlers->handler))
{
$factory = new \ServiceDouble\Matcher\Factory();
$requestParams = new Parameters($request);
foreach ($handlers->handler as $handlerData)
{
if (isset($handlerData['url']))
{
$newUri = new \Zend\Uri\Http((string) $handlerData['url']);
$newUri->setPath($request->getUri()->getPath());
$newUri->setQuery($request->getUri()->getQuery());
$newRequest = clone $request;
$newRequest->setUri($newUri);
$handler = new \ServiceDouble\Request\Handler\Proxy(
$newRequest,
new Client()
);
}
else
{
$handler = new \ServiceDouble\Request\Handler(
self::_getResponse($handlerData, $requestParams)
);
}
$handler->setMatcher($factory->get($handlerData->matcher->asXML()));
$result[] = $handler;
}
}
chdir($currentDir);
return $result;
}
/**
*
* @param SimpleXMLElement $handlerData
* @param \ServiceDouble\Request\Parameters $requestParams
* @return \ServiceDouble\Response\Fake|null
*/
private static function _getResponse(\SimpleXMLElement $handlerData, Parameters $requestParams)
{
$response = null;
if (isset($handlerData['response']))
{
$response = new \ServiceDouble\Response\Fake($handlerData['response'], $requestParams);
}
return $response;
}
}
|
ef896334be467134c09a491f1cbf0e54a667fdde
|
[
"Markdown",
"INI",
"PHP",
"Shell"
] | 30
|
PHP
|
piotrrepetowski/service-double
|
5f08082c0fb13077b5b6dab23300301f28c00fd9
|
ea77310af2e263a668f03c88a4679b13b43f0f4d
|
refs/heads/master
|
<repo_name>salmanasghar12/temporary<file_sep>/edit.php
<?php
$conn= mysql_connect("localhost","root","");
$db=mysql_select_db('students',$conn);
$edit_record =$_GET['edit']; // that is coming from previous page from view.php
$query="select * from u_reg where u_id='$edit_record'";
$run=mysql_query($query);
while($row=mysql_fetch_array($run)){
$edit_id=$row['u_id'];
$s_name=$row['1'];
$s_father=$row['2'];
$s_school=$row['3'];
$s_roll=$row['4'];
$s_class=$row['5'];
}
?>
<html>
<head>
<title>Updating Student's Record</title>
</head>
<body>
<form method="post" action="edit.php?edit_form=<?php echo $edit_id; ?>">
<table width="500" border="3" align="center">
<tr>
<th bgcolor="yellow" colspan="5">updating Form </th>
</tr>
<tr>
<td>Student's Name</td>
<td>
<input type="text" name = 'user_name1' value='<?php echo $s_name; ?>' >
</td>
</tr>
<tr>
<td>Father's Name</td>
<td><input type="text" name = 'father_name1' value='<?php echo $s_father; ?>'>
</tr>
<tr>
<td>School's Name</td>
<td><input type="text" name = 'school_name1' value='<?php echo $s_school; ?>'</td>
</tr>
<tr>
<td>Roll Number</td>
<td><input type="text" name = 'roll_no1' value='<?php echo $s_roll; ?>'>
</td>
</tr>
<tr>
<td> Class: </td>
<td><select name="student_class1">
<option value='<?php echo $s_class; ?>'><?php echo $s_class; ?></option>
<option value ='10th'>10th</option>
<option value ='9th'>9th</option>
</select> </td>
</tr>
<tr>
<td align="center" colspan="6">
<input type='submit' name = 'update' value = 'update' > </td>
</tr>
</table>
</form>
</body>
</html>
<?php
if(isset($_POST['update'])){
$edit_record1= $_GET['edit_form'];
$student_name= $_POST['user_name1'];
$student_father= $_POST['father_name1'];
$student_school= $_POST['school_name1'];
$student_roll= $_POST['roll_no1'];
$student_class = $_POST['student_class1'];
$query1="update u_reg set u_name='$student_name',u_father='$student_father', u_school='$student_school' , u_roll='$student_roll',u_class='$student_class' where u_id='$edit_record1'";
if (mysql_query($query1)){
echo "<script>window.open('view.php?updated=Record has been updated..!','_self')</script>";
}
}
?><file_sep>/delete.php
<?php
$conn=mysql_connect("localhost","root","");
$db=mysql_select_db('students',$conn);
$delete_record=$_GET['del'];
$query ="delete from u_reg where u_id='$delete_record'";
if (mysql_query($query)){
echo "<script>window.open('view.php?deleted=Record has been deleted successfully!','_self')</script>";
}
?><file_sep>/user_registration.php
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="<NAME>, <NAME>, and Bootstrap contributors">
<meta name="generator" content="Jekyll v3.8.5">
<title>Student's Registration Form</title>
</head>
<body>
<form method="post" action="user_registration.php">
<table width="500" border="3" align="center">
<tr>
<th bgcolor="yellow" colspan="5">Registration Form </th>
</tr>
<tr>
<td>Student's Name</td>
<td><input type="text" name = 'user_name'>
<font color='red'><?php echo @$_GET['name'];?></font>
</td>
</tr>
<tr>
<td>Father's Name</td>
<td><input type="text" name = 'father_name'>
<font color='red'><?php echo @$_GET['father'];?></font>
</td>
</tr>
<tr>
<td>School's Name</td>
<td><input type="text" name = 'school_name'>
<font color='red'><?php echo @$_GET['school'];?></font>
</td>
</tr>
<tr>
<td>Roll Number</td>
<td><input type="text" name = 'roll_no'>
<font color='red'><?php echo @$_GET['roll'];?></font>
</td>
</tr>
<tr>
<td> Class: </td>
<td><select name="student_class">
<option value="null">Select Class </option>
<option value ='10th'>10th</option>
<option value ='9th'>9th</option>
</select>
<font color='red'><?php echo @$_GET['class'];?></font>
</td>
</tr>
<tr>
<td align="center" colspan="6">
<input type='submit' name = 'submit' value = 'submit' > </td>
</tr>
</table>
</form>
</body>
</html>
<?php
$conn=mysql_connect("localhost","root","");
$db=mysql_select_db('students',$conn);
if(isset($_POST['submit'])){
$student_name=$_POST['user_name'];
$student_father=$_POST['father_name'];
$student_school=$_POST['school_name'];
$student_roll=$_POST['roll_no'];
$student_class=$_POST['student_class'];
if($student_name==''){
echo "<script>window.open('user_registration.php?name=Name is Required','_self')</script>";
exit();
}
if($student_father==''){
echo "<script>window.open('user_registration.php?father=Father name is Required','_self') </script>";
exit();
}
if($student_school==''){
echo "<script>window.open('user_registration.php?school=School Name write','_self')</script>";
exit();
}
if($student_roll==''){
echo "<script>window.open('user_registration.php?roll=Roll Number is Required','_self')</script>";
exit();
}
if($student_class=='null'){
echo "<script>window.open('user_registration.php?class=Select your Class','_self') </script>";
exit();
}
$que = "insert into u_reg (u_name,u_father,u_school,u_roll,u_class) values ('$student_name','$student_father','$student_school','$student_roll','$student_class')";
if(mysql_query($que)){
echo "<center><b>The followind data is being inserted into database</b></center>";
echo "<table align='center' border='4'>
<tr>
<td>$student_name</td>
<td>$student_father</td>
<td>$student_school</td>
<td>$student_roll</td>
<td>$student_class</td>
<tr>
</table>";
}
}
?><file_sep>/admin_login.php
<?php
session_start();
?>
<html>
<head>
<title> Admin Login</title>
</head>
<body>
<form action='admin_login.php' method='post' >
<table width="400" bgcolor ='orange' border="2" align='center'>
<tr>
<td align= 'center' bgcolor="pink" colspan="6"><h2>Admin Panel Form</h2></td>
</tr>
<tr>
<td align= 'right'>Admin Name <td>
<td><input type='text' name='admin_name' > </td>
</tr>
<tr>
<td align='right'>Admin Password <td>
<td><input type='Password' name='admin_pass' > </td>
</tr>
<tr>
<td colspan="4" align ='center'> <input type='submit' name ='login' value= 'login' ></td>
</tr>
</table>
</form>
<center><?php echo @$_GET['error'] ; ?> </center>
</body>
</html>
<?php
$conn=mysql_connect("localhost","root","");
$db=mysql_select_db('students',$conn);
if(isset($_POST['login'])){
$admin_name = $_SESSION['admin_name'] = $_POST['admin_name'];
$admin_pass=$_POST['admin_pass'];
$query="select * from login where user_name='$admin_name' AND user_password='$<PASSWORD>'";
$run=mysql_query($query);
if(mysql_num_rows($run)>0){
echo "<script>window.open('view.php?logged=Logged in Successfully','_self')</script>";
}
else {
echo "<script>alert('Username or Password is incorrect!')</script>";
session_destroy();
}
}
?><file_sep>/view.php
<?php
session_start();
if (!$_SESSION['admin_name']){
header('location:admin_login.php?error=You are not an administrator');
}
?>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<head>
<title>Viewing the Records</title>
</head>
<body>
<a href ='user_registration.php'>Insert New Record </a>
Welcome: <font color="red" size='3'>
<?php echo $_SESSION['admin_name']; ?> </font>
<a href ='logout.php' >LOGOUT </a>
<center><font color ='red' size='6' >
<?php echo @$_GET['deleted'] ; ?>
<?php echo @$_GET['updated'] ; ?>
<?php echo @$_GET['logged'] ; ?>
</font></center>
<table align="center" width="1000" border="4">
<tr>
<td colspan="20" align="center" bgcolor='yellow'>
<h1>Viewing All the Records</td></h1>
</tr>
<tr align='center'>
<th>Serial No</th>
<th>Student's Name </th>
<th>Father's Name </th>
<th>Roll Number </th>
<th>Delete </th>
<th>Edit</th>
<th>Details</th>
</tr>
<?php
$conn=mysql_connect("localhost","root","");
$db=mysql_select_db('students',$conn);
$que = "select * from u_reg order by 1 DESC";
$run=mysql_query($que);
$i=1;
while ($row=mysql_fetch_array($run)){
$u_id=$row['u_id'];
$u_name=$row[1];
$u_father=$row[2];
$u_roll=$row[4];
?>
<tr align='center'>
<td><?php echo $i; $i++ ?></td>
<td><?php echo $u_name; ?></td>
<td><?php echo $u_father; ?></td>
<td><?php echo $u_roll; ?></td>
<td><a href='delete.php?del=<?php echo $u_id; ?>'>Delete</a></td>
<td><a href ='edit.php?edit=<?php echo $u_id; ?>'>Edit</a></td>
<td><a href ='view.php?details=<?php echo $u_id; ?>'>Details</a></td>
</tr>
<?php } ?>
</table>
<?php
$record_details=@$_GET['details'];// @ is very necessary to remove error
$query="select * from u_reg where u_id='$record_details'";
$run1=mysql_query($query);
while($row1=mysql_fetch_array($run1)){
$name=$row1[1];
$father=$row1[2];
$school=$row1[3];
$roll=$row1[4];
$class=$row1[5];
?>
<br><br>
<table align="center" border='4' bgcolor='gray' width='800'>
<tr>
<td colspan= '6' bgcolor='yellow' align='center'><h2>Your Details here</h2></td>
</tr>
<tr align='center' bgcolor="white">
<td><?php echo $name; ?></td>
<td><?php echo $father; ?></td>
<td><?php echo $school; ?></td>
<td><?php echo $roll; ?></td>
<td><?php echo $class; ?></td>
</tr>
<?php } ?>
</table>
<br><br><br><br><br><br>
<form action='view.php' method='get'>Search a Record : <input type='text' name ='search'>
<input type='submit' name ='submit' value ='Find Now'>
</form>
<?php
if(isset($_GET['search'])){
$search_record=$_GET['search'];
$query2="select * from u_reg where u_name='$search_record' OR u_roll ='$search_record'";
$run2=mysql_query ($query2);
while ($row2=mysql_fetch_assoc($run2))// ITs same like mysql_fetch_array
{
$name123=$row2['u_name'];// it will give error in it if we write 1,2 instead of database names as in the fields in phpmyadmin
$father123=$row2['u_father'];
$school123=$row2['u_school'];
$roll123=$row2['u_roll'];
$class123=$row2['u_class'];
?>
<table width='800' bgcolor='yellow' align='center' border='1'>
<tr align='center'>
<td><?php echo $name123; ?> </td>
<td><?php echo $father123; ?> </td>
<td><?php echo $school123; ?> </td>
<td><?php echo $roll123; ?> </td>
<td><?php echo $class123; ?> </td>
</tr>
</table>
<?php }} ?>
</body>
</html><file_sep>/search.php
<html>
<head>
<title>Search a Record</title>
</head>
<body>
<?php
$conn=mysql_connect("localhost","root","");
$db=mysql_select_db('students',$conn);
?>
<form action='search.php' method='get'>Search a Record : <input type='text' name ='search'>
<input type='submit' name ='submit' value ='Find Now'>
</form>
<?php
if(isset($_GET['search'])){
$search_record=$_GET['search'];
$query2="select * from u_reg where u_name='$search_record' OR u_roll ='$search_record'";
$run2=mysql_query ($query2);
while ($row2=mysql_fetch_assoc($run2))// ITs same like mysql_fetch_array
{
$name123=$row2['u_name'];// it will give error in it if we write 1,2 instead of database names as in the fields in phpmyadmin
$father123=$row2['u_father'];
$school123=$row2['u_school'];
$roll123=$row2['u_roll'];
$class123=$row2['u_class'];
?>
<ul align='center'>
<li><?php echo $name123; ?></li>
<li><?php echo $father123; ?></li>
<li><?php echo $school123; ?></li>
<li><?php echo $roll123; ?></li>
<li><?php echo $class123; ?></li>
</ul>
<table width='800' bgcolor='yellow' align='center' border='1'>
<tr align='center'>
<td><?php echo $name123; ?> </td>
<td><?php echo $father123; ?> </td>
<td><?php echo $school123; ?> </td>
<td><?php echo $roll123; ?> </td>
<td><?php echo $class123; ?> </td>
</tr>
</table>
<?php }} ?>
</body>
</html>
|
9467d92ae23b5d45cb55492491a726cd7f9db9a9
|
[
"PHP"
] | 6
|
PHP
|
salmanasghar12/temporary
|
53208df6fddb95438caf87fe4681f9f7cc47e80a
|
6c33c3b3d52bede96a1aed7b90f0078c6db6143b
|
refs/heads/master
|
<repo_name>jorian82/InventoryApp<file_sep>/InventoryApp/src/com/ssde/desktop/db/Connector.java
/*
* 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.
*/
package com.ssde.desktop.db;
import java.sql.*;
import com.ssde.desktop.model.*;
/**
*
* @author jorian
*/
public class Connector {
private String forName = null;
private String db = null;
private Connection c = null;
private Statement stmt = null;
public Connector(String db) {
this.forName = "org.sqlite.JDBC";
this.db = "jdbc.sqlite:"+db;
}
public Connection getConnection() {
try{
Class.forName(forName);
c = DriverManager.getConnection(db);
} catch (Exception e) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
}
return c;
}
public void closeConnection() {
try{
c.close();
} catch (Exception e) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
}
}
}
|
ad4e63439c35c623467e2defab86a74daafff073
|
[
"Java"
] | 1
|
Java
|
jorian82/InventoryApp
|
a95cff836dc5564113f986d3de57662c835abd9d
|
75c2451d8c02504a50cda384451ce5fe695ae1c3
|
refs/heads/master
|
<repo_name>albertxavierlopez/R-scripts<file_sep>/Basic_ML.R
##############################
### CLUSTERING with KMEANS ###
##############################
# Set random seed. Don't remove this line.
set.seed(1)
# Chop up iris in my_iris and species
my_iris <- iris[-5]
species <- iris$Species
# Perform k-means clustering on my_iris in 3 clusters: kmeans_iris
kmeans_iris<-kmeans(my_iris, 3)
# Compare the actual Species to the clustering using table() // The same for a confussion matrix
table(species, kmeans_iris$cluster)
# Plot Petal.Width against Petal.Length, coloring by cluster
plot(Petal.Length ~ Petal.Width, data = my_iris, col = kmeans_iris$cluster)
# MEASURING ACCURACY ratio of the WSS to the BSS
# Print out the ratio of the within sum of squares to the between cluster sum of squares, so WSS/BSS.
# Print out the ratio of the WSS to the BSS
kmeans_iris$tot.withinss/kmeans_iris$betweenss
##############################
### CLASSIFICATION by hand ###
##############################
# The spam filter that has been 'learned' for you
spam_classifier <- function(x){
prediction <- rep(NA, length(x)) # initialize prediction vector
prediction[x > 4] <- 1
prediction[x >= 3 & x <= 4] <- 0
prediction[x >= 2.2 & x < 3] <- 1
prediction[x >= 1.4 & x < 2.2] <- 0
prediction[x > 1.25 & x < 1.4] <- 1
prediction[x <= 1.25] <- 0
return(factor(prediction, levels = c("1", "0"))) # prediction is either 0 or 1
}
spam_classifier_simple <- function(x){
prediction <- rep(NA, length(x)) # initialize prediction vector
prediction[x > 4] <- 1
prediction[x <= 4] <- 0
return(factor(prediction, levels = c("1", "0"))) # prediction is either 0 or 1
}
a<-c(1:10)
spam_classifier_simple(a)
# Apply spam_classifier to emails_full: pred_full
pred_full<-spam_classifier(a)
# Build CONFUSION MATRIX
conf_full <- table(a, pred_full)
# Calculate the ACCURACY
acc_full <- sum(diag(conf_full)) / sum(conf_full)
# Print out ACCURACY
acc_full
########################
###### Tree Model ######
########################
# Set random seed. Don't remove this line.
library(rpart)
library(rattle)
library(rpart.plot)
library(RColorBrewer)
set.seed(1)
# Take a look at the iris dataset
str(iris)
summary(iris)
# A decision tree model has been built for you
tree <- rpart(Species ~ .,
data = iris, method = "class") #classification method
# A dataframe containing unseen observations
unseen <- data.frame(Sepal.Length = c(5.3, 7.2),
Sepal.Width = c(2.9, 3.9),
Petal.Length = c(1.7, 5.4),
Petal.Width = c(0.8, 2.3))
# Predict the label of the unseen observations. Print out the result.
predict(tree, unseen, type="class")
head(iris)
# Plot rpart
fancyRpartPlot(tree)
# Prune the tree:method to shrink tree to a more compact tree,
pruned<-prune(tree, cp=0.01)
# Visualize the new pruned tree (this is a simple case but should be a shrinked version)
fancyRpartPlot(pruned)
<file_sep>/spam_classifier.R
# The spam filter that has been 'learned' for you
spam_classifier <- function(x){
prediction <- rep(NA, length(x)) # initialize prediction vector
prediction[x > 4] <- 1
prediction[x >= 3 & x <= 4] <- 0
prediction[x >= 2.2 & x < 3] <- 1
prediction[x >= 1.4 & x < 2.2] <- 0
prediction[x > 1.25 & x < 1.4] <- 1
prediction[x <= 1.25] <- 0
return(factor(prediction, levels = c("1", "0"))) # prediction is either 0 or 1
}
spam_classifier_simple <- function(x){
prediction <- rep(NA, length(x)) # initialize prediction vector
prediction[x > 4] <- 1
prediction[x <= 4] <- 0
return(factor(prediction, levels = c("1", "0"))) # prediction is either 0 or 1
}
a<-c(1:10)
spam_classifier_simple(a)
# Apply spam_classifier to emails_full: pred_full
pred_full<-spam_classifier(a)
# Build CONFUSION MATRIX
conf_full <- table(a, pred_full)
# Calculate the ACCURACY
acc_full <- sum(diag(conf_full)) / sum(conf_full)
# Print out ACCURACY
acc_full
<file_sep>/house_price_forecast.R
#Directorio de trabajo
setwd("C:/Users/Albert/Desktop/R Studio")
###------- Starting a machine learning project ---------###
###------- ( Regression Tree )---------###
#Packages
# utility functions
library("tidyverse")
# for regression trees
library(rpart)
# for random forests
library(randomForest)
#Read the data from a table and visualize
data<-read.csv("../train.csv")
summary(data)
names(data)
nrow(data)
ncol(data)
#Defining model (regression tree)
fit<- rpart(SalePrice~LotArea+YearBuilt, data=data)
plot(fit, uniform=TRUE)
text(fit, cex=.6)
#Predictions based on model
print("Predictions for the following 5 houses")
print(head(data))
print("The predictions are")
print(predict(fit, head(data)))
print("Actual price")
print(head(data$SalePrice))
#Measuring model accuracy
library("modelr")
#Getting the mean average error (MAE). On average, our predictions are off by about X.
mae(model=fit, data=data)
#We HAVE TO separate data into testing an training data.
#To split data we can use this function from modelr library
splitdata<-resample_partition(data, c(test=0.3, train=0.7))
#how many cases are in test and training set?
lapply(splitdata, dim)
#Fitting a new model to our trainig data
fit2<- rpart(SalePrice~LotArea+YearBuilt, data=splitdata$train)
mae(model=fit2, data=splitdata$test)
###------- ( Random forest )---------###
fitRandomForest <- randomForest(SalePrice~LotArea+YearBuilt, data=splitdata$train)
mae(model=fitRandomForest, data=splitdata$train)
#Competition between models adding more variables (añadiendo más variables los modelos se vuelven peores)
fit2<- rpart(SalePrice~LotArea+YearBuilt+HouseStyle+BedroomAbvGr+GarageCars, data=splitdata$train)
mae(model=fit2, data=splitdata$train)
fitRandomForest <- randomForest(SalePrice~LotArea+YearBuilt+HouseStyle+BedroomAbvGr+GarageCars, data=splitdata$train)
mae(model=fitRandomForest, data=splitdata$train)
# Predict values in test set
pred <- predict(fitRandomForest, newdata=splitdata$test)
head(pred)
<file_sep>/CUDA.rmd
---
title: "GPU Programming"
author: "<NAME> and <NAME>"
date: "Parallel programming, 22th January 2019"
output: pdf_document
fontsize: 12pt
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# 1. Introduction
Until now we have been working on paralellization using the capabilities of the CPU, however it is not the only device in a standard computer capable to perform mathematical operations. For this assignment, we are going to use NVIDIA GPU to parallelize our processes. In order to perform this, we are going to use some pragmas comming from CUDA libraries, which will tell to the compiler which parts of the code should go to the GPU instead of going to the CPU.
# 2. OpenACC on the Jacobi Method Algorithm.
Our first interaction with GPU parallelization will be testing the well known Jacobi Algorithm. The first task will be a comparison of performance between a CPU execution against a GPU using different matrix dimensions.
First of all we are asked to perform the CPU accelerated version using a benchmark matrix size of $n=1000$ and $n=4000$.
```{r echo=FALSE, fig.align = "center", message=FALSE, warning=FALSE}
library(tidyverse)
library(ggplot2)
CPU_GPU<-c("CPU","GPU","CPU","GPU")
Matrix_Dimension<-c(1000,1000,4000,4000)
Iterations<-c(5000,5000,5000,5000)
#Traces<-c(250,250,50,50)
Elapsed_Time<-c(0.446201, 1.45692,33.157,3.4)
Error<-c(0.000997877, 0.000997877,1.26637,1.26637)
Convergence<-c(4448, 4448,5000,5000)
first_opt<-cbind(CPU_GPU,Matrix_Dimension,Iterations,Elapsed_Time,Error)
names(first_opt) <- c("CPU/GPU","n size", "iterations", "execution time (s)", "error")
knitr::kable(first_opt)
```
Results for these first exepriments where quite expected, since increasing the complexity by a factor of x4 the execution time increased by a factor of x75. In the other side, the accelerated version by GPU using the OpenACC implementation for a matrix size of $n=1000$ spent three times more the time used by the CPU version. That was a bit surprising because even we know it's a small size problem we expected to get at least a little improvement in executing times. Such a poor performance can be analyzed using the Nvidia graphics, and we can see there is so much time spent initiallizing and closing CUDA in comparison to the time spent in executing the body of the program.
```{r echo=FALSE,out.width = "80%", fig.align = "center"}
setwd("C:/Users/Albert/Desktop/Data Science/Paralel programming")
#setwd("/home/faraday/HD-linux/ownCloud/Documents/Master/PP/CUDA/Markdown")
knitr::include_graphics('1000.png')
```
It seems like in low complex computation problems, there is more time opening and closing CUDA module and there is no benefit in using the a GPU parallelization of the algorithm. However, when increasing the complexity by a factor of x4, time spent is reduced by a magnitude we have never seen neither using OpenMP or MPI parallelizations. Such an improvement in execution times when increasing the complexity of the problem is not that much clear when making the visualizations. In fact, the complexity magnitude of this algorithm even with a matrix size of $n=4000$ is not enough to really appreaciate the capacity of GPU programming.
```{r echo=FALSE,out.width = "80%", fig.align = "center"}
knitr::include_graphics('4000.png')
```
# 3. OpenACC on the Heat transfer.
In this part we have applied the same methodology as the last one but on the Heat transfer problem. The script provided simulates the heat transfer along a metal bar with the temperature at the boundary points being fixed. This phenomena can be modeled with the following partial diferential equation:
$$ \alpha \dfrac{\delta ^2T_{(x,t)}}{\delta ^2 x} = \dfrac{\delta T_{(x,t)}}{\delta t} $$
This expression is known as Fourier law, and its parameters are temperature ($T$), position ($x$), time ($t$) and thermal diffusivity ($\alpha$), which deppends on the material. This PDE can be computed analitically using finite differences method, this method approximates the derivative of a function in the following way:
$$\dfrac{\delta y_{(a)}}{\delta t} \simeq \dfrac{y_{(a+h)}-y_{(a)}}{h}$$
With all of this, the way to solve the heat transfer problem is using an array of N elements which represents the points of the metal bar, so for a single point,the next time step can be computed as a function of its neighbours and itself. This new element is an stencil that uses a value U[x] and its two neighbors.
As we have an stencil, we can parallelize the whole process as we did with the Jacobi Method Algorithm.
## Implementation of OpenACC.
As it has been done in the previous section, we have implemented some pragmas in the baseline code in order to tell to the GPU to perform the computations in parallel. In the following pharagraphs, we will explain what we have been doing with the code and what does it mean all these implementations.
```{}
L2 = (1.0f-2.0f*L);
#pragma acc data copyin(U1[:(N+2)],U2[:(N+2)])
for (t=1; t<=T; t++){ // loop on time
```
Here we introduced the first pragma clause, which tells the GPU to copy arrays U1 and U2 from the host to the device in order to prepare the parallelisation process.
```{}
if ((t&1) == 1){ // t is odd
#pragma acc kernels loop independent
for (x=1; x<=N; x++) // loop on 1D bar
U2[x] = L2*U1[x] + L*U1[x+1] + L*U1[x-1];}
else{ // t is even
#pragma acc kernels loop independent
for (x=1; x<=N; x++) // loop on 1D bar
U1[x] = L2*U2[x] + L*U2[x+1] + L*U2[x-1];}
```
Then the time loop starts, when t is odd, we tell to the compiler to parallelize the for loop in order to compute the stencil. The same happens when t is even. Notice that this two processes cannot be computed in parallel since we need the information stored in U2 before updating the new U1 array.
```{}
if ((t&1) == 1)
{
if (N<=100)
printV(U1,N);
else
{
S = 0.0;
#pragma acc kernels loop independent
for ( x=0; x<=N+1; x++) // compute checksum of final state
S = S + U1[x];
//printf("\nCheckSum = %1.10e\n", S);
}
}
else
{
if (N<=100)
printV(U2,N);
else
{
S=0.0;
#pragma acc kernels loop independent
for ( x=0; x<=N+1; x++) // compute checksum of final state
S = S + U2[x];
//printf("\nCheckSum = %1.10e\n", S);
}
```
Finally we tell the compiler the same as before but, to compute the checksum of both cases, when t is odd and even. This pragma implies an implicit reduction of S, which is desirable for our porpuses.
Once this implementations have been done, we can compile and perform our analysis over CPU and GPU.
## Performance analysis with L fixed.
Here we have our performances fixing $L=0.001234$ and $N=10^7$ to compare execution times with different Times sizes in CPU vs GPU:
```{r echo=FALSE, fig.align = "center", message=FALSE, warning=FALSE}
#Version with N fixed
N_fix <-c(1e7,1e7,1e7,1e7,1e7)
L <-c(0.001234,0.001234,0.001234,0.001234,0.001234)
T_step_Nfix <-c(1000,2000,4000,8000,16000)
Elapsed_Time_CPU_Nfix<-c(10.59,21.12,42.62,85.22,169.13)
S_Checksum_CPU_Nfix <-c(2.9185,3.4178,4.1387,5.1678,6.6300)
Elapsed_Time_GPU_Nfix<-c(1.25,1.99,3.40,6.26,12.01)
S_Checksum_GPU_Nfix <-c(2.9185,3.4178,4.1387,5.1678,6.6300)
ratio_CPU_GPU_Nfix <- Elapsed_Time_CPU_Nfix/Elapsed_Time_GPU_Nfix
second_opt<-cbind(T_step_Nfix,Elapsed_Time_CPU_Nfix,Elapsed_Time_GPU_Nfix,ratio_CPU_GPU_Nfix,S_Checksum_CPU_Nfix,S_Checksum_GPU_Nfix)
colnames(second_opt) <- c("T","CPU Time (s)", "GPU Time (s)","Ratio GPU vs CPU", "Checksum CPU","Checksum GPU")
knitr::kable(second_opt)
```
And performances fixing the $T=1000$ and $L=0.001234$ to compare execution times between CPU and GPU changing the size of N.
```{r echo=FALSE, fig.align = "center", message=FALSE, warning=FALSE}
#Version with T fixed
N_Tfix <-c(1e7,2*1e7,4*1e7,8*1e7,16*1e7)
L_Tfix <-c(0.001234,0.001234,0.001234,0.001234,0.001234)
T_step <-c(2000,2000,2000,2000,2000)
Elapsed_Time_CPU_Tfix<-c(21.12,42.36,84.59,167.69,332.71)
S_Checksum_CPU_Tfix <-c(3.4178,3.4178,3.4178,3.4178,3.4178)
Elapsed_Time_GPU_Tfix<-c(1.99,3.07,5.06,9.37,18.00)
S_Checksum_GPU_Tfix <-c(3.4178,3.4178,3.4178,3.4178,3.4178)
ratio_CPU_GPU_Tfix <- Elapsed_Time_CPU_Tfix/Elapsed_Time_GPU_Tfix
third_opt<-cbind(N_Tfix,Elapsed_Time_CPU_Tfix,Elapsed_Time_GPU_Tfix,ratio_CPU_GPU_Tfix,S_Checksum_CPU_Tfix,S_Checksum_GPU_Tfix)
colnames(third_opt) <- c("N","CPU Time(s)", "GPU Time(s)","Ratio GPU/CPU", "Checksum CPU","Checksum GPU")
knitr::kable(third_opt)
```
The best option to realise time performances from the executions above is with bar plots with all performance times and comparing them when changing parameters:
```{r echo=FALSE, out.width = "80%", fig.align = "center", message=FALSE, warning=FALSE}
library(ggplot2)
library(tidyverse)
library(reshape2)
df1 <- data.frame(log(Elapsed_Time_CPU_Nfix), log(Elapsed_Time_GPU_Nfix), T_step_Nfix)
df2 <- melt(df1, id.vars='T_step_Nfix')
ggplot(df2, aes(x=log2(T_step_Nfix), y=value, fill=variable)) +
geom_bar(stat='identity', position='dodge')+
xlab("Log(N) in base 2") +
ylab("log Time elapsed") +
ggtitle("Execution times CPU vs GPU N fixed")+
theme_minimal()
```
The figure above shows the logarithmic time elapsed of the CPU vs the GPU with different sizes of N (with logarithm in base 2 for better visualization). We observe that an increase of N implies also an increase of time spent by the machine doing its computations, but the host spends more time than the device. Notice that the time and N dimension in this figure is rescaled in a logaritmic way, so actually the improvement of the GPU is greater. We can observe the same thing when the we fix T and let N vary:
```{r echo=FALSE, out.width = "80%", fig.align = "center", message=FALSE, warning=FALSE}
df3 <- data.frame(log(Elapsed_Time_CPU_Tfix), log(Elapsed_Time_GPU_Tfix), N_Tfix)
df4 <- melt(df3, id.vars='N_Tfix')
ggplot(df4, aes(x=log2(N_Tfix), y=value, fill=variable)) +
geom_bar(stat='identity', position='dodge')+
xlab("Log(N) in base 2") +
ylab("log Time elapsed") +
ggtitle("Execution times CPU vs GPU T fixed")+
theme_minimal()
```
Finally, the following two figures show performances as a ratio between GPU and CPU:
```{r echo=FALSE, out.width = "80%", fig.align = "center", message=FALSE, warning=FALSE}
df1 <- data.frame(ratio_CPU_GPU_Nfix, T_step_Nfix)
ggplot(df1, aes(x=log2(T_step_Nfix), y=ratio_CPU_GPU_Nfix)) +
geom_bar(stat='identity', position='dodge')+
xlab("Time step increase") +
ylab("Improvement ratio GPU over CPU") +
ggtitle("Improvement growth with N fixed")+
theme_minimal()
df2 <- data.frame(ratio_CPU_GPU_Tfix, N_Tfix)
ggplot(df2, aes(x=log2(N_Tfix), y=ratio_CPU_GPU_Tfix)) +
geom_bar(stat='identity', position='dodge')+
xlab("Number of points N increase") +
ylab("Improvement ratio GPU over CPU") +
ggtitle("Improvement growth with T")+
theme_minimal()
```
The last figure quantifies the improvement of the device over the host while Time step (T) increases. We observe a logaritmic-like improvement over T, where seems that the performance won't increase much more than 14x times approximately, but a further analysis has to be done in order to find the maximum increase of performance. The same pattern appears when whe fix T and we increase the number of points of the metal bar (N), the maximum improvement we have obtained for this experiment was 18x but like the case where N is fixed, a more detailed analysis has to be done in order to find the limit for the improvement.
This improvement was expected since the GPU is able to perform more computations than the CPU per second. This is because they are able to execute hundreds of thousands of threads of execution simultaneously, while the CPU computing units are usually made for high-level control tasks, and for inherently sequential algorithms. However, at some point when the complexity is high enough the ratio of improvement GPU over CPU remains constant because both device and host have achieved the maximum work load.
## Graphic visualization
Once we have done the time analysis of the GPU over the CPU using information about perf stat and time execution of the program, now is time to take a look at the visual profiler using Gantt Diagram. This diagram provides information about the time spent in each part of the execution, such as memory copies from host to device and viceversa or computation steps. For this part we took a look at a case wich had the following parameters : ($T = 100$ $N = 10e7$ $L = 0.001234$)
```{r echo=FALSE,out.width = "80%", fig.align = "center"}
knitr::include_graphics('100_10e7_heattransfer.png')
knitr::include_graphics('100_10e7_heattransfer_zoom.png')
```
We can observe that for this case, the program spends too much time initialising and ending tasks, and there is some relevant time copying data from device to host. If we take a closer look, we observe how the memcopy from host to device presents an irregular pattern.
After this, the task is performed in two different parts. We can distinguish bettween the clauses in lines 64 and 68, which correspond to the computation of the stencil, and the clauses in lines 79 and 92, which correspond to the computation of S. Notice this two steps take almost the same amount of time.
Also, we can observe two other traces in lines 80 and 93, which correspond to the implicit reduction by the kernel when S is computed.
Notice how the execution of the kernels present a "stairs-like" shape. This is because all kernels are inside an if clause, which depend on the value of t. The ideal case would be that all kernels execute in a parallel way, or at least, without having these huge gaps in between.
The first advice we can observe is shown in the **results** visualization below, which tell us the following: First, there is a low memcpy/compute overlap, which means there are too much copies from the host to the device compared with the computation time. Second, we have low kernel concurrency, which means that we can rewrite the code in order to perform the execution of several kernels together. Third, there is also low memcpy overlap, showing again how the data transmition from host to device could be improved. And finally, there is a low compute utilization, which simply means the computation work load is small. This could be improved increasing the number of iterations in the problem, but if we do so, the time spent for the sbatch to write the traces and analysis files would take too much time.
This tool also provides us a detailed analysis of individual kernels. Lets take a look at the kernel corresponding to the computation of U2, which takes place at line 64:
```{r echo=FALSE,out.width = "80%", fig.align = "center"}
knitr::include_graphics('kernel_1_analysis.png')
```
The figure above shows how the memory of the device is too much used. The bar chart shows how the computation part is mainly divided in arithmetic operations and memory operations. In an ideal case, the device should be only performing arithmetic operations. Also we can read what the tool says: *Kernel Performance is bound by memory bandwigth*, which means that in this step the kernel is limited by the memory accesses.
If we also take a look at the kernel corresponding to the computation of the first checksum (S), we observe the following:
```{r echo=FALSE,out.width = "80%", fig.align = "center"}
knitr::include_graphics('kernel_2_analysis.png')
```
In this case, the compute utilization is higher than the last one, but again we have some troubles with memory. Now the problem is the latency, this means that the performance of this kernel is limited not by the accesses to the memory but the time spent while the kernel ask to the memory for receiving the input it should be computed.
All in all, it seems that this program could be improved if we change the kernels for other ones that deal with the memory and arithmetic operations in a better way. Also, there are other modifications we could implement in the code, such as avoiding time blocking, or rewritting the code in more efficient way.
#4. Conclusions
In this assignment we have learnt how to parallelize two algorithms using the GPU. In both we can see a time performance improvement when increasing the complexity of the algorithms by increasing the sizes of the problem. Actually, the more independent loops are in the algorithm, the more improvement we get when parallelizing into GPU, given the advantage the GPU over CPU in high frequency tasks. However, size of our problems wheren't big enough to appreciate the full potential of GPU parallelization, because in both cases there is more time spent in opening and closing CUDA than time spent in the main body of both algorithms.
Also we want to add that we didn't add any modifications to the program but the necessaries in order to include the openACC directives. So we would expect to get a better performance if we add those modifications or if we rewrite the code in a more efficient way.
<file_sep>/maps.R
# https://www.r-graph-gallery.com/180-change-background-in-leaflet-map/
###################################################################
############ Barcelona Latitude = 41.3597, Longitude = 2.2566
############ Other map "Esri.WorldImagery"
# Load libraries
library(shiny)
library(leaflet)
plastic<-read.table(".../barcelona_plastic.csv", header = TRUE, sep = ",")
data<-plastic[ which(plastic$year==0 & plastic$month==0), ]
data2<-plastic[ which(plastic$year==0 & plastic$month==2), ]
data4<-plastic[ which(plastic$year==0 & plastic$month==4), ]
data6<-plastic[ which(plastic$year==0 & plastic$month==6), ]
data8<-plastic[ which(plastic$year==0 & plastic$month==8), ]
data10<-plastic[ which(plastic$year==0 & plastic$month==10), ]
data12<-plastic[ which(plastic$year==1 & plastic$month==0), ]
data24<-plastic[ which(plastic$year==2 & plastic$month==0), ]
data36<-plastic[ which(plastic$year==3 & plastic$month==0), ]
# Make data with several positions
data_plastic=data.frame(LONG=data$lng, LAT=data$lat, PLACE=paste("Plastic"), PROB=data$probability)
data_plastic2=data.frame(LONG=data2$lng, LAT=data2$lat, PLACE=paste("Plastic2"),PROB=data2$probability )
data_plastic4=data.frame(LONG=data4$lng, LAT=data4$lat, PLACE=paste("Plastic4"),PROB=data4$probability )
data_plastic6=data.frame(LONG=data6$lng, LAT=data6$lat, PLACE=paste("Plastic6"),PROB=data6$probability )
data_plastic8=data.frame(LONG=data8$lng, LAT=data8$lat, PLACE=paste("Plastic8"),PROB=data8$probability )
data_plastic10=data.frame(LONG=data10$lng, LAT=data10$lat, PLACE=paste("Plastic10"),PROB=data10$probability )
data_plastic12=data.frame(LONG=data12$lng, LAT=data12$lat, PLACE=paste("Plastic12"),PROB=data12$probability )
data_plastic24=data.frame(LONG=data24$lng, LAT=data24$lat, PLACE=paste("Plastic24"),PROB=data24$probability )
data_plastic36=data.frame(LONG=data36$lng, LAT=data36$lat, PLACE=paste("Plastic36"),PROB=data36$probability )
# Initialize the leaflet map:
leaflet() %>%
setView(lng=14, lat=42, zoom=5 ) %>%
# Add two tiles
addProviderTiles("NASAGIBS.ViirsEarthAtNight2012", group="background 1") %>%
#addTiles(options = providerTileOptions(noWrap = TRUE), group="background 1") %>%
# Add 2 marker groups
addCircleMarkers(data=data_plastic, lng=~LONG , lat=~LAT, radius=20 , color="", fillColor="white", stroke = TRUE, fillOpacity = 0.8, group="1st month") %>%
addCircleMarkers(data=data_plastic2, lng=~LONG , lat=~LAT, radius=~sqrt(PROB)*20 , color="", fillColor="white", stroke = TRUE, fillOpacity = 0.8, group="2nd month") %>%
addCircleMarkers(data=data_plastic4, lng=~LONG , lat=~LAT, radius=~sqrt(PROB)*20 , color="", fillColor="white", stroke = TRUE, fillOpacity = 0.8, group="4th month") %>%
addCircleMarkers(data=data_plastic6, lng=~LONG , lat=~LAT, radius=~sqrt(PROB)*20 , color="", fillColor="white", stroke = TRUE, fillOpacity = 0.8, group="6th month") %>%
addCircleMarkers(data=data_plastic8, lng=~LONG , lat=~LAT, radius=~sqrt(PROB)*20 , color="", fillColor="white", stroke = TRUE, fillOpacity = 0.8, group="8th month") %>%
addCircleMarkers(data=data_plastic10, lng=~LONG , lat=~LAT, radius=~sqrt(PROB)*20 , color="", fillColor="white", stroke = TRUE, fillOpacity = 0.8, group="10th month") %>%
addCircleMarkers(data=data_plastic12, lng=~LONG , lat=~LAT, radius=~sqrt(PROB)*20, color="", fillColor="white", stroke = TRUE, fillOpacity = 0.8, group="1st year") %>%
addCircleMarkers(data=data_plastic24, lng=~LONG , lat=~LAT, radius=~sqrt(PROB)*20, color="", fillColor="white", stroke = TRUE, fillOpacity = 0.8, group="2nd year") %>%
addCircleMarkers(data=data_plastic36, lng=~LONG , lat=~LAT, radius=~sqrt(PROB)*20, color="", fillColor="white", stroke = TRUE, fillOpacity = 0.8, group="3rd year") %>%
# Add the control widget
addLayersControl(baseGroups = c("1st month","2nd month","4th month","6th month","8th month","10th month","1st year", "2nd year","3rd year"), options = layersControlOptions(collapsed = F))
<file_sep>/Lasso_Ridge _Linear_Regression.R
##### Multiple Regression Chap 3 ISL
## Install packages
install.packages("leaps");install.packages("car");
install.packages("glmnet"); install.packages("plotmo")
install.packages("corrplot") # plotting covariance matrix
## load libraries
require(MASS);require(car)#para el vif
require(glmnet)#lasso y ridge
require(leaps)#subset selection, Cp, AIC, BIC
require(corrplot)
require(plotmo)
###### Data
data("Boston")
names(Boston)
# medv=median house value
attach(Boston)
pairs(Boston)
M=cor(Boston)
corrplot(M, method = "square")
corrplot.mixed(M) #(colormap&values)
hist(Boston$medv,br=50)
modelo1=lm(medv~.,data=Boston) #full-model
summary(modelo1)
vif(modelo1) #cutoff 5 or 10 are usually considered signs of colinearity
modelo2=update(modelo1,~.-tax)
summary(modelo2)
modelo3=update(modelo1,~.-age)
summary(modelo3)
saic=stepAIC(modelo1)
plot(saic)
######### seleccion de modelos
stepAIC(modelo1)
fit.full=regsubsets(medv~.,data=Boston)
summary(fit.full) #max 8 predictors , change it with nvmax=...
summary.fit.full=summary(fit.full)
names(summary.fit.full)
summary.fit.full$cp # proportional to AIC
summary.fit.full$bic
summary.fit.full$adjr2
## All criteria choose model 8
fit.full.larger=regsubsets(medv~.,data=Boston,nvmax=13)
summary.fit.full.larger=summary(fit.full.larger)
summary.fit.full.larger$cp #mod 11
summary.fit.full.larger$bic #mod 11
summary.fit.full.larger$adjr2 #mod 11
par(mfrow=c(2,2))
plot(summary.fit.full.larger$cp,xlab="Number of variables",ylab="Cp", type="b",col="darkblue",lwd=2)
plot(summary.fit.full.larger$bic,xlab="Number of variables",ylab="BIC", type="b",col="darkcyan",lwd=2)
plot(summary.fit.full.larger$adjr2,xlab="Number of variables",ylab="RSSadj", type="b",col="darkblue",lwd=2)
### a particular plot from regsubsets:
par(mfrow=c(1,1))
#squares indicate which variable is present
plot(fit.full.larger, scale="adjr2", col="darkcyan")
plot(fit.full.larger, scale="bic", col="maroon4")
plot(fit.full.larger, scale="Cp", col="dodgerblue2")
###### forward selection
forward=regsubsets(medv~.,data=Boston,nvmax=13,method="forward")
summary(forward)
stepAIC(modelo1)
######### how do we choose among these models????? Cross-validation (later)
########## LASSO lambda is chosen with CV as well... train/validate
## in order to split the data, put it in vector Y matrix X
library(plotmo) # for plot_glmnet
set.seed(115) #to get always the same results
x=model.matrix(medv~.,data=Boston)[,-1]
y=Boston$medv
train=sample(1:nrow(x),nrow(x)/2)
test=(-train)
y.test=y[test]
lasso.mod=glmnet(x[train,], y[train],alpha=1,standardize=TRUE) #alpha=1:lasso
plot(lasso.mod, label=TRUE,lwd=2)
print(lasso.mod) ## nr. predictors, % deviance , Lambda
### choosing lambda with corssvalidation
cv.out =cv.glmnet (x[train ,],y[train],alpha =1)
plot(cv.out)
bestlam =cv.out$lambda.min;bestlam ## might be too conservative
## try also
bestlam =cv.out$lambda.1se;bestlam
lasso.pred=predict (lasso.mod ,s=bestlam ,newx=x[test ,])
mean((lasso.pred -y.test)^2)
out=glmnet (x,y,alpha =1) #### with all data
lasso.who=predict(out,type="nonzero",s=bestlam);lasso.who # regressors at chosen lambda
lasso.coef=predict (out,type="coefficients",s=bestlam )[1:13,]
lasso.coef
#### other training proportion
train2=sample(1:nrow(x),2*nrow(x)/3)
test2=(-train2)
y2.test=y[test2]
cv.out =cv.glmnet (x[train2,],y[train2],alpha =1)
plot(cv.out)
bestlam =cv.out$lambda.min;bestlam
out=glmnet (x,y,alpha =1) #### with all data
lasso.coef=predict (out,type="coefficients",s=bestlam )[1:13,]
lasso.coef
############### mtcars (far away from "big" data)
data(mtcars)
correlations=cor(mtcars)
corrplot(correlations, method = "square")
corrplot.mixed(correlations) #(colormap&values)
round(correlations,2)
modelo=lm(mpg~., data=mtcars)
summary(modelo)
anova(modelo)
x=as.matrix(mtcars[-1])
# cyl disp hp drat wt qsec vs am gear carb
y=mtcars[,1]
mod=glmnet(as.matrix(mtcars[-1]),as.matrix(mtcars[,1]),standardize=T,alpha=1)
mod=glmnet(x,y,standardize=T,alpha=1)
plot.glmnet(mod,label=T,lwd=2)
#mod=glmnet(as.matrix(x),y,standardize=T,alpha=1)
plot.glmnet(mod, label=T, lwd=2, xvar="norm") # default colors
plot.glmnet(mod, label=5) # label the 5 biggest final coefs
######choosing lambda
#### not mandatory to separate train/test
train=sample(1:nrow(x),nrow(x)*0.66)
test=(-train)
y.test=y[test]
cv.out =cv.glmnet (as.matrix(x[train,]),y[train],alpha =1,nfold=5,standardize=T)
plot(cv.out) # dotted line on the left min cv-error, right error within 1 stdev from min
bestlam =cv.out$lambda.1se;bestlam
out=glmnet(x,y,alpha =1) #### with all data, no standarization
plot(out,xvar = "lambda", label = TRUE)
plot(out,xvar = "dev", label = TRUE) # -loglik
features=predict (out,type="nonzero",s=bestlam );features
coef=predict (out,type="coefficients",s=bestlam )
## choose a model with 3 variables: 5 (wt) 1(cyl) and 3 (hp)
## take a look at coef paths
lasso.coef=predict (out,type="coefficients",s=bestlam)[1:10,]
length(lasso.coef[lasso.coef!=0])
lasso.coef
########### with lars
install.packages("lars");
require(lars)
lars=lars(as.matrix(mtcars[-1]),mtcars$mpg,type="lasso")
lars
cv=lars::cv.lars(as.matrix(mtcars[-1]),mtcars$mpg,plot.it=T)
####################### SIMMULATED DATA
####################### p >> n
## model: Y=Xbeta+error, beta=(1,...,1,0,....,0) number of 1s=real_p
##
set.seed(19875)
n=1000 # Number of observations
p=5000 # Number of predictors included in model
####### in this setting, small signal and big i.i.d. noise
real_p=15 # Number of true predictors
x=matrix(rnorm(n*p), nrow=n, ncol=p)
y=apply(x[,1:real_p], 1, sum) + rnorm(n)
# Split data into train and test sets
train_rows <- sample(1:n, .66*n)
x.train <- x[train_rows, ]
x.test <- x[-train_rows, ]
y.train <- y[train_rows]
y.test <- y[-train_rows]
fit.lasso=glmnet(x.train, y.train, family="gaussian", alpha=1)
fit.lasso.cv=cv.glmnet(x.train, y.train, type.measure="mse", alpha=1,family="gaussian")
plot.cv.glmnet(fit.lasso.cv)
bestlam =fit.lasso.cv$lambda.1se;bestlam
coef=coef.cv.glmnet(fit.lasso.cv)
sum(coef!=0)
lasso.coef=predict (fit.lasso,type="coefficients",s=bestlam)#[1:5000,]
length(lasso.coef[lasso.coef!=0])
lasso.who=predict(fit.lasso,type="nonzero",s=bestlam);lasso.who
##predictions on test set
y.hat=predict(fit.lasso, s=bestlam, newx=x.test)
mse=mean((y.test - y.hat)^2)
##Lasso mse should be smaller than Ridge or elastic net in this case
fit.ridge=glmnet(x.train, y.train, family="gaussian", alpha=0)
fit.ridge.cv=cv.glmnet(x.train, y.train, type.measure="mse", alpha=0,family="gaussian")
plot.cv.glmnet(fit.ridge.cv)
bestlam.ridge =fit.ridge.cv$lambda.1se;bestlam.ridge
coef=coef.cv.glmnet(fit.ridge.cv)
sum(coef!=0)
ridge.coef=predict (fit.ridge,type="coefficients",s=bestlam.ridge)
##predictions on test set
y.hat.ridge=predict(fit.ridge, s=bestlam.ridge, newx=x.test)
mse=mean((y.test - y.hat.ridge)^2)
######### Other Scenarios.
#big signal, big i.i.d noise
real_p=1500
x=matrix(rnorm(n*p), nrow=n, ncol=p)
y=apply(x[,1:real_p], 1, sum) + rnorm(n)
train_rows <- sample(1:n, .66*n)
x.train <- x[train_rows, ]
x.test <- x[-train_rows, ]
y.train <- y[train_rows]
y.test <- y[-train_rows]
fit.lasso=glmnet(x.train, y.train, family="gaussian", alpha=1)
fit.lasso.cv=cv.glmnet(x.train, y.train, type.measure="mse", alpha=1,family="gaussian")
plot.cv.glmnet(fit.lasso.cv)
bestlam =fit.lasso.cv$lambda.min;bestlam
coef=coef.cv.glmnet(fit.lasso.cv)
sum(coef!=0)
lasso.coef=predict (fit.lasso,type="coefficients",s=bestlam)#[1:5000,]
length(lasso.coef[lasso.coef!=0])
lasso.who=predict(fit.lasso,type="nonzero",s=bestlam);lasso.who
##predictions on test set
y.hat=predict(fit.lasso, s=bestlam, newx=x.test)
mse.lasso=mean((y.test - y.hat)^2)
##Lasso mse should be smaller than Ridge or elastic net in this case
fit.ridge=glmnet(x.train, y.train, family="gaussian", alpha=0)
fit.ridge.cv=cv.glmnet(x.train, y.train, type.measure="mse", alpha=0,family="gaussian")
plot.cv.glmnet(fit.ridge.cv)
bestlam.ridge =fit.ridge.cv$lambda.1se;bestlam.ridge
coef=coef.cv.glmnet(fit.ridge.cv)
sum(coef!=0)
ridge.coef=predict (fit.ridge,type="coefficients",s=bestlam.ridge)
##predictions on test set
y.hat.ridge=predict(fit.ridge, s=bestlam.ridge, newx=x.test)
mse=mean((y.test - y.hat.ridge)^2)
####### Ridge is slightly better
##Varying signals. High correlation between predictors
## β=(10,10,5,5,rep(1,10),rep(0,36))
##
library(MASS)
p=50
n=100
##Correlated predictors: Cov(X)ij=(0.7)|i−j|
CovMatrix <- outer(1:p, 1:p, function(x,y) {.7^abs(x-y)})
x <- mvrnorm(n, rep(0,p), CovMatrix)
y <- 10 * apply(x[, 1:2], 1, sum) +
5 * apply(x[, 3:4], 1, sum) +
apply(x[, 5:14], 1, sum) +
rnorm(n)
# Split data into train and test sets
train_rows <- sample(1:n, .66*n)
x.train <- x[train_rows, ]
x.test <- x[-train_rows, ]
y.train <- y[train_rows]
y.test <- y[-train_rows]
# Fit models:
fit.lasso <- glmnet(x.train, y.train, family="gaussian", alpha=1)
fit.ridge <- glmnet(x.train, y.train, family="gaussian", alpha=0)
fit.elnet <- glmnet(x.train, y.train, family="gaussian", alpha=.5)
fit.lasso.cv <- cv.glmnet(x.train, y.train, type.measure="mse", alpha=1,
family="gaussian")
fit.ridge.cv <- cv.glmnet(x.train, y.train, type.measure="mse", alpha=0,
family="gaussian")
fit.elnet.cv <- cv.glmnet(x.train, y.train, type.measure="mse", alpha=.5,
family="gaussian")
coef.lasso=coef.cv.glmnet(fit.lasso.cv)
sum(coef.lasso!=0)
coef.ridge=coef.cv.glmnet(fit.ridge.cv)
sum(coef.ridge!=0)
coef.elnet=coef.cv.glmnet(fit.elnet.cv)
sum(coef.elnet!=0)
bestlam.lasso =fit.lasso.cv$lambda.1se;
bestlam.ridge =fit.ridge.cv$lambda.1se;
bestlam.elnet =fit.elnet.cv$lambda.1se;
y.hat.lasso=predict(fit.lasso, s=bestlam.lasso, newx=x.test)
mse.lasso=mean((y.test - y.hat.lasso)^2);mse.lasso
y.hat.ridge=predict(fit.ridge, s=bestlam.ridge, newx=x.test)
mse.ridge=mean((y.test - y.hat.ridge)^2);mse.ridge
y.hat.elnet=predict(fit.elnet, s=bestlam.elnet, newx=x.test)
mse.elnet=mean((y.test - y.hat.elnet)^2);mse.elnet
######
fit.elnet.cv <- cv.glmnet(x.train, y.train, type.measure="mse", alpha=.03,
family="gaussian")
plot(fit.lasso, xvar="lambda")
plot(fit.ridge, xvar="lambda")
plot(fit.elnet, xvar="lambda")
<file_sep>/quantmod.R
install.packages("quantmod") #Instalem un paquet. Aquest paquest és per importar dades directament, per exemple de yahoo
library(quantmod) #Carreguem el paquet a la sessió
getSymbols("AAPL",from="2012-01-01", to="2018-09-18")
############ descarrega del SP500
SPX <- getSymbols("^GSPC",auto.assign = FALSE, from = "2017-11-01")
library(tidyverse)
SPX<-as.tibble(SPX)
SP500<-select(SPX, GSPC.Adjusted)
write.table(zoo(SP500),"SP500.csv")
x<-c(1:262)
ClosingPrices<-c(SP500$GSPC.Adjusted)
XY<-data.frame(y)
XY[0,1]<-"Closing Prices"
write.table(zoo(XY),"SP500.csv")
############ final de la descarrega
write.table(zoo(AAPL),"AAPL_20120101_20180918.txt") #Guardar les dades al directori de treball en format txt
#####################################################################
#### Si ho preferiu podeu treballar les dades amb Excel
#####################################################################
#####################################################################
#### Exloreu les sèries
#####################################################################
#Podeu representar algunes sèries:
plot(AAPL$AAPL.Adjusted)
plot(AAPL$AAPL.Close)
plot(dailyReturn(AAPL))
plot(volatility(AAPL))
#repetim els gràfics en format millorat
chartSeries(AAPL$AAPL.Adjusted,type = c("auto"),subset = NULL,theme="white",TA=NULL)
chartSeries(volatility(AAPL),type = c("auto"),subset = NULL,theme="white",TA=NULL)
chartSeries(dailyReturn(AAPL),type = c("auto"),subset = NULL,theme="white",TA=NULL)
#####################################################################
#### Si treballem amb excel, els logreturns i les volatilitats poden variar lleugerament
#### ja que usem fórmules diferents.
#### A l'ajut d'R de la funció específica trobareu els detalls de la formulació usada.
#### Si seguim la notació i formulació de classe, podem simplificar les dades de la manera següent:
#####################################################################
t<-as.Date(rownames(zoo(AAPL)))
Pt<-as.numeric(AAPL$AAPL.Close)#Adjusted)
rt<-diff(log(Pt))
datos<-data.frame(t=t[-1],Pt=Pt[-1],rt=rt)
<file_sep>/README.md
# R-scripts
Some useuful R scripts in several different tasks and assignments
<file_sep>/time_series_forecast.R
###### Time series analysis ######
####################################
# Prediction with ARIMA(p,d,q) models: the goal is to discover the best parameters (p,d,q) to fit the ARIMA model.
# These examples are made with simulated time series WITHOUT SEASONALITY !!!
# For exact explanations on how to identify (p,d,q) -> https://people.duke.edu/~rnau/411arim.htm
# -> http://people.duke.edu/~rnau/Slides_on_ARIMA_models--Robert_Nau.pdf
# Let's see a simualted AR(1) time series:
data<-arima.sim(model=list(ar=.7),n=120) # simulate a time series AR(1) of 120 observations
ts.plot(data,col=4) # plot it just to see it
# How can we know the ARIMA(p,q,r) type? By analysing the ACF and PACF.
library(TSA)
par(mfrow=c(1,1))
acf(data) # here we can see the correlation in the second period, so AR(1)
pacf(data)
fit<-arima(data,c(1,0,0)) # fit an ARIMA model with form AR(1)
ts.plot(data,fit$residuals, col=c(1,2)) # the ARIMA(1,0,0) over the simulated sime series and we can see we almost nailed.
predictions<-predict(fit,5) # prediction for the next 5 periods
ts.plot(data,predictions$pred, col=c(1,2)) # prediciton plot
# Now let's do the same with AR(2)
data2<-arima.sim(model=list(ar=c(.7,-0.3)),n=120)
ts.plot(data2,col=4)
# How can we know the ARIMA(p,q,r) type? By analysing the ACF and PACF.
par(mfrow=c(1,1))
acf(data2) # here we can see the correlation in the second period, so AR(2)
pacf(data2)
fit2<-arima(data2,c(2,0,0)) # fit an ARIMA model with form AR(1)
ts.plot(data2,fit2$residuals, col=c(1,2))
predictions2<-predict(fit2,5) # prediction for the next 5 periods
ts.plot(data2,predictions2$pred, col=c(1,2))
# Now let's do the same with MA(1)
data3<-arima.sim(model=list(ma=.5),n=120)
ts.plot(data3,col=4)
# How can we know the ARIMA(p,q,r) type? By analysing the ACF and PACF.
par(mfrow=c(1,1))
acf(data3) # see the tips from the website
pacf(data3)
fit3<-arima(data3,c(0,0,1)) # fit an ARIMA model with form MA(1)
ts.plot(data3,fit3$residuals, col=c(1,2)) # residuals from the model should match the time series
predictions3<-predict(fit3,5) # prediction for the next 5 periods
ts.plot(data3,predictions3$pred, col=c(1,2))
# Example with real data from Car accidents between 1973-1979.
accidents<-ts(read.table("accidents.dat"),start=1973,frequency=12)
ts.plot(accidents)
# Regular differences to eliminate the seasonality/tendency
dserie<-diff(accidents)
par(mfrow=c(1,1))
plot(dserie,col=4)
par(mfrow=c(2,1))
acf(dserie,lag=100)
pacf(dserie,lag=100)
# Seasonality diferences !!!!!!!!!!! (there was some tendency yet)
ddserie<-diff(dserie,lag=12)
par(mfrow=c(1,1))
plot(ddserie,col=4)
par(mfrow=c(2,1))
acf(ddserie,lag=100)
pacf(ddserie,lag=100)
# How can we know the ARIMA(p,q,r) type? By analysing the ACF and PACF.
par(mfrow=c(1,1))
acf(accidents) # see the tips from the website
pacf(accidents)
fit4<-arima(ddserie,c(12,0,0))
ts.plot(ddserie, fit4$residuals, col=c(1,2))
# Analysing residuals => ACF and PACF have to be clean (no spikes outside) !!! Only from (12,0,0) and above
par(mfrow=c(2,1))
acf(fit4$residuals,lag=100)
pacf(fit4$residuals,lag=100)
par(mfrow=c(1,1))
predicitons4<-predict(fit4,5)
ts.plot(ddserie, predicitons4$pred, col=c(4,2))
predicitons4
accidents
library(forecast)
plot(forecast(Arima(y = accidents, order = c(11,0,0)))) # To undo diferences and get the forecast
forecast(Arima(y = accidents, order = c(3,0,0)))
## Spanish unemployment !!!!!!!!!!!!!!!
paro<-read.csv(".../LRHUTTTTESM156S.csv", header = TRUE)
ts.plot(paro$LRHUTTTTESM156S)
paro<-ts(paro$LRHUTTTTESM156S, start = c(1986, 4), frequency=12)
ts.plot(paro)
dparo<-diff(paro)
ts.plot(dparo)
par(mfrow=c(2,1))
acf(dparo,lag=100)
pacf(dparo,lag=100)
ddparo<-diff(dparo, lag=1)
ts.plot(ddparo)
fit5<-arima(ddparo,c(2,1,1), seasonal = list(order=c(0,0,1)))
ts.plot(ddparo, fit5$residuals, col=c(1,2))
# Analysing residuals => ACF and PACF have to be clean (no spikes outside) smallest AIC !!!
AIC(fit5)
par(mfrow=c(2,1))
acf(fit5$residuals,lag=100)
pacf(fit5$residuals,lag=100)
par(mfrow=c(1,1))
predicitons5<-predict(fit5,12)
ts.plot(ddparo, predicitons5$pred, col=c(4,2))
library(forecast)
plot(forecast(Arima(y = paro, order = c(1,1,1),seasonal = list(order=c(0,0,1))))) # To undo diferences and get the forecast
forecast(Arima(y = paro, order = c(2,1,1)))
#plot through ggplot
library(ggplot2)
paro %>%
Arima(order=c(1,1,1), seasonal = c(0,0,1)) %>%
forecast(h=18) %>%
autoplot
<file_sep>/tidyverse.R
install.packages("tidyverse")
## ----install, eval=FALSE-------------------------------------------------
## install.packages(c("tidyverse",
## "nycflights13"))
## ----install_tidyverse, eval=FALSE---------------------------------------
## install.packages("tidyverse")
## ----load_tydiverse------------------------------------------------------
library(tidyverse)
## ----iris----------------------------------------------------------------
head(iris)
## ----create_tible--------------------------------------------------------
iris.tib <- as_tibble(iris) #as_tibble function from tidyverse, the same as data.frames in R
iris.tib
## ----create_new----------------------------------------------------------
tibble(
x = 1:5,
y = 1,
z = x ^ 2 + y
)
## ----change_print--------------------------------------------------------
print(iris.tib, n = 10, width = Inf)
## ----change_print2-------------------------------------------------------
print(iris.tib, n = 10, width = 25)
## ----subsetting----------------------------------------------------------
df <- tibble(
x = runif(5),
y = rnorm(5)
)
# Extract by name
df$x
df[["x"]]
# Extract by position
df[[1]]
## ----compare-------------------------------------------------------------
install.packages("readr")
library(readr) ## if we gonna use just one fucntion from the package, just write ( read::read.delim )
system.time(genom<-read.delim("../genome.txt", header = TRUE, sep = "" ))
dim(genom)
system.time(dd1 <- read.delim("../../data/genome.txt"))
system.time(dd2 <- read_delim("../../data/genome.txt",
delim="\t"))
dim(dd2)
## ----compare_read--------------------------------------------------------
head(dd1)
dd2
## ----load_data-----------------------------------------------------------
library(nycflights13)
library(tidyverse)
## ----show_flights--------------------------------------------------------
flights
## ----filter--------------------------------------------------------------
jan1 <- filter(flights, month == 1, day == 1)
## ----filter2-------------------------------------------------------------
(jan1 <- filter(flights, month == 1, day == 1))
## ----example_boolean1----------------------------------------------------
filter(flights, month == 11 | month == 12)
## ----example_boolean2----------------------------------------------------
filter(flights, !(arr_delay > 120 | dep_delay > 120))
## ----arrange-------------------------------------------------------------
arrange(flights, year, month, day)
## ----arrange2------------------------------------------------------------
arrange(flights, desc(dep_delay))
## ----select--------------------------------------------------------------
select(flights, year, month, day)
## ----select2-------------------------------------------------------------
select(flights, year:day)
## ----select3-------------------------------------------------------------
select(flights, -(year:day))
## ----add_var-------------------------------------------------------------
flights_sml <- select(flights,
year:day,
ends_with("delay"),
distance,
air_time
)
mutate(flights_sml,
gain = dep_delay - arr_delay,
speed = distance / air_time * 60
)
## ----transmute-----------------------------------------------------------
transmute(flights,
gain = dep_delay - arr_delay,
hours = air_time / 60,
gain_per_hour = gain / hours
)
## ----summary-------------------------------------------------------------
summarise(flights, delay = mean(dep_delay, na.rm = TRUE))
## ----summary2------------------------------------------------------------
by_day <- group_by(flights, year, month, day)
summarise(by_day, delay = mean(dep_delay, na.rm = TRUE))
## ----pipe----------------------------------------------------------------
by_dest <- group_by(flights, dest)
delay <- summarise(by_dest,
count = n(),
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE)
)
delay <- filter(delay, count > 20, dest != "HNL")
delay
## ----plot_pipe-----------------------------------------------------------
ggplot(data = delay, mapping = aes(x = dist, y = delay)) +
geom_point(aes(size = count), alpha = 1/3) +
geom_smooth(se = FALSE)
## ----pipe_use------------------------------------------------------------
delays <- flights %>%
group_by(dest) %>%
summarise(
count = n(),
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE)
) %>%
filter(count > 20, dest != "HNL")
delays
## ----group_var-----------------------------------------------------------
flights %>%
group_by(year, month, day) %>%
summarise(
avg_delay1 = mean(arr_delay, na.rm=TRUE),
avg_delay2 = mean(arr_delay[arr_delay > 0], na.rm=TRUE)
)
## ------------------------------------------------------------------------
sessionInfo()
<file_sep>/parallel.R
# Testing parallelizations
library(doParallel)
getDoParWorkers() #testing how many cores are registered
n=100
t = Sys.time()
cl <- makeCluster(2)
registerDoParallel(cl)
foreach(i=1:n) %dopar% {
sqrt(i) }
print(paste0(format(Sys.time()-t,units='hours')))
cl <- makeCluster(4)
registerDoParallel(cl)
getDoParWorkers() #testing how many cores are registered
x <- iris[which(iris[,5] != "setosa"), c(1,5)]
trials <- 100000
ptime <- system.time({
r <- foreach(icount(trials), .combine=cbind) %dopar% {
ind <- sample(100, 100, replace=TRUE)
result1 <- glm(x[ind,2]~x[ind,1], family=binomial(logit))
coefficients(result1)
}
})[3]
ptime
|
550acb02ca8cb71362a4660a2eaff49642e56ff7
|
[
"Markdown",
"R",
"RMarkdown"
] | 11
|
R
|
albertxavierlopez/R-scripts
|
3ca1824e6f2078fafc8a7b8a55e1c11c04bbb31c
|
8780715d4d2da8901426d35d81c3dc8786d8e9a7
|
refs/heads/master
|
<file_sep>#define HTML_HEADER "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n" \
"<html><head><title>Gearman Status</title>\n" \
"<style type='text/css'>\n" \
"body{font-family: 'Trebuchet MS';color: #444;background: #f9f9f9;}\n" \
"h1{background: #eee;border: 1px solid #ddd;padding: 3px;text-shadow: #ccc 1px 1px 0;color: #756857;text-transform:uppercase;}\n" \
"h2{padding: 3px;text-shadow: #ccc 1px 1px 0;color: #ACA39C;text-transform:uppercase;border-bottom: 1px dotted #ddd;display: inline-block;}\n" \
"hr{color: transparent;}\n" \
"table{width: 100%%;border: 1px solid #ddd;border-spacing:0px;}\n" \
"table th{border-bottom: 1px dotted #ddd;background: #eee;padding: 5px;font-size: 15px;text-shadow: #fff 1px 1px 0;}\n" \
"table td{text-align: center;padding: 5px;font-size: 13px;color: #444;text-shadow: #ccc 1px 1px 0;}\n" \
"</style></head><body>\n"
#define HTML_FOOTER "</body></html>"
#define SERVER_INFO "<h1>Gearmn Server Status for %s</h1>\n"
#define WORKERS_TABLE_HEADER "<h2>Workers</h2>\n" \
"<table border='0'><tr><th>File Descriptor</th><th>IP Address</th><th>Client ID</th><th>Function</th></tr>"
#define STATUS_TABLE_HEADER "<h2>Status</h2>\n" \
"<table border='0'><tr><th>Function</th><th>Total</th><th>Running</th><th>Available Workers</th></tr>"
#define CONNECTION_ERROR "Error connecting to Gearman server %s:%d."
<file_sep>#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include "ngx_http_gearman_status_module.h"
typedef struct {
ngx_str_t hostname;
ngx_uint_t port;
} ngx_http_gearman_status_conf_t;
enum task {
TASK_STATUS = 0,
TASK_WORKERS = 1
};
static char *ngx_http_set_gearman_status(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static void *ngx_http_gearman_status_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_gearman_status_merge_loc_conf(ngx_conf_t *cf,
void *parent, void *child);
static ngx_command_t ngx_http_gearman_status_commands[] = {
{
ngx_string("gearman_status"),
NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_http_set_gearman_status,
0,
0,
NULL
},
{
ngx_string("gearman_status_hostname"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_gearman_status_conf_t, hostname),
NULL
},
{
ngx_string("gearman_status_port"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_gearman_status_conf_t, port),
NULL
},
ngx_null_command
};
static ngx_http_module_t ngx_http_gearman_status_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_gearman_status_create_loc_conf,/* create location configuration */
ngx_http_gearman_status_merge_loc_conf /* merge location configuration */
};
ngx_module_t ngx_http_gearman_status_module = {
NGX_MODULE_V1,
&ngx_http_gearman_status_module_ctx, /* module context */
ngx_http_gearman_status_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
int readline(int socket_fd, char *buffer, size_t len)
{
char c;
char *bufx = buffer;
static char *bp;
static int cnt = 0;
static char b[1500];
while (--len > 0) {
if (--cnt <= 0) {
cnt = recv(socket_fd, b, sizeof(b), 0);
if (cnt < 0) {
if (errno == EINTR) {
len++;
continue;
}
return -1;
}
if (cnt == 0)
return 0;
bp = b;
}
c = *bp++;
*buffer++ = c;
if (c == '\n') {
*buffer = '\0';
return buffer - bufx;
}
}
return -1;
}
static inline ngx_chain_t *get_last_chain(ngx_chain_t *c)
{
ngx_chain_t *last = c;
if (last != NULL)
while (last->next != NULL)
last = last->next;
return last;
}
static inline off_t get_content_length(ngx_chain_t *c)
{
off_t l = 0;
while (c != NULL) {
l += ngx_buf_size(c->buf);
c = c->next;
}
return l;
}
static ngx_chain_t *get_header(ngx_http_request_t *r)
{
ngx_buf_t *b;
ngx_chain_t *c;
b = ngx_create_temp_buf(r->pool, sizeof(HTML_HEADER));
if (b == NULL)
return NULL;
c = ngx_pcalloc(r->pool, sizeof(ngx_chain_t));
if (c == NULL)
return NULL;
b->last = ngx_sprintf(b->last, HTML_HEADER);
c->buf = b;
c->next = NULL;
return c;
}
static ngx_chain_t *
get_connection_error(ngx_http_request_t *r, const char *hostname, int port)
{
ngx_chain_t *c;
ngx_buf_t *b;
size_t size;
size = sizeof(CONNECTION_ERROR) + NGX_INT32_LEN + strlen(hostname);
b = ngx_create_temp_buf(r->pool, size);
if (b == NULL)
return NULL;
c = ngx_pcalloc(r->pool, sizeof(ngx_chain_t));
if (c == NULL)
return NULL;
b->last = ngx_sprintf(b->last, CONNECTION_ERROR, hostname, port);
c->buf = b;
c->next = NULL;
return c;
}
static ngx_chain_t *get_footer(ngx_http_request_t *r)
{
ngx_buf_t *b;
ngx_chain_t *c;
b = ngx_create_temp_buf(r->pool, sizeof(HTML_FOOTER));
if (b == NULL)
return NULL;
c = ngx_pcalloc(r->pool, sizeof(ngx_chain_t));
if (c == NULL)
return NULL;
b->last = ngx_sprintf(b->last, HTML_FOOTER);
c->buf = b;
c->next = NULL;
return c;
}
static ngx_chain_t *get_info(ngx_http_request_t *r, int socket_fd, int task)
{
char buffer[50];
char *delim;
char line[128];
char *token;
int i, j = 0;
ngx_buf_t *b;
ngx_chain_t *c;
size_t size;
size_t size_per_row;
if (task == TASK_WORKERS) {
size = sizeof(WORKERS_TABLE_HEADER);
size_per_row = sizeof("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>");
sprintf(buffer, "workers\n");
delim = " ";
} else {
size = sizeof(STATUS_TABLE_HEADER);
size_per_row = sizeof("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>");
sprintf(buffer, "status\n");
delim = "\t";
}
write(socket_fd, buffer, strlen(buffer));
while (readline(socket_fd, line, sizeof(line)) > 0) {
if (line[0] == '.' && line[1] == '\n')
break;
for (i = 0, token = strtok(line, delim); token; token = strtok(NULL, delim), i++) {
if (token == NULL)
break;
size += sizeof(token);
if (task == TASK_WORKERS)
if (i == 3)
continue;
}
j++;
}
size += size_per_row * j;
size += sizeof("</table>");
b = ngx_create_temp_buf(r->pool, size);
if (b == NULL)
return NULL;
c = ngx_pcalloc(r->pool, sizeof(ngx_chain_t));
if (c == NULL)
return NULL;
if (task == TASK_WORKERS)
b->last = ngx_sprintf(b->last, WORKERS_TABLE_HEADER);
else
b->last = ngx_sprintf(b->last, STATUS_TABLE_HEADER);
write(socket_fd, buffer, strlen(buffer));
while (readline(socket_fd, line, sizeof(line)) > 0) {
if (line[0] == '.' && line[1] == '\n')
break;
b->last = ngx_sprintf(b->last, "<tr>");
for (i = 0, token = strtok(line, delim); token; token = strtok(NULL, delim), i++) {
if (token == NULL)
break;
if (task == TASK_WORKERS && i == 3)
continue;
b->last = ngx_sprintf(b->last, "<td>%s</td>", token);
}
b->last = ngx_sprintf(b->last, "</tr>");
}
b->last = ngx_sprintf(b->last, "</table>");
c->buf = b;
c->next = NULL;
return c;
}
static ngx_chain_t *
get_version(ngx_http_request_t *r, int socket_fd, const char *hostname)
{
char buffer[50];
char line[10];
ngx_buf_t *b;
ngx_chain_t *c;
size_t size;
c = ngx_pcalloc(r->pool, sizeof(ngx_chain_t));
sprintf(buffer, "version\n");
write(socket_fd, buffer, strlen(buffer));
if (readline(socket_fd, line, sizeof(line)) > 0) {
size = sizeof(SERVER_INFO) + strlen(hostname) + sizeof("Version: ") + sizeof(line) + sizeof("<hr />");
b = ngx_create_temp_buf(r->pool, size);
if (b == NULL)
return NULL;
if (c == NULL)
return NULL;
b->last = ngx_sprintf(b->last, SERVER_INFO, hostname);
b->last = ngx_sprintf(b->last, "Version: %s", line);
b->last = ngx_sprintf(b->last, "<hr />");
c->buf = b;
c->next = NULL;
} else {
c->buf = NULL;
}
return c;
}
static ngx_int_t ngx_http_gearman_status_handler(ngx_http_request_t *r)
{
int status = 1;
int socket_fd;
ngx_chain_t *fc, *mc, *lc;
ngx_http_gearman_status_conf_t *gscf;
ngx_int_t rc;
struct hostent* hostinfo;
struct sockaddr_in name;
gscf = ngx_http_get_module_loc_conf(r, ngx_http_gearman_status_module);
if (r->method != NGX_HTTP_GET)
return NGX_HTTP_NOT_ALLOWED;
rc = ngx_http_discard_request_body(r);
if (rc != NGX_OK)
return rc;
r->headers_out.content_type.len = sizeof( "text/html; charset=ISO-8859-1" ) - 1;
r->headers_out.content_type.data = (u_char *) "text/html; charset=ISO-8859-1";
fc = get_header(r);
if (fc == NULL)
return NGX_HTTP_INTERNAL_SERVER_ERROR;
lc = get_last_chain(fc);
socket_fd = socket(PF_INET, SOCK_STREAM, 0);
name.sin_family = AF_INET;
hostinfo = gethostbyname((const char *) gscf->hostname.data);
name.sin_addr = *((struct in_addr *) hostinfo->h_addr);
name.sin_port = htons(gscf->port);
if (connect(socket_fd, &name, sizeof(struct sockaddr_in)) < 0) {
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
"Error connecting to Gearman server %s:%d",
gscf->hostname.data, gscf->port
);
status = 0;
}
if (status) {
mc = get_version(r, socket_fd, (const char *)gscf->hostname.data);
if (mc == NULL)
return NGX_HTTP_INTERNAL_SERVER_ERROR;
lc->next = mc;
lc = get_last_chain(mc);
mc = get_info(r, socket_fd, TASK_STATUS);
if (mc == NULL)
return NGX_HTTP_INTERNAL_SERVER_ERROR;
lc->next = mc;
lc = get_last_chain(mc);
mc = get_info(r, socket_fd, TASK_WORKERS);
if (mc == NULL)
return NGX_HTTP_INTERNAL_SERVER_ERROR;
lc->next = mc;
lc = get_last_chain(mc);
} else {
mc = get_connection_error(r, (const char *)gscf->hostname.data, gscf->port);
if (mc == NULL)
return NGX_HTTP_INTERNAL_SERVER_ERROR;
lc->next = mc;
lc = get_last_chain(mc);
}
shutdown(socket_fd, 2);
mc = get_footer(r);
if (mc == NULL)
return NGX_HTTP_INTERNAL_SERVER_ERROR;
lc->next = mc;
lc = get_last_chain(mc);
lc->buf->last_buf = 1;
r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n = get_content_length(fc);
rc = ngx_http_send_header(r);
if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
return rc;
}
return ngx_http_output_filter(r, fc);
}
static char *
ngx_http_set_gearman_status(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_core_loc_conf_t *clcf;
clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
clcf->handler = ngx_http_gearman_status_handler;
return NGX_CONF_OK;
}
static void *
ngx_http_gearman_status_create_loc_conf(ngx_conf_t *cf)
{
ngx_http_gearman_status_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_gearman_status_conf_t));
if (conf == NULL) {
return NGX_CONF_ERROR;
}
conf->port = NGX_CONF_UNSET_UINT;
return conf;
}
static char *
ngx_http_gearman_status_merge_loc_conf(ngx_conf_t *cf,
void *parent, void *child)
{
ngx_http_gearman_status_conf_t *prev = parent;
ngx_http_gearman_status_conf_t *conf = child;
ngx_conf_merge_str_value(conf->hostname, prev->hostname, "localhost");
ngx_conf_merge_uint_value(conf->port, prev->port, 4730);
return NGX_CONF_OK;
}
|
4d05bf5802792e7d5210436fce5b4836a0192048
|
[
"C"
] | 2
|
C
|
amir/ngx_http_gearman_status_module
|
7640b03c98f327dec360e85624747635b5ece01b
|
ce1b7b549b81d6bb1f007eec7246addd7883717b
|
refs/heads/master
|
<file_sep>const BACKEND_DOMAIN = 'https://109k4.pythonanywhere.com'
//exports
export default BACKEND_DOMAIN
<file_sep>import Axios from 'axios'
import { createStore } from 'vuex'
import qs from "qs"
import createPersistedState from 'vuex-persistedstate';
import BACKEND_DOMAIN from '../messanger-config';
export default createStore({
state: {
authorizedUser: '',
contacts: [],
chats: []
},
plugins: [createPersistedState()],
mutations: {
CONTACT_TO_STORE(state, contacts){
state.contacts = contacts;
},
CHATS_TO_STORE(state, chats){
state.chats = chats;
},
SET_NEW_MESSAGE(state, {message, chatId}){
let chat = state.chats.filter(chat => chat.id == chatId)[0]
chat.messages.push(message)
},
CLEAN_NOTS(state, {authUser, chatWith}){
if(authUser){
let user = state.contacts.find(user => user.name == authUser)
let nots = user.notifications.filter(n => n.messageFrom != chatWith)
user.notifications = nots
}
},
NEW_CHAT_TO_STORE(state, newChat){
state.chats.unshift(newChat)
},
NEW_CONTACT_TO_STORE(state, newContact){
state.contacts.push(newContact)
},
NEW_PROFILE_NAME(state, {newUsername, oldUsername}){
state.contacts.forEach((item)=>{
if(item.name == oldUsername){
item.name = newUsername
}
})
state.authorizedUser = newUsername
},
LOG_OUT(state, {index, last_seen}){
state.contacts[index].last_seen = last_seen
state.contacts[index].status = false
state.authorizedUser = ''
},
DELETE_AUTH(state){
state.authorizedUser = ''
},
LOG_IN(state, name){
state.authorizedUser = name
}
},
actions: {
GET_CONTACT({commit}){
return new Promise((reject) => {
Axios.get(BACKEND_DOMAIN+'/APIgetContacts/')
.then(contacts =>{
commit('CONTACT_TO_STORE', contacts.data)
})
.catch((err)=>{
reject(err)
})
})
},
GET_CHATS({commit}){
let user = this.state.authorizedUser
return Axios.get(`${BACKEND_DOMAIN}/APIgetChats/${user}/`)
.then(chats =>{
commit('CHATS_TO_STORE', chats.data)
})
},
SEND_MESSAGE({commit}, {message, chatId}){
return new Promise((resolve) => {
Axios({
method: "POST",
url:`${BACKEND_DOMAIN}/APIsendMessage/${chatId}/`,
data: qs.stringify(message)
})
.then(()=>{
commit('SET_NEW_MESSAGE', {message, chatId})
resolve()
})
})
},
CLEAN_NOTS({commit}, {authUser, chatWith}){
commit('CLEAN_NOTS', {authUser, chatWith})
let data = {
"authUser": authUser,
"chatWith": chatWith
}
Axios({
method: "POST",
url:`${BACKEND_DOMAIN}/APIclearNots/`,
data: qs.stringify(data)
})
.then((respons) => {
return respons;
})
},
SET_NEW_CHAT({commit}, newChat){
return new Promise((resolve) => {
Axios({
method: "POST",
url:`${BACKEND_DOMAIN}/APIsetNewChat/`,
data: qs.stringify(newChat)
})
.then((respons) => {
const newChat = respons.data
commit('NEW_CHAT_TO_STORE', newChat)
resolve(newChat)
})
})
},
// registration
SET_NEW_CONTACT({commit}, newContact){
return new Promise((resolve) => {
Axios({
method: "POST",
url:`${BACKEND_DOMAIN}/APIreg/`,
data: qs.stringify(newContact)
})
.then((respons) => {
const newUser = respons.data
commit('NEW_CONTACT_TO_STORE', newUser)
resolve(newUser)
})
})
},
CHANGE_PROFILE({commit}, {changes, oldUsername, newUsername}){
Axios({
method: "POST",
url: `${BACKEND_DOMAIN}/APIchengeProfileData/${oldUsername}/`,
data: changes,
headers: {
"content-type": "multipart/form-data"
}
})
.then(()=>{
if(newUsername){
commit('NEW_PROFILE_NAME', {newUsername, oldUsername})
}
})
},
// logIn
LOG_IN({commit}, authorizedUser){
let name = authorizedUser.name
return new Promise((resolve) => {
Axios({
method: "POST",
url:`${BACKEND_DOMAIN}/APIlog/`,
data: qs.stringify(authorizedUser)
})
.then((respons) => {
if(respons.data){
commit('LOG_IN', name)
}else{
let name = ''
commit('LOG_IN', name)
}
resolve(respons)
})
})
},
// logOut
LOG_OUT({commit}, deAutorized){
let user = this.state.authorizedUser
let index = deAutorized.index
Axios({
method: 'POST',
url: `${BACKEND_DOMAIN}/APIlogout/${user}/`,
data: qs.stringify(deAutorized)
})
.then((respons)=>{
if(respons.data){
let last_seen = respons.data
commit('LOG_OUT', {index, last_seen})
}
})
}
},
modules: {
}
})
|
ca85230600f42e9282cb5af9b61be473e23b2203
|
[
"JavaScript"
] | 2
|
JavaScript
|
iTka4enko/VueJS-messenger
|
4c2a953588fdf99604fb0d42ddefcd15e6c981ef
|
1be2f8cd37ab226b110eb8eacd88a8f5b2ee7ad8
|
refs/heads/master
|
<file_sep>import pandas as pd
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.preprocessing import image
from keras import backend as K
from keras import metrics
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import load_model
model = load_model('trained_model.h5')
def predictImage(image_name):
img = image.load_img(image_name, target_size=(150, 150))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
prediction = model.predict_classes(x)
if prediction == 0:
prediction='Cat'
else:
prediction = 'Dog'
print(prediction)
predictImage('Data/Dog1.jpg')
predictImage('Data/cat1.jpg')
predictImage('Data/Dog2.jpg')
predictImage('Data/Cat2.jpg')
<file_sep>from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.preprocessing import image
from keras import backend as K
import numpy as np
img_width, img_height = 150, 150
train_data_dir = 'Practice2Train'
validation_data_dir = 'Practice2Valid'
test_data_dir = 'Practice2Test'
nb_train_samples = 8000
nb_validation_samples = 2500
epochs = 10
batch_size = 64
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
test_generator = test_datagen.flow_from_directory(
test_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
testResult= model.evaluate_generator(test_generator)
model.fit_generator(
train_generator,
shuffle=True,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples//batch_size)
model.save('trained_model.h5')
def predictImage(image_name):
img = image.load_img(image_name, target_size=(150, 150))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
prediction = model.predict_classes(x)
if prediction == 0:
prediction='african'
else
prediction = 'asian'
print(prediction)
#testResult= model.evaluate_generator(test_generator,verbose=2)
<file_sep>Ethnic = {
readFile: function(){
var preview = document.querySelector('#e_actual_image');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.readAsDataURL(file); //Takes input and changes it into image
$(reader).load(function () {
$(preview).attr('src', reader.result) //make the src attribute the result of the file reader
Ethnic.data.readerURL = reader.result
});
Ethnic.uploadImage();
},
uploadImage: function(){
$(".e-upload-border").css({'border': 'solid 1px #91C6FF'})
$("#e_pre_upload").hide();
$("#e_post_upload").show();
$("#test").attr('src', Ethnic.data.readerURL)
}
}
Ethnic.data = {
readerURL: ""
}
$(document).ready(function () {
$(document).foundation();
Ethnic.init()
});
<file_sep>import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import *
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
trainPath='Data/Train'
testPath='Data/Test'
validPath='Data/Valid'
practiceTrainPath='Data/PracticeTrain'
practiceTestPath='Data/PracticeTest'
practiceValidPath='Data/PracticeValid'
trainBatches = ImageDataGenerator().flow_from_directory(trainPath, target_size=(224,224), classes=['African', 'American', 'Arab', 'Asian', 'Indian'], batch_size=64)
testBatches = ImageDataGenerator().flow_from_directory(testPath, target_size=(224,224), classes=['African', 'American', 'Arab', 'Asian', 'Indian'], batch_size=32)
validBatches = ImageDataGenerator().flow_from_directory(validPath, target_size=(224,224), classes=['African', 'American', 'Arab', 'Asian', 'Indian'], batch_size=32)
practiceTrainBatches = ImageDataGenerator().flow_from_directory(practiceTrainPath, target_size=(224,224), classes=['Cats','Dogs'], batch_size=64)
practiceTestBatches = ImageDataGenerator().flow_from_directory(practiceTestPath, target_size=(224,224), classes=['Cats','Dogs'], batch_size=32)
practiceValidBatches = ImageDataGenerator().flow_from_directory(practiceValidPath, target_size=(224,224), classes=['Cats','Dogs'], batch_size=32)
print((trainBatches))
imgs, labels = next(trainBatches)
if K.image_data_format() == 'channels_first':
input_shape = (3, 224, 224)
else:
input_shape = (224, 224, 3)
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Dense(2,ctivation='relu'))
model.add(Activation(2, 'sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.fit_generator(practiceTrainBatches, steps_per_epoch=5, validation_data=practiceValidBatches, validation_steps=5, epochs=50,verbose=2)<file_sep>Ethnic.init = function(){
$("#e_post_upload").hide();
$("#e_file_upload").on('change', function(){
Ethnic.readFile()
});
}
|
33b7526b32b3d66d837ee8c4d5d840e4972ef99f
|
[
"JavaScript",
"Python"
] | 5
|
Python
|
bigdatasciencegroup/EthnicityTracker
|
dbf9b29c001eae59c0ddee1bdf0097304b08e954
|
0aa4ac5647ee90beeb31c5fe840aa81e8085fbc5
|
refs/heads/main
|
<repo_name>poojatiwari19/project1<file_sep>/index.js
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'checkin', 'Checout'],
['2014', 400, 200],
['2015', 460, 250],
['2016', 1120, 300],
['2017', 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Checkin, Checkout : 2014-2017',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Checked Out', 11],
['In Stock', 2],
['In Storage', 2],
['In Use', 2],
['Out for Repair', 7]
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
|
a7dd7585f31072b02f2449a6e091658da527b5eb
|
[
"JavaScript"
] | 1
|
JavaScript
|
poojatiwari19/project1
|
b615fbb4523f09f09a698063b3a476d619a7d3a6
|
bca0167459d49fbddc6f3c56f17af445a5afefe7
|
refs/heads/master
|
<file_sep>window.addEventListener('DOMContentLoaded', function() {
var canvas = document.getElementById('canvas');
var engine = new BABYLON.Engine(canvas, true);
var createScene = function() {
var scene = new BABYLON.Scene(engine);
scene.clearColor = new BABYLON.Color3.White();
var box = BABYLON.Mesh.CreateBox("Box", 4.0, scene);
//var camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 0, -10), scene);
//camera.setTarget(BABYLON.Vector3.Zero());
var camera = new BABYLON.ArcRotateCamera("arcCam",
BABYLON.Tools.ToRadians(45),
BABYLON.Tools.ToRadians(45),
10.0, box.position, scene);
camera.attachControl(canvas, true);
var light = new BABYLON.PointLight("pointLight",
new BABYLON.Vector3(5, 10, 0), scene);
light.diffuse = new BABYLON.Color3(0, 1, 0);
// click fades to black
box.actionManager = new BABYLON.ActionManager(scene);
box.actionManager.registerAction(
new BABYLON.InterpolateValueAction(
BABYLON.ActionManager.OnPickTrigger,
light,
'diffuse',
BABYLON.Color3.Black(),
1000
)
);
return scene;
}
var scene = createScene();
engine.runRenderLoop(function() {
scene.render();
});
});
|
174362928fedd291c4faadcc20b0ebc6eea356f8
|
[
"JavaScript"
] | 1
|
JavaScript
|
idiomatic/orbitable-cube
|
95ec334cb28b294e13d77a3b80bd4675fb411bef
|
80e03caed7588dbdc87de9316199ff0583dea58c
|
refs/heads/master
|
<file_sep># ramdb
C library that implements a simple in-memory database structure.
This project is also an experiment in using the [Makeheaders](https://fossil-scm.org/xfer/doc/trunk/src/makeheaders.html) program to auto-generate the header files.
<file_sep>/*** ramdb
**
** An implementation of an in-memory database structure, as well as relational
** algebra for querying the data.
**
***/
#define _GNU_SOURCE
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "rdb.h"
#define LEFT_ALIGN(type) ((type) == RDB_Integer || (type) == RDB_Real)
#define is_null(type,val) \
((type) == RDB_Integer ? (val.int_val) == LONG_MIN : \
(type) == RDB_Real ? isnan(val.real_val) : \
(type) == RDB_String ? val.str_val == NULL : \
(type) == RDB_DateTime ? val.dt_val == NULL : 0)
/* -------------------------------------------------------------------------- */
#if INTERFACE
typedef enum rdb_type_t rdb_type_t;
typedef union rdb_val_t rdb_val_t;
typedef struct rdb_t rdb_t;
/* Enums indicating the different supported data types. */
enum rdb_type_t {
RDB_Integer,
RDB_Real,
RDB_String,
RDB_DateTime
};
/* Union that holds any possible supported value. We indicate Null by using
* special values for each of these types; viz.,
* RDB_Integer : LONG_MIN
* RDB_Real : NaN
* RDB_String : NULL
* RDB_DateTime : NULL
*/
union rdb_val_t {
long int int_val; /* RDB_Integer */
double real_val; /* RDB_Real */
char *str_val; /* RDB_String */
struct tm *dt_val; /* RDB_DateTime */
};
/* Struct that represents a relation (i.e., a table). */
struct rdb_t {
unsigned int n_attrs; /* number of attributes */
unsigned int n_tuples; /* number of tuples */
char **attr_names ; /* (ordered) list of attribute names */
rdb_type_t *attr_types ; /* (ordered) list of attribute types */
rdb_val_t **attr_tuples; /* (ordered) 2D array of attributes */
};
#endif
/* These are the allocation/free functions; they are set to malloc/free by
* default, but may be changed to custom functions. */
static void *(*rdb_alloc)(size_t n) = malloc;
static void (*rdb_free )(void *p) = free ;
/* -------------------------------------------------------------------------- */
static void to_trunc_string(char *dest, rdb_type_t type, rdb_val_t val, size_t dest_nbytes);
/* -------------------------------------------------------------------------- */
///~ Operations in relational algebra:
///~ - Union, intersection, and difference: usual set operations, but both operands must have the same relation schema.
///~ - Selection: picking certain rows.
///~ - Projection: picking certain columns.
///~ - Products and joins: compositions of relations.
///~ - Renaming of relations and attributes.
// TODO: add setters for rdb_alloc and rdb_free
/**
* Set the memory allocation function to the given function. The given function
* should exhibit the same behavious as `malloc'.
*
* @param the allocation function to be used by ramdb henceforth.
*/
void rdb_set_alloc_fn(void *(*alloc_fn)(size_t)) { rdb_alloc = alloc_fn; }
/**
* Set the memory freeing function to the given function. The given function
* should exhibit the same behavious as `free'.
*
* @param the free function to be used by ramdb henceforth.
*/
void rdb_set_free_fn(void (*free_fn)(void *)) { rdb_free = free_fn; }
/**
* In ramdb, the null value is represented by a special value, different for
* each data type. (E.g., a null RDB_Integer is represented by LONG_MIN). This
* function return the null value corresponding to the given type.
*
* @return the corresponding null value.
*/
rdb_val_t rdb_null(rdb_type_t type)
{
rdb_val_t null;
switch (type) {
case RDB_Integer : null.int_val = LONG_MIN; break;
case RDB_Real : null.real_val = nan("1"); break;
case RDB_String : null.str_val = NULL; break;
case RDB_DateTime : null.dt_val = NULL; break;
default: assert(0);
}
return null;
}
/**
* Create and return a new relation, using the allocation function rdb_alloc.
*
* @return a pointer to the new relation, or NULL if memory allocation failed.
*/
rdb_t *rdb_new(void)
{
rdb_t *p = rdb_alloc(sizeof(rdb_t));
if (p == NULL) return NULL;
p->n_attrs = 0;
p->n_tuples = 0;
p->attr_names = NULL;
p->attr_types = NULL;
p->attr_tuples = NULL;
return p;
}
/**
* Create a (deep) copy of the given relation.
*
* @param rel the relation that is to be copied.
*
* @return a pointer to a copy of the given relation, or NULL if memory
* allocation failed.
*/
rdb_t *rdb_copy(rdb_t *rel)
{
rdb_t *copy = rdb_new();
if (copy == NULL) goto cleanup_1;
copy->n_attrs = rel->n_attrs;
copy->n_tuples = rel->n_tuples;
/* copy the attribute names and attribute types */
copy->attr_names = rdb_alloc(copy->n_attrs * sizeof(char *));
if (copy->attr_names == NULL) goto cleanup_1;
copy->attr_types = rdb_alloc(copy->n_attrs * sizeof(rdb_type_t));
if (copy->attr_types == NULL) goto cleanup_2;
for (unsigned int i = 0; i < copy->n_attrs; i++) {
copy->attr_names[i] = rdb_alloc(strlen(rel->attr_names[i])+1);
if (copy->attr_names[i] == NULL) goto cleanup_3;
strcpy(copy->attr_names[i],rel->attr_names[i]);
copy->attr_types[i] = rel->attr_types[i];
}
/* copy the tuples */
copy->attr_tuples = rdb_alloc(copy->n_tuples * sizeof(rdb_val_t *));
if (copy->attr_tuples == NULL) goto cleanup_3;
for (unsigned int i = 0; i < copy->n_tuples; i++) {
copy->attr_tuples[i] = rdb_alloc(copy->n_tuples * sizeof(rdb_val_t));
if (copy->attr_tuples[i] == NULL) goto cleanup_4;
memcpy(copy->attr_tuples[i],rel->attr_tuples[i],copy->n_attrs * sizeof(rdb_val_t));
}
return copy;
/* ... commence error handling and cleanup code ... */
cleanup_4:
/* free any elements of copy->attr_tuples that we managed to alloc */
for (unsigned int i = 0; i < copy->n_tuples && copy->attr_tuples[i] != NULL; i++)
rdb_free(copy->attr_tuples[i]);
rdb_free(copy->attr_tuples);
cleanup_3:
/* free any elements of copy->attr_names that we managed to alloc */
for (unsigned int i = 0; i < copy->n_attrs && copy->attr_names[i] != NULL; i++)
rdb_free(copy->attr_names[i]);
rdb_free(copy->attr_types);
cleanup_2:
rdb_free(copy->attr_names);
cleanup_1:
rdb_free(copy);
return NULL;
}
// TODO
void rdb_free(rdb_t *rel)
{
}
/**
* Print a relation to the given file (using ASCII art to create a tabular
* format).
*
* @param fp the file pointer indicating where to print.
* @param rel the relation to print.
* @param pr_width the width (in characters) to use for columns (excluding
* spaces on either side).
*/
void rdb_print(FILE *fp, rdb_t *rel, size_t pr_width)
{
assert(pr_width >= 3);
/* dividing lines (made of dashes) */
size_t divlen = rel->n_attrs * (pr_width + 3) + 1;
char *div = rdb_alloc(divlen+1);
div[0] = div[divlen] = '+';
for (unsigned int i = 1; i < divlen-1; i++) {
div[i] = (i % (pr_width+3) == 0) ? '+' : '-';
}
div[divlen-1] = '+';
div[divlen ] = '\0';
fprintf(fp," %s\n",div);
/* headers */
fprintf(fp," | ");
for (unsigned int i = 0; i < rel->n_attrs; i++) {
if (strlen(rel->attr_names[i]) >= pr_width+1) {
char trun[pr_width+1];
strncpy(trun,rel->attr_names[i],pr_width-3);
trun[pr_width-3] = '\0';
fprintf(fp,"%-*s... | ",(int)pr_width-3,trun);
} else {
fprintf(fp,"%-*s | ",(int)pr_width,rel->attr_names[i]);
}
}
fprintf(fp,"\n");
fprintf(fp," %s\n",div);
/* tuples */
char *entry = rdb_alloc(pr_width+1);
for (unsigned int i = 0; i < rel->n_tuples; i++) {
fprintf(fp," | ");
for (unsigned int j = 0; j < rel->n_attrs; j++) {
to_trunc_string(entry,rel->attr_types[j],rel->attr_tuples[i][j],pr_width+1);
/* numbers are right-aligned */
if (LEFT_ALIGN(rel->attr_types[j]))
fprintf(fp,"%*s | ",(int)pr_width,entry);
else
fprintf(fp,"%-*s | ",(int)pr_width,entry);
}
fprintf(fp,"\n");
fprintf(fp," %s\n",div);
}
free(div);
}
/* -------------------------------------------------------------------------- */
/* Relational Algebra Operators */
// select_fn: given a tuple, returns true/false
// IDEA: function that maps attr name -> attr index, which is an opaque data
// data type (but really, just an int) identifying the attribute. Then can have
// select functions like follows:
// bool select_fn(rdb_val_t *tuple)
// {
// return tuple[rdb_attr_index("ID")] == 1;
// }
// Prolly gonna need comparison functions for the RDB data types?
rdb_t *rdb_insert (rdb_t *rel, rdb_val_t val_1, ...); // should be n_attrs values
// rdb_alter???
rdb_t *rdb_rename (rdb_t *rel, char *from, char *to);
rdb_t *rdb_select (rdb_t *rel, bool (*select_fn)(rdb_val_t *tuple));
rdb_t *rdb_join (rdb_t *rel_A, rdb_t *rel_B);
rdb_t *rdb_product (rdb_t *rel_A, rdb_t *rel_B); // Cartesian product
rdb_t *rdb_project (rdb_t *rel, char **attr_list, unsigned int n_attrs, bool unique_tuples);
rdb_t *rdb_calc_attr (rdb_t *rel, char *name, rdb_type_t type, rdb_val_t (*calc)(rdb_val_t *tuple));
// Synonyms:
// select -> filter
// Other potential operations:
// apply -> apply a function to every element in a column (can be implemented
// ito. the existing RA operations)
// map -> apply a function to every column
// pivot -> changes rows to columns and vice versa (transpose?)
// selection is a homomorphism (?):
// \sigma_{\varphi_1 \wedge \varphi_2} = \sigma_{\varphi_1} \circ \sigma_{\varphi_2}
// What about \vee and \not?
// The join is associative
// The join is not commutative, unless it is followed by a projection:
// Find out other algebraic laws that are used to optimise queries
/* constraint for multiset operations: the two relations must have the same attributes */
rdb_t *rdb_union (rdb_t *rel_A, rdb_t *rel_B);
rdb_t *rdb_diff (rdb_t *rel_A, rdb_t *rel_B);
rdb_t *rdb_inter (rdb_t *rel_A, rdb_t *rel_B);
// NB: could write OR conditions and AND conditions in terms of unions and
// intersections of relations
// IDEA: add extra joins for efficiency:
// - theta joins
// - natural joins
// - left and right joins (theta join followed by projection onto LHS's
// columns or RHS's columns, respectively)
// - anti-join
// - outer joins (left, right, full)
// (In the same way, the join operator is simply a product followed by a
// select).
///~ Bars.select(tab => tab.addr == "Maple St.")
///~ .project("name");
///~ union
///~ Sells.select(tab => tab.price < 3 && tab.beer == "Bud")
///~ .project("bar")
///~ .rename({ "bar" -> "name")
// rdb_count, etc.?
/* -------------------------------------------------------------------------- */
static void to_trunc_string(char *dest, rdb_type_t type, rdb_val_t val, size_t dest_nbytes)
{
assert(dest_nbytes > 3);
char *t;
if (is_null(type,val)) {
asprintf(&t,"(null)");
} else {
switch (type) {
case RDB_Integer : asprintf(&t,"%ld",val.int_val ); break;
case RDB_Real : asprintf(&t,"%g",val.real_val ); break;
case RDB_String : asprintf(&t,"%s",val.str_val ); break;
case RDB_DateTime : {
t = rdb_alloc(20); // 19+1 chars for format YYYY-MM-DD HH:MM:SS
strftime(t,20,"%Y-%m-%d %H:%M:%S",val.dt_val);
break;
}
default: assert(0);
}
}
if (strlen(t)+1 > dest_nbytes) {
strncpy(dest,t,dest_nbytes-4);
dest[dest_nbytes-4] = '.';
dest[dest_nbytes-3] = '.';
dest[dest_nbytes-2] = '.';
dest[dest_nbytes-1] = '\0';
} else {
strncpy(dest,t,dest_nbytes);
}
free(t);
}
<file_sep>/*** ramdb
**
** An implementation of an in-memory database structure, as well as relational
** algebra for querying the data.
**
***/
#define _GNU_SOURCE
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"
#include "rdb.h"
/* -------------------------------------------------------------------------- */
///~ #if INTERFACE
///~ #endif
/* -------------------------------------------------------------------------- */
int main(void)
{
rdb_t *rel = rdb_new();
rel->n_attrs = 4;
rel->n_tuples = 5;
rel->attr_names = (char*[]) { "ID", "First Name", "Surname", "<NAME>" };
rel->attr_types = (rdb_type_t[]) { RDB_Integer, RDB_String, RDB_String, RDB_DateTime };
rel->attr_tuples = malloc(5 * sizeof(rdb_val_t *));
time_t timer_1 = time(NULL);
rel->attr_tuples[0] = malloc(4 * sizeof(rdb_val_t));
rel->attr_tuples[0][0].int_val = 1;
rel->attr_tuples[0][1].str_val = "Dennis";
rel->attr_tuples[0][2].str_val = "Barrett";
rel->attr_tuples[0][3] = rdb_null(RDB_DateTime);
time_t timer_2 = time(NULL);
rel->attr_tuples[1] = malloc(4 * sizeof(rdb_val_t));
rel->attr_tuples[1][0].int_val = 2;
rel->attr_tuples[1][1].str_val = "John";
rel->attr_tuples[1][2].str_val = "Smith";
rel->attr_tuples[1][3].dt_val = localtime(&timer_2);
time_t timer_3 = time(NULL);
rel->attr_tuples[2] = malloc(4 * sizeof(rdb_val_t));
rel->attr_tuples[2][0].int_val = 3;
rel->attr_tuples[2][1].str_val = "Elizabeth";
rel->attr_tuples[2][2].str_val = "Weir";
rel->attr_tuples[2][3].dt_val = localtime(&timer_3);
time_t timer_4 = time(NULL);
rel->attr_tuples[3] = malloc(4 * sizeof(rdb_val_t));
rel->attr_tuples[3][0].int_val = 4;
rel->attr_tuples[3][1].str_val = "George";
rel->attr_tuples[3][2] = rdb_null(RDB_String); //"Hammond";
rel->attr_tuples[3][3].dt_val = localtime(&timer_4);
time_t timer_5 = time(NULL);
rel->attr_tuples[4] = malloc(4 * sizeof(rdb_val_t));
rel->attr_tuples[4][0] = rdb_null(RDB_Integer); // 5;
rel->attr_tuples[4][1].str_val = "Jack";
rel->attr_tuples[4][2].str_val = "O'Neill";
rel->attr_tuples[4][3].dt_val = localtime(&timer_5);
rdb_print(stdout,rel,20);
rdb_t *copy = rdb_copy(rel);
return 0;
}
/* -------------------------------------------------------------------------- */
<file_sep>CC = gcc
LD = gcc
MH = mh
TARGET_EXEC = rdb
BUILD_DIR = ./build
SRC_DIR = ./src
SRCS := $(wildcard $(SRC_DIR)/*.c)
HDRS := $(wildcard $(SRC_DIR)/*.h)
OBJS := $(SRCS:$(SRC_DIR)/%.c=$(BUILD_DIR)/%.o)
DEPS := $(SRCS:$(SRC_DIR)/%.c=$(BUILD_DIR)/%.d)
INC_DIRS := ./include
INC_FLAGS := $(addprefix -I,$(INC_DIRS))
LIB_DIRS := ./lib
LIB_FLAGS := $(addprefix -L,$(LIB_DIRS))
CFLAGS = -std=c11 -Os -Wall -Wextra -pedantic -Wno-unused-variable -Wno-unused-function -g $(INC_FLAGS) -pipe
DEPFLAGS = -MT $@ -MMD -MP -MF $(BUILD_DIR)/$*.d
LIBS :=
# all
.PHONY: all
all: $(TARGET_EXEC) rdb.api
# exe
$(TARGET_EXEC): $(OBJS)
@$(LD) $(OBJS) -o $@ $(LIB_FLAGS) $(LIBS:%=-l%)
@echo Successfully linked
# C source
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c $(SRC_DIR)/%.h
@$(CC) $(DEPFLAGS) $(CFLAGS) -c $< -o $@
@echo Successfully compiled $^
# headers
$(SRC_DIR)/%.h: $(SRC_DIR)/%.c
$(MH) $<
@echo Successfully generated header from $^
# C tags
nana.api: $(SRCS) $(HDRS)
@ctags --excmd=number --c-types=pcdgstu -f $(BUILD_DIR)/tags $^
@python /mnt/c/dev/SciTE/tags2api.py $(BUILD_DIR)/tags >rdb.api
.PHONY: clean
clean:
del $(TARGET_EXEC)
del $(BUILD_DIR)/*.o
del $(BUILD_DIR)/*.d
del $(BUILD_DIR)/tags
-include $(DEPS)
$(DEPS): $(SRCS)
@$(CC) $(CFLAGS) $< -MM -MT $(@:.d=.o) > $@
|
ccb4a67759c1a1c2440ed3e2c5e0e3f24625f0a6
|
[
"Markdown",
"C",
"Makefile"
] | 4
|
Markdown
|
dennii/ramdb
|
d9b0f9abeb9a03f23d84e98ebaeee5ed623aa5d4
|
78b52490690770fddfa08fc20bd3752972888697
|
refs/heads/master
|
<repo_name>Maximuel/TP-Planning<file_sep>/main.py
import os
from datetime import date
from tkinter import ttk
from selenium import webdriver
import time
from tkinter import *
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from pynput.keyboard import Key, Controller
import tkinter as tk
import tkinter.font as tkFont
from tkcalendar import DateEntry
class main(object):
addedRequests = [[],[],[],[],[]]
addedRequestsList = []
request_col = ["Project name", "Country", "Test item", "Due date", "Comment"]
keyboard = Controller()
def __init__(self, master):
def defocus(event):
event.widget.master.focus_set()
def on_entry_click(event):
"""function that gets called whenever entry is clicked"""
if self.commentList.get("1.0", 'end-1c') == 'Enter comment here...':
self.commentList.delete("1.0", END) # delete all the text in the entry
self.commentList.insert("1.0", '') # Insert blank for user input
self.commentList.config(fg='black')
def on_focusout(event):
if self.commentList.get("1.0",END) == '':
self.commentList.insert(0, 'Enter comment here...')
self.commentList.config(fg='grey')
# buttonsFrame = Frame(top,borderwidth=4, relief="raised")
# buttonsFrame.place(x=300, y=500, width=120, height=20)
# Project entry frame
projectFrame = Frame(top, borderwidth=4, relief="raised")
projectFrame.place(x=30, y=245, width=227, height=100)
# Calendar frame
calendarFrame = Frame(top, borderwidth=4, relief="raised")
calendarFrame.place(x=267, y=245, width=210, height=100)
# country
frame = Frame(top, borderwidth=4, relief="raised")
frame.place(x=30, y=355, width=447, height=200)
# test type frame
testTypeFrame = Frame(top, borderwidth=4, relief="raised")
testTypeFrame.place(x=487, y=355, width=447, height=200)
# Request button frame
addProjectFrame = Frame(top)
addProjectFrame.place(x=30, y=565, width=900, height=70)
# Request button frame
sendRequestFrame = Frame(top)
sendRequestFrame.place(x=30, y=645, width=900, height=70)
# List
#listFrame = Frame(top, borderwidth=4, relief="raised")
#listFrame.place(x=30, y=30, width=904, height=205)
# Comment
commentFrame = Frame(top, borderwidth=4, relief="raised")
commentFrame.place(x=487, y=245, width=447, height=100)
self.commentList = Text(commentFrame, height=100, width=667)
self.commentList.insert(END, "Enter comment here...")
self.commentList.bind('<FocusIn>', on_entry_click)
self.commentList.bind('<FocusOut>', on_focusout)
self.commentList.config(fg='grey')
self.commentList.pack(side="left")
self.commentList.pack()
self.testTypeLabel = Label(testTypeFrame, text="Select test item")
self.testTypeLabel.pack()
self.countryLabel = Label(frame, text="Country")
self.countryLabel.pack()
self.projectEntry = Label(projectFrame, text="Project")
self.projectEntry.place(x=88, y=15)
self.projectEntry = ttk.Combobox(projectFrame, state="readonly", width=26, values=["SM-J105F_MEA_XSG", "SM-A515F_EUR_XX"])
self.projectEntry.place(x=20, y=40)
self.projectEntry.bind("<FocusIn>", defocus)
self.calendar = Label(calendarFrame, text="Due date")
self.calendar.place(x=72, y=15)
self.calendar = MyDateEntry(top, date_pattern='yyyy-MM-dd')
self.calendar._set_text(self.calendar._date.strftime('%Y-%m-%d'))
self.calendar.place(x=322,y=287)
self.listBoxRequests = MultiColumnListbox()
#=====================================================================================================
# Country checkboxes
self.chbPoland = BooleanVar()
self.countryCheckBox1 = Checkbutton(frame, variable=self.chbPoland, text="Poland")
self.countryCheckBox1.place(x=5, y=10)
self.chbItaly = BooleanVar()
self.countryCheckBox2 = Checkbutton(frame, variable=self.chbItaly, text="Italy")
self.countryCheckBox2.place(x=5, y=30)
self.chbGermany = BooleanVar()
self.countryCheckBox3 = Checkbutton(frame, variable=self.chbGermany, text="Germany")
self.countryCheckBox3.place(x=5, y=50)
self.chbFrance = BooleanVar()
self.countryCheckBox4 = Checkbutton(frame, variable=self.chbFrance, text="France")
self.countryCheckBox4.place(x=5, y=70)
self.chbUK = BooleanVar()
self.countryCheckBox5 = Checkbutton(frame, variable=self.chbUK, text="U.K.")
self.countryCheckBox5.place(x=5, y=90)
self.chbSpain = BooleanVar()
self.countryCheckBox6 = Checkbutton(frame, variable=self.chbSpain, text="Spain")
self.countryCheckBox6.place(x=5, y=110)
self.chbSweden = BooleanVar()
self.countryCheckBox7 = Checkbutton(frame, variable=self.chbSweden, text="Sweden")
self.countryCheckBox7.place(x=5, y=130)
#----------------------
#select all button
self.chAllButton = Button(frame, text="Check ALL",
command=lambda: self.checkAllcountry())
self.chAllButton.place(x=93 ,y=510)
#----------------------
#deselectALL
self.chAllButton = Button(frame, text="Clear",
command=lambda: self.uncheckAllcountry())
self.chAllButton.place(x=163, y=275)
self.buttonAdd = Button(addProjectFrame, width=140, height=30, text="Add request",
command=lambda: self.printlist())
self.buttonAdd.pack()
self.buttonRequest = Button(sendRequestFrame, width=140, height=30, text="Start planning",
command=lambda: self.request())
self.buttonRequest.pack()
#===================================================================================================
# =====================================================================================================
# TestItems checkboxes
self.chbIOT = BooleanVar()
self.testItemCheckBox1 = Checkbutton(testTypeFrame, variable=self.chbIOT, text="IOT")
self.testItemCheckBox1.place(x=5, y=10)
self.chbFullTC = BooleanVar()
self.testItemCheckBox2 = Checkbutton(testTypeFrame, variable=self.chbFullTC, text="Full Test Case")
self.testItemCheckBox2.place(x=5, y=30)
self.chbWA = BooleanVar()
self.testItemCheckBox3 = Checkbutton(testTypeFrame, variable=self.chbWA, text="Widget/Application Test")
self.testItemCheckBox3.place(x=5, y=50)
self.chbEurExtra = BooleanVar()
self.testItemCheckBox4 = Checkbutton(testTypeFrame, variable=self.chbEurExtra, text="EUR Extra Test")
self.testItemCheckBox4.place(x=5, y=70)
self.chbNetworkCheckList = BooleanVar()
self.testItemCheckBox5 = Checkbutton(testTypeFrame, variable=self.chbNetworkCheckList, text="Network Check List")
self.testItemCheckBox5.place(x=5, y=90)
self.chbBMICT = BooleanVar()
self.testItemCheckBox6 = Checkbutton(testTypeFrame, variable=self.chbBMICT, text="Base Model Issue")
self.testItemCheckBox6.place(x=5, y=110)
self.chbSimCardAt = BooleanVar()
self.testItemCheckBox7 = Checkbutton(testTypeFrame, variable=self.chbSimCardAt, text="Sim Card AT")
self.testItemCheckBox7.place(x=5, y=130)
# ----------------------
# select all button
self.chAllButton = Button(frame, text="Check All",
command=lambda: self.checkAllcountry())
self.chAllButton.place(x=270, y=147, width=70, height=30)
# ----------------------
# deselectALL
self.chAllButton = Button(frame, text="Clear",
command=lambda: self.uncheckAllcountry())
self.chAllButton.place(x=350, y=147, width=70, height=30)
# ===================================================================================================
# select all button
self.chAllButton = Button(testTypeFrame, text="Check All",
command=lambda: self.checkAllitems())
self.chAllButton.place(x=270, y=147, width=70, height=30)
# ----------------------
# deselectALL
self.chAllButton = Button(testTypeFrame, text="Clear",
command=lambda: self.uncheckAllitems())
self.chAllButton.place(x=350, y=147, width=70, height=30)
# ===================================================================================================
def checkAllcountry(self):
self.countryCheckBox1.select()
self.countryCheckBox2.select()
self.countryCheckBox3.select()
self.countryCheckBox4.select()
self.countryCheckBox5.select()
self.countryCheckBox6.select()
self.countryCheckBox7.select()
def uncheckAllcountry(self):
self.countryCheckBox1.deselect()
self.countryCheckBox2.deselect()
self.countryCheckBox3.deselect()
self.countryCheckBox4.deselect()
self.countryCheckBox5.deselect()
self.countryCheckBox6.deselect()
self.countryCheckBox7.deselect()
def checkAllitems(self):
self.testItemCheckBox1.select()
self.testItemCheckBox2.select()
self.testItemCheckBox3.select()
self.testItemCheckBox4.select()
self.testItemCheckBox5.select()
self.testItemCheckBox6.select()
self.testItemCheckBox7.select()
def uncheckAllitems(self):
self.testItemCheckBox1.deselect()
self.testItemCheckBox2.deselect()
self.testItemCheckBox3.deselect()
self.testItemCheckBox4.deselect()
self.testItemCheckBox5.deselect()
self.testItemCheckBox6.deselect()
self.testItemCheckBox7.deselect()
def createListOfRequest(self,project, chbPoland,chbItaly,chbGermany,chbFrance,chbUK,chbSpain,chbSweden,
chbFullTC,chbIOT,chbWA,chbEurExtra,chbNetworkCheckList,chbBMICT,chbSimCardAt,
dueDate, comment):
listofrequest = [[], [], [], [], []]
if chbPoland is True:
if chbFullTC is True:
listofrequest[0].append(project)
listofrequest[1].append("Poland")
listofrequest[2].append("Full Test Case")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbIOT is True:
listofrequest[0].append(project)
listofrequest[1].append("Poland")
listofrequest[2].append("IOT")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbWA is True:
listofrequest[0].append(project)
listofrequest[1].append("Poland")
listofrequest[2].append("Widgets/Applications Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbEurExtra is True:
listofrequest[0].append(project)
listofrequest[1].append("Poland")
listofrequest[2].append("EUR Extra Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbNetworkCheckList is True:
listofrequest[0].append(project)
listofrequest[1].append("Poland")
listofrequest[2].append("Network Checklist Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbBMICT is True:
listofrequest[0].append(project)
listofrequest[1].append("Poland")
listofrequest[2].append("Base Model Issue Checking Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbSimCardAt is True:
listofrequest[0].append(project)
listofrequest[1].append("Poland")
listofrequest[2].append("SIM card AT Functionalities")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbItaly is True:
if chbFullTC is True:
listofrequest[0].append(project)
listofrequest[1].append("Italy")
listofrequest[2].append("Full Test Case")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbIOT is True:
listofrequest[0].append(project)
listofrequest[1].append("Italy")
listofrequest[2].append("IOT")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbWA is True:
listofrequest[0].append(project)
listofrequest[1].append("Italy")
listofrequest[2].append("Widgets/Applications Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbEurExtra is True:
listofrequest[0].append(project)
listofrequest[1].append("Italy")
listofrequest[2].append("EUR Extra Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbNetworkCheckList is True:
listofrequest[0].append(project)
listofrequest[1].append("Italy")
listofrequest[2].append("Network Checklist Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbBMICT is True:
listofrequest[0].append(project)
listofrequest[1].append("Italy")
listofrequest[2].append("Base Model Issue Checking Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbSimCardAt is True:
listofrequest[0].append(project)
listofrequest[1].append("Italy")
listofrequest[2].append("SIM card AT Functionalities")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbGermany is True:
if chbFullTC is True:
listofrequest[0].append(project)
listofrequest[1].append("Germany")
listofrequest[2].append("Full Test Case")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbIOT is True:
listofrequest[0].append(project)
listofrequest[1].append("Germany")
listofrequest[2].append("IOT")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbWA is True:
listofrequest[0].append(project)
listofrequest[1].append("Germany")
listofrequest[2].append("Widgets/Applications Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbEurExtra is True:
listofrequest[0].append(project)
listofrequest[1].append("Germany")
listofrequest[2].append("EUR Extra Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbNetworkCheckList is True:
listofrequest[0].append(project)
listofrequest[1].append("Germany")
listofrequest[2].append("Network Checklist Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbBMICT is True:
listofrequest[0].append(project)
listofrequest[1].append("Germany")
listofrequest[2].append("Base Model Issue Checking Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbSimCardAt is True:
listofrequest[0].append(project)
listofrequest[1].append("Germany")
listofrequest[2].append("SIM card AT Functionalities")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbFrance is True:
if chbFullTC is True:
listofrequest[0].append(project)
listofrequest[1].append("France")
listofrequest[2].append("Full Test Case")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbIOT is True:
listofrequest[0].append(project)
listofrequest[1].append("France")
listofrequest[2].append("IOT")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbWA is True:
listofrequest[0].append(project)
listofrequest[1].append("France")
listofrequest[2].append("Widgets/Applications Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbEurExtra is True:
listofrequest[0].append(project)
listofrequest[1].append("France")
listofrequest[2].append("EUR Extra Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbNetworkCheckList is True:
listofrequest[0].append(project)
listofrequest[1].append("France")
listofrequest[2].append("Network Checklist Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbBMICT is True:
listofrequest[0].append(project)
listofrequest[1].append("France")
listofrequest[2].append("Base Model Issue Checking Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbSimCardAt is True:
listofrequest[0].append(project)
listofrequest[1].append("France")
listofrequest[2].append("SIM card AT Functionalities")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbUK is True:
if chbFullTC is True:
listofrequest[0].append(project)
listofrequest[1].append("UK")
listofrequest[2].append("Full Test Case")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbIOT is True:
listofrequest[0].append(project)
listofrequest[1].append("UK")
listofrequest[2].append("IOT")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbWA is True:
listofrequest[0].append(project)
listofrequest[1].append("UK")
listofrequest[2].append("Widgets/Applications Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbEurExtra is True:
listofrequest[0].append(project)
listofrequest[1].append("UK")
listofrequest[2].append("EUR Extra Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbNetworkCheckList is True:
listofrequest[0].append(project)
listofrequest[1].append("UK")
listofrequest[2].append("Network Checklist Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbBMICT is True:
listofrequest[0].append(project)
listofrequest[1].append("UK")
listofrequest[2].append("Base Model Issue Checking Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbSimCardAt is True:
listofrequest[0].append(project)
listofrequest[1].append("UK")
listofrequest[2].append("SIM card AT Functionalities")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbSpain is True:
if chbFullTC is True:
listofrequest[0].append(project)
listofrequest[1].append("Spain")
listofrequest[2].append("Full Test Case")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbIOT is True:
listofrequest[0].append(project)
listofrequest[1].append("Spain")
listofrequest[2].append("IOT")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbWA is True:
listofrequest[0].append(project)
listofrequest[1].append("Spain")
listofrequest[2].append("Widgets/Applications Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbEurExtra is True:
listofrequest[0].append(project)
listofrequest[1].append("Spain")
listofrequest[2].append("EUR Extra Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbNetworkCheckList is True:
listofrequest[0].append(project)
listofrequest[1].append("Spain")
listofrequest[2].append("Network Checklist Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbBMICT is True:
listofrequest[0].append(project)
listofrequest[1].append("Spain")
listofrequest[2].append("Base Model Issue Checking Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbSimCardAt is True:
listofrequest[0].append(project)
listofrequest[1].append("Spain")
listofrequest[2].append("SIM card AT Functionalities")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbSweden is True:
if chbFullTC is True:
listofrequest[0].append(project)
listofrequest[1].append("Sweden")
listofrequest[2].append("Full Test Case")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbIOT is True:
listofrequest[0].append(project)
listofrequest[1].append("Sweden")
listofrequest[2].append("IOT")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbWA is True:
listofrequest[0].append(project)
listofrequest[1].append("Sweden")
listofrequest[2].append("Widgets/Applications Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbEurExtra is True:
listofrequest[0].append(project)
listofrequest[1].append("Sweden")
listofrequest[2].append("EUR Extra Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbNetworkCheckList is True:
listofrequest[0].append(project)
listofrequest[1].append("Sweden")
listofrequest[2].append("Network Checklist Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbBMICT is True:
listofrequest[0].append(project)
listofrequest[1].append("Sweden")
listofrequest[2].append("Base Model Issue Checking Test")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
if chbSimCardAt is True:
listofrequest[0].append(project)
listofrequest[1].append("Sweden")
listofrequest[2].append("SIM card AT Functionalities")
listofrequest[3].append(dueDate)
listofrequest[4].append(comment)
return listofrequest
def printlist(self):
del self.addedRequestsList[:]
listofrequest= self.createListOfRequest(self.projectEntry.get(), self.chbPoland.get(), self.chbItaly.get(),self.chbGermany.get(),self.chbFrance.get(),self.chbUK.get(),self.chbSpain.get(),self.chbSweden.get(),
self.chbFullTC.get(),self.chbIOT.get(),self.chbWA.get(),self.chbEurExtra.get(),
self.chbNetworkCheckList.get(),self.chbBMICT.get(),self.chbSimCardAt.get(),
self.calendar.get(), comment=self.commentList.get("1.0", END))
for i in range(len(listofrequest)):
self.addedRequests[i].extend(listofrequest[i])
for i in range(len(self.addedRequests[0])):
self.addedRequestsList.append((self.addedRequests[0][i],self.addedRequests[1][i],self.addedRequests[2][i],self.addedRequests[3][i],self.addedRequests[4][i]))
self.listBoxRequests = MultiColumnListbox()
def request(self):
ieCapabilities = DesiredCapabilities.INTERNETEXPLORER.copy()
ieCapabilities.values()
ieCapabilities["nativeEvents"] = False
ieCapabilities["ignoreProtectedModeSettings"] = True
ieCapabilities["disable-popup-blocking"] = True
ieCapabilities["enablePersistentHover"] = True
driver = webdriver.Ie(capabilities=ieCapabilities, executable_path=r'IEDriverServer.exe')
driver.get("http://mdvh.sec.samsung.net/swvh/pjt/info/viewSwvhProjectList.do")
driver.maximize_window()
time.sleep(5)
#driver.find_element_by_xpath("//a[@name='SET_PROJECT']").click()
#time.sleep(2)
driver.find_element_by_id("devModelNm").clear()
driver.find_element_by_id("devModelNm").send_keys("<KEY>") #Model project name zmienna pobierana
driver.find_element_by_id("b2_pjtRegisterDateStart").click() #czyszczenie daty mozna zostawic albo czyscic
driver.find_element_by_id("searchBtn").click() # przycisk search
time.sleep(2)
driver.find_element_by_xpath("//tbody[@id='resultTableBody']/tr/td[2]/a/span").click() #project pierwszy z listy
driver.find_element_by_xpath("/html/body/div/div/div[1]/ul/li[3]/a").click() #request test
#switch na nowe okno
#--------------------------------------
time.sleep(10)
print("sleep 10")
driver.switch_to.window(driver.window_handles[1])
print("nowe okno")
time.sleep(10)
print("sleep 10")
#select = Select(driver.find_element_by_xpath("//select[@id='searchAreaCd']"))
#print("szuka test regionu")
#select.select_by_visible_text("[FTE]EUR") #wybieranie fte eur jako test region
#print("zmiana na fte eur")
#driver.find_element_by_id("searchBtn").click() # przycisk search
#print("klika search")
#------------TEST ITEM I KRAJ--------------------------------
testItems = driver.find_elements_by_xpath("//tbody[@id='view_list']/*/td[4]")
country = driver.find_elements_by_xpath("//tbody[@id='view_list']/*/td[3]")
#print("searching for "+self.testType.get() + " country " + self.country.get())
'''LISTOFREQUEST = self.createListOfRequest(self.chbPoland.get(), self.chbItaly.get(),self.chbGermany.get(),self.chbFrance.get(),self.chbUK.get(),self.chbSpain.get(),self.chbSweden.get(),
self.chbFullTC.get(),self.chbIOT.get(),self.chbWA.get(),self.chbEurExtra.get()
,self.chbNetworkCheckList.get(),self.chbBMICT.get(),self.chbSimCardAt.get())'''
LISTOFREQUEST=self.addedRequests
print(len(LISTOFREQUEST))
print(len(testItems))
print(LISTOFREQUEST)
even=0
odd=1
for j in range(0,len(LISTOFREQUEST)):
for i in range(len(testItems)):
print("+++++++++++++++++++++++")
#print(LISTOFREQUEST[0][j])
#print(LISTOFREQUEST[1][j])
print(testItems[i].text)
print("======================")
if LISTOFREQUEST[even][j] in country[i].text and LISTOFREQUEST[odd][j] in testItems[i].text:
"""---------------------------"""
driver.find_element_by_xpath("/html/body/form/div[2]/div[5]/table/tbody/tr["+str(i+1)+"]/td[1]/input").click()
driver.find_element_by_xpath("//form[@id='planLayerForm']/div[2]/div[6]/div/div/span[2]/span/a").click()
time.sleep(4)
driver.switch_to.window(driver.window_handles[2])
time.sleep(4)
driver.find_element_by_xpath("//textarea[@name='saveList[0].pjtTestRequestVo.requestContent']").send_keys("jakis komentarz")
time.sleep(4)
driver.close()
#driver.find_element_by_xpath("//form[@id='listForm']/div/div/div/div/span/a[@onclick]").click()#close button
print("close")
driver.switch_to.window(driver.window_handles[1])
driver.find_element_by_xpath("/html/body/form/div[2]/div[5]/table/tbody/tr[" + str(i + 1) + "]/td[1]/input").click()
break
even+=2
odd+=2
#_____________KONIEC TEST ITEMU___________________
#driver.find_element_by_xpath("//form[@id='planLayerForm']/div[2]/div[6]/div/div/span[2]/span/a").click() #request button
class ABC(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
def onExit(top):
os.startfile("end.vbs")
top.destroy()
class Checkbar(Frame):
def __init__(self, parent=None, picks=[], side=LEFT, anchor=W):
Frame.__init__(self, parent)
self.vars = []
for pick in picks:
var = IntVar()
chk = Checkbutton(self, text=pick, variable=var)
chk.pack(side=side, anchor=anchor, expand=YES)
self.vars.append(var)
def state(self):
return map((lambda var: var.get()), self.vars)
class MyDateEntry(DateEntry):
def __init__(self, master=None, **kw):
DateEntry.__init__(self, master=None, **kw)
# add black border around drop-down calendar
self._top_cal.configure(bg='black', bd=1)
self._top_cal.configure()
# add label displaying today's date below
tk.Label(self._top_cal, bg='gray90', anchor='w',
text='Today: %s' % date.today().strftime('%Y-%m-%d')).pack(fill='x')
def _select(self, event=None):
date = self._calendar.selection_get()
if date is not None:
self._set_text(date.strftime('%Y-%m-%d'))
self.event_generate('<<DateEntrySelected>>')
self._top_cal.withdraw()
if 'readonly' not in self.state():
self.focus_set()
class MultiColumnListbox(object):
"""use a ttk.TreeView as a multicolumn ListBox"""
def __init__(self):
self.tree = None
self._setup_widgets()
self._build_tree()
"""def delete(self):
selected_item = self.tree.selection()[0] ## get selected item
self.tree.delete(selected_item)
selected = selected_item[-1]
print("Przed usunieciem addedRequests: " + str(len(main.addedRequests)))
print("Przed usunieciem request_planning_list: " + str(len(main.request_planning_list)))
print("Przed usunieciem finalLinks: " + str(len(main.finalLinks)))
del main.addedRequests[int(selected)-1]
del main.request_planning_list[int(selected)-1]
del main.finalLinks[int(selected)-1]
print("Po usunieciu addedRequests: " + str(len(main.addedRequests)))
print("Po usunieciem request_planning_list: " + str(len(main.request_planning_list)))
print("Po usunieciem finalLinks: " + str(len(main.finalLinks)))
print(main.request_planning_list)"""
def _setup_widgets(self):
container = ttk.Frame(borderwidth=4, relief="raised")
container.place(x=30, y=30, width=905, height=205)
# create a treeview with dual scrollbars
self.tree = ttk.Treeview(columns=main.request_col, show="headings")
vsb = ttk.Scrollbar(orient="vertical",
command=self.tree.yview)
"""hsb = ttk.Scrollbar(orient="horizontal",
command=self.tree.xview)"""
self.tree.configure(yscrollcommand=vsb.set)
self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
vsb.grid(column=1, row=0, sticky='ns', in_=container)
#hsb.grid(column=0, row=1, sticky='ew', in_=container)
container.grid_columnconfigure(0, weight=1)
container.grid_rowconfigure(0, weight=1)
def _build_tree(self):
for col in main.request_col:
self.tree.heading(col, text=col.title())
# adjust the column's width to the header string
self.tree.column(col,
width=tkFont.Font().measure(col.title()))
for item in main.addedRequestsList:
self.tree.insert('', 'end', values=item)
# adjust column's width if necessary to fit each value
for ix, val in enumerate(item):
col_w = tkFont.Font().measure(val)
"""if self.tree.column(main.request_planning_col[ix],width=None)<col_w:
self.tree.column(main.request_planning_col[ix], width=col_w)"""
def sortby(tree, col, descending):
"""sort tree contents when a column header is clicked on"""
# grab values to sort
data = [(tree.set(child, col), child) \
for child in tree.get_children('')]
# if the data to be sorted is numeric change to float
#data = change_numeric(data)
# now sort the data in place
data.sort(reverse=descending)
for ix, item in enumerate(data):
tree.move(item[1], '', ix)
# switch the heading so it will sort in the opposite direction
tree.heading(col, command=lambda col=col: sortby(tree, col, \
int(not descending)))
top = Tk()
top.protocol("WM_DELETE_WINDOW", lambda: onExit(top))
# Gets the requested values of the height and width.
windowWidth = top.winfo_reqwidth()
windowHeight = top.winfo_reqheight()
# Gets both half the screen width/height and window width/height
positionRight = int(top.winfo_screenwidth() / 4 - windowWidth / 2)
positionDown = int(top.winfo_screenheight() / 4 - windowHeight / 2)
# Positions the window in the center of the page.
top.geometry("+{}+{}".format(positionRight, positionDown))
top.configure()
obj = main(top)
app = ABC(master=top)
app.master.title("Zastopic TP automatem")
top.geometry("964x745")
top.resizable(0, 0)
top.mainloop()
|
633620a69a25fff135c78015d8e3c0cf972a48c4
|
[
"Python"
] | 1
|
Python
|
Maximuel/TP-Planning
|
4a1187d7dfc9b43604252bbdd79e8fa9e6bd85bc
|
b0ab4778f9f2cff8a2cf7e2f83c9b08ab2fe1907
|
refs/heads/master
|
<repo_name>Zintinio/SoundCloudFS<file_sep>/SoundCloudFS/SoundCloudFS/fakeFileLayer.cpp
#include "fakeFileLayer.h"
static std::wstring fakeBasePath;
void setBaseFakePath(std::wstring _fakeBasePath)
{
fakeBasePath = _fakeBasePath;
}
std::wstring getFakePath(std::wstring _fakePath)
{
return fakeBasePath + _fakePath;
}<file_sep>/SoundCloudFS/SoundCloudFS/fakeFileLayer.h
#include <string>
void setBaseFakePath(std::wstring _fakeBasePath);
std::wstring getFakePath(std::wstring _fakePath);<file_sep>/SoundCloudFS/SoundCloudFS/stringutils.h
#include <string>
std::string awts(const std::wstring & wstr)
{
std::string str(wstr.length(),' ');
copy(wstr.begin(), wstr.end(), str.begin());
return str;
}
std::wstring astw(const std::string & str)
{
std::wstring wstr(str.length(),L' ');
copy(str.begin(), str.end(), wstr.begin());
return wstr;
}<file_sep>/SoundCloudFS/SoundCloudFS/debugout.h
#include <Windows.h>
#include <string>
#define debugPrint(...) fwprintf(stderr, __VA_ARGS__); fflush(stderr);<file_sep>/README.md
SoundCloudFS
============
Filesystem plugin for soundcloud<file_sep>/SoundCloudFS/SoundCloudFS/main.cpp
#include <Windows.h>
#include "dokan.h"
#include <string>
#include "fakeFileLayer.h"
#include "debugout.h"
#include "stringutils.h"
static int __stdcall sc_openDirectory(LPCWSTR fileName, PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakeFilePath = getFakePath(fileName);
HANDLE handle;
DWORD attr = GetFileAttributes(fakeFilePath.c_str());
if (attr == INVALID_FILE_ATTRIBUTES) {
DWORD error = GetLastError();
debugPrint(L"\terror code = %d\n\n", error);
return error * -1;
}
if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
return -1;
}
handle = CreateFile(
fakeFilePath.c_str(),
0,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (handle == INVALID_HANDLE_VALUE) {
DWORD error = GetLastError();
debugPrint(L"\terror code = %d\n\n", error);
return error * -1;
}
fileInfo->Context = (ULONG64)handle;
return 0;
}
static int __stdcall sc_createFile(
LPCWSTR fileName,
DWORD accessMode,
DWORD shareMode,
DWORD creationDisposition,
DWORD flagsAndAttributes,
PDOKAN_FILE_INFO dokanFileInfo)
{
HANDLE handle;
DWORD fileAttr;
std::wstring fileNameStr = fileName;
std::wstring fakePath = getFakePath(fileName);
if (creationDisposition == CREATE_NEW)
debugPrint(L"\tCREATE_NEW\n");
if (creationDisposition == OPEN_ALWAYS)
debugPrint(L"\tOPEN_ALWAYS\n");
if (creationDisposition == CREATE_ALWAYS)
debugPrint(L"\tCREATE_ALWAYS\n");
if (creationDisposition == OPEN_EXISTING)
debugPrint(L"\tOPEN_EXISTING\n");
if (creationDisposition == TRUNCATE_EXISTING)
debugPrint(L"\tTRUNCATE_EXISTING\n");
fileAttr = GetFileAttributes(fakePath.c_str());
if (fileAttr && fileAttr & FILE_ATTRIBUTE_DIRECTORY)
{
flagsAndAttributes |= FILE_FLAG_BACKUP_SEMANTICS;
}
debugPrint(L"\tFlagsAndAttributes = 0x%x\n", flagsAndAttributes);
handle = CreateFile(
fakePath.c_str(),
accessMode,
shareMode,
NULL,
creationDisposition,
flagsAndAttributes,
NULL);
if (handle == INVALID_HANDLE_VALUE)
{
DWORD error = GetLastError();
debugPrint(L"\terror code = %d\n\n", error);
return error * -1;
}
debugPrint(L"\n");
dokanFileInfo->Context = (ULONG64)handle;
return 0;
}
static int __stdcall sc_unmount(PDOKAN_FILE_INFO dokanFileInfo)
{
debugPrint(L"Unmounted drive\n");
return 0;
}
static int __stdcall sc_createDirectory(LPCWSTR fileName, PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
debugPrint(L"Creating directory at %s\n", fakePath.c_str());
if (!CreateDirectory(fakePath.c_str(), NULL))
{
DWORD error = GetLastError();
debugPrint(L"\terror code = %d\n\n", error);
return error * -1;
}
return 0;
}
static int __stdcall sc_cleanup(LPCWSTR fileName, PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
if (fileInfo->Context || (HANDLE)fileInfo->Context == INVALID_HANDLE_VALUE)
{
debugPrint(L"Cleanup: %s\n\n", fakePath.c_str());
CloseHandle((HANDLE)fileInfo->Context);
fileInfo->Context = 0;
if (fileInfo->DeleteOnClose)
{
debugPrint(L"DeleteOnClose\n");
if (fileInfo->IsDirectory)
{
debugPrint(L"Deleting a directory");
if (!RemoveDirectory(fakePath.c_str()))
{
debugPrint(L"Error code = %d\n\n", GetLastError());
} else {
debugPrint(L"Successfully deleted directory\n\n");
}
} else {
debugPrint(L"Deleting a file");
if (!DeleteFile(fakePath.c_str()))
{
debugPrint(L"Deleting file failed; Error code = %d\n\n", GetLastError());
} else {
debugPrint(L"Successfully deleted file");
}
}
}
} else {
debugPrint(L"Cleaning up an invalid handle: %s\n\n", fakePath.c_str());
return -1;
}
return 0;
}
static int __stdcall sc_closeFile(
LPCWSTR fileName,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring filePath = getFakePath(fileName);
if (fileInfo->Context)
{
debugPrint(L"CloseFile: %s\n", filePath.c_str());
CloseHandle((HANDLE)fileInfo->Context);
fileInfo->Context = 0;
} else {
debugPrint(L"Close: %s\n\n", filePath.c_str());
return 0;
}
return 0;
}
static int __stdcall sc_getVolumeInformation(
LPWSTR volumeNameBuffer,
DWORD volumeNameSize,
LPDWORD volumeSerialNumber,
LPDWORD maximumComponentLength,
LPDWORD fileSystemFlags,
LPWSTR fileSystemNameBuffer,
DWORD fileSystemNameSize,
PDOKAN_FILE_INFO fileInfo)
{
wcscpy_s(volumeNameBuffer, volumeNameSize / sizeof(WCHAR), L"My Soundcloud");
*volumeSerialNumber = 0x19831116;
*maximumComponentLength = 256;
*fileSystemFlags = FILE_CASE_SENSITIVE_SEARCH |
FILE_CASE_PRESERVED_NAMES |
FILE_SUPPORTS_REMOTE_STORAGE |
FILE_UNICODE_ON_DISK |
FILE_PERSISTENT_ACLS;
wcscpy_s(fileSystemNameBuffer, fileSystemNameSize / sizeof(WCHAR), L"SoundCloudFilesystem");
return 0;
}
static int __stdcall sc_readFile(
LPCWSTR fileName,
LPVOID buffer,
DWORD bufferLength,
LPDWORD readLength,
LONGLONG offset_,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
HANDLE handle = (HANDLE)fileInfo->Context;
ULONG offset = (ULONG)offset_;
BOOL opened = false;
if (!handle || handle == INVALID_HANDLE_VALUE) {
debugPrint(L"\tinvalid handle, was it cleaned up?\n");
handle = CreateFile(
fakePath.c_str(),
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
if (handle == INVALID_HANDLE_VALUE) {
debugPrint(L"\tCreateFile error : %d\n\n", GetLastError());
return -1;
}
opened = true;
}
if (SetFilePointer(handle, offset, NULL, FILE_BEGIN) == 0xFFFFFFFF) {
debugPrint(L"\tseek error, offset = %d\n\n", offset);
if (opened)
CloseHandle(handle);
return -1;
}
if (!ReadFile(handle, buffer, bufferLength, readLength, NULL)) {
debugPrint(L"\tread error = %u, buffer length = %d, read length = %d\n\n",
GetLastError(), bufferLength, *readLength);
if (opened)
CloseHandle(handle);
return -1;
} else {
debugPrint(L"\tread %d, offset %d\n\n", *readLength, offset);
}
if (opened)
CloseHandle(handle);
return 0;
}
static int __stdcall sc_writeFile(
LPCWSTR fileName,
LPCVOID buffer,
DWORD numBytesToWrite,
LPDWORD numBytesWritten,
LONGLONG offset_,
PDOKAN_FILE_INFO fileInfo)
{
HANDLE handle = (HANDLE)fileInfo->Context;
ULONG offset = (ULONG)offset_;
BOOL opened = FALSE;
std::wstring fakePath = getFakePath(fileName);
debugPrint(L"WriteFile : %s, offset %164d, length %d\n", fakePath.c_str(), offset, numBytesToWrite);
if (!handle || handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tinvalid handle, was it cleaned up?\n");
handle = CreateFile(
fakePath.c_str(),
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
if (handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tCreateFile error : %d\n\n", GetLastError());
return -1;
}
opened = TRUE;
}
if (fileInfo->WriteToEndOfFile)
{
if (SetFilePointer(handle, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER)
{
debugPrint(L"\tseek error, offset = EOF, error = %d\n", GetLastError());
return -1;
}
} else if (SetFilePointer(handle, offset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
{
debugPrint(L"\seek error, offset = %d, error = %d\n", offset, GetLastError());
}
if (!WriteFile(handle, buffer, numBytesToWrite, numBytesWritten, NULL))
{
debugPrint(L"\twrite error = %u, buffer length = %d, write length = %d\n",
GetLastError(), numBytesToWrite, *numBytesWritten);
return -1;
} else {
debugPrint(L"\twrite %d, offset %d\n\n", *numBytesWritten, offset);
}
if (opened)
CloseHandle(handle);
return 0;
}
static int __stdcall sc_flushFileBuffers(LPCWSTR fileName, PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
HANDLE handle = (HANDLE)fileInfo->Context;
debugPrint(L"FlushFileBuffers : %s\n", fakePath.c_str());
if (!handle || handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tinvalid handle\n\n");
return 0;
}
if (FlushFileBuffers(handle)) {
return 0;
} else {
debugPrint(L"\tflush error code = %d\n", GetLastError());
return -1;
}
}
static int __stdcall sc_getFileInformation(
LPCWSTR fileName,
LPBY_HANDLE_FILE_INFORMATION HandleFileInformation,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
HANDLE handle = (HANDLE)fileInfo->Context;
BOOL opened = false;
debugPrint(L"GetFileInfo : %s\n", fakePath.c_str());
if (!handle || handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tinvalid handle\n\n");
handle = CreateFile(fakePath.c_str(), 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (handle == INVALID_HANDLE_VALUE)
return -1;
opened = TRUE;
}
if (!GetFileInformationByHandle(handle, HandleFileInformation))
{
debugPrint(L"\terror code = %d\n", GetLastError());
if (wcslen(fileName) == 1) {
debugPrint(L"root dir\n");
HandleFileInformation->dwFileAttributes = GetFileAttributes(fakePath.c_str());
} else {
WIN32_FIND_DATA find;
ZeroMemory(&find, sizeof(WIN32_FIND_DATAW));
handle = FindFirstFile(fakePath.c_str(), &find);
if (handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tFindFirstFile error code = %d\n\n", GetLastError());
return -1;
}
HandleFileInformation->dwFileAttributes = find.dwFileAttributes;
HandleFileInformation->ftCreationTime = find.ftCreationTime;
HandleFileInformation->ftLastAccessTime = find.ftLastAccessTime;
HandleFileInformation->ftLastWriteTime = find.ftLastWriteTime;
HandleFileInformation->nFileSizeHigh = find.nFileSizeHigh;
HandleFileInformation->nFileIndexLow = find.nFileSizeLow;
debugPrint(L"\tFindFile OK, file size = %d\n", find.nFileSizeLow);
FindClose(handle);
}
} else {
debugPrint(L"\tGetFIleInformationByHandle success, file size = %d\n",
HandleFileInformation->nFileSizeLow);
}
debugPrint(L"\n");
if (opened)
CloseHandle(handle);
return 0;
}
static int __stdcall sc_findFiles(
LPCWSTR fileName,
PFillFindData fillFindData,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath;
HANDLE hFind;
WIN32_FIND_DATAW findData;
DWORD error;
int count = 0;
fakePath = getFakePath(fileName) + L"\\*";
debugPrint(L"FindFiles : %s\n", fakePath.c_str());
hFind = FindFirstFile(fakePath.c_str(), &findData);
if (hFind == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tinvalid file handle. Error is %u\n\n", GetLastError());
return -1;
}
fillFindData(&findData, fileInfo);
count++;
while (FindNextFile(hFind, &findData) != 0)
{
fillFindData(&findData, fileInfo);
count++;
}
error = GetLastError();
FindClose(hFind);
if (error != ERROR_NO_MORE_FILES)
{
debugPrint(L"\tFindNextFile error. Error is %u\n\n", error);
return -1;
}
debugPrint(L"\tFindFiles return %d entires in %s\n\n", count, fakePath.c_str());
return 0;
}
static int __stdcall sc_setFileAttributes(
LPCWSTR fileName,
DWORD fileAttributes,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
debugPrint(L"SetFileAttributes %s\n", fakePath.c_str());
if (!SetFileAttributes(fakePath.c_str(), fileAttributes))
{
DWORD error = GetLastError();
debugPrint(L"\terror code = %d\n\n", error);
return error * -1;
}
debugPrint(L"\n");
return 0;
}
static int __stdcall sc_setFileTime(
LPCWSTR fileName,
CONST FILETIME* creationTime,
CONST FILETIME* lastAccessTime,
CONST FILETIME* lastWriteTime,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
HANDLE handle;
debugPrint(L"SetFileTime %s\n", fakePath.c_str());
handle = (HANDLE)fileInfo->Context;
if (!handle || handle == INVALID_HANDLE_VALUE) {
debugPrint(L"\tinvalid handle\n\n");
return -1;
}
if (!SetFileTime(handle, creationTime, lastAccessTime, lastWriteTime)) {
DWORD error = GetLastError();
debugPrint(L"\terror code = %d\n\n", error);
return error * -1;
}
debugPrint(L"\n");
return 0;
}
static int __stdcall sc_deleteFile(
LPCWSTR fileName,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
HANDLE handle = (HANDLE)fileInfo->Context;
debugPrint(L"DeleteFile %s\n", fakePath.c_str());
return 0;
}
static int __stdcall sc_deleteDirectory(
LPCWSTR fileName,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
HANDLE handle = (HANDLE)fileInfo->Context;
HANDLE hFind;
WIN32_FIND_DATAW findData;
ULONG fileLen;
debugPrint(L"DeleteDirectory %s\n", fakePath.c_str());
if (fakePath.substr(fakePath.size() - 1) != L"\\")
fakePath += L"\\";
fakePath += L"*";
hFind = FindFirstFile(fakePath.c_str(), &findData);
while (hFind != INVALID_HANDLE_VALUE)
{
if (wcscmp(findData.cFileName, L"..") != 0 &&
wcscmp(findData.cFileName, L".") != 0) {
FindClose(hFind);
debugPrint(L" Directory is not empty: %s\n", findData.cFileName);
return -(int)ERROR_DIR_NOT_EMPTY;
}
if (!FindNextFile(hFind, &findData))
break;
}
FindClose(hFind);
if (GetLastError() == ERROR_NO_MORE_FILES)
return 0;
else
return -1;
}
static int __stdcall sc_moveFile(
LPCWSTR fileName,
LPCWSTR newFileName,
BOOL replaceIfExisting,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
std::wstring newFakePath = getFakePath(newFileName);
BOOL status;
if (fileInfo->Context)
{
CloseHandle((HANDLE)fileInfo->Context);
fileInfo->Context = 0;
}
if (replaceIfExisting)
status = MoveFileEx(fakePath.c_str(), newFakePath.c_str(), MOVEFILE_REPLACE_EXISTING);
else
status = MoveFile(fakePath.c_str(), newFakePath.c_str());
if (status == FALSE)
{
DWORD error = GetLastError();
debugPrint(L"\tMoveFile failed status = %d, code = %d\n", status, error);
return -(int)error;
} else {
return 0;
}
}
static int __stdcall sc_setEndOfFile(
LPCWSTR fileName,
LONGLONG byteOffset,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
HANDLE handle;
LARGE_INTEGER offset;
debugPrint(L"SetEndOfFile %s, %I64d\n", fakePath.c_str(), byteOffset);
handle = (HANDLE)fileInfo->Context;
if (!handle || handle == INVALID_HANDLE_VALUE) {
debugPrint(L"\tinvalid handle\n\n");
return -1;
}
offset.QuadPart = byteOffset;
if (!SetFilePointerEx(handle, offset, NULL, FILE_BEGIN)) {
debugPrint(L"\tSetFilePointer error: %d, offset = %I64d\n\n",
GetLastError(), byteOffset);
return GetLastError() * -1;
}
if (!SetEndOfFile(handle)) {
DWORD error = GetLastError();
debugPrint(L"\terror code = %d\n\n", error);
return error * -1;
}
return 0;
}
static int __stdcall sc_setAllocationSize(
LPCWSTR fileName,
LONGLONG allocSize,
PDOKAN_FILE_INFO fileInfo)
{
HANDLE handle;
LARGE_INTEGER fileSize;
std::wstring fakePath = getFakePath(fileName);
debugPrint(L"SetAllocationSize %s, %I64d\n", fakePath.c_str(), allocSize);
handle = (HANDLE)fileInfo->Context;
if (!handle || handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tinvalid handle\n\n");
return -1;
}
if (GetFileSizeEx(handle, &fileSize)) {
if (allocSize < fileSize.QuadPart) {
fileSize.QuadPart = allocSize;
if (!SetFilePointerEx(handle, fileSize, NULL, FILE_BEGIN)) {
debugPrint(L"\tSetAllocationSize: SetFilePointer error: %d, "
L"offset = %I64d\n\n", GetLastError(), allocSize);
return GetLastError() * -1;
}
if (!SetEndOfFile(handle)) {
DWORD error = GetLastError();
debugPrint(L"\terror code = %d\n\n", error);
return error * -1;
}
}
} else {
DWORD error = GetLastError();
debugPrint(L"\terror code = %d\n\n", error);
return error * -1;
}
return 0;
}
static int __stdcall sc_unlockFile(
LPCWSTR fileName,
LONGLONG byteOffset,
LONGLONG length_,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
HANDLE handle;
LARGE_INTEGER length;
LARGE_INTEGER offset;
debugPrint(L"UnlockFile %s\n", fakePath.c_str());
handle = (HANDLE)fileInfo->Context;
if (!handle || handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tinvalid handle\n\n");
return -1;
}
length.QuadPart = length_;
offset.QuadPart = byteOffset;
if (UnlockFile(handle, offset.HighPart, offset.LowPart, length.HighPart, length.LowPart))
{
debugPrint(L"\tsuccess\n\n");
return 0;
} else {
debugPrint(L"\tfail\n\n");
return -1;
}
}
static int __stdcall sc_lockFile(
LPCWSTR fileName,
LONGLONG byteOffset,
LONGLONG length_,
PDOKAN_FILE_INFO fileInfo)
{
std::wstring fakePath = getFakePath(fileName);
HANDLE handle;
LARGE_INTEGER offset;
LARGE_INTEGER length;
debugPrint(L"LockFile %s\n", fakePath.c_str());
handle = (HANDLE)fileInfo->Context;
if (!handle || handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tinvalid handle\n\n");
return -1;
}
length.QuadPart = length_;
offset.QuadPart = byteOffset;
if (LockFile(handle, offset.HighPart, offset.LowPart, length.HighPart, length.LowPart))
{
debugPrint(L"\tsuccess\n\n");
return 0;
} else {
debugPrint(L"\tfail\n\n");
return -1;
}
}
static int __stdcall sc_setFileSecurity(
LPCWSTR fileName,
PSECURITY_INFORMATION securityInformation,
PSECURITY_DESCRIPTOR securityDescriptor,
ULONG securityDescriptorLength,
PDOKAN_FILE_INFO fileInfo)
{
HANDLE handle;
std::wstring fakePath = getFakePath(fileName);
debugPrint(L"SetFileSEecurity %s\n", fakePath.c_str());
handle = (HANDLE)fileInfo->Context;
if (!handle || handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tinvalid hendle\n\n")
}
if (!SetUserObjectSecurity(handle, securityInformation, securityDescriptor)) {
int error = GetLastError();
debugPrint(L" SetUserObjectSecuity failed: %d\n", error);
return -1;
}
return 0;
}
static int __stdcall sc_getFileSecurity(
LPCWSTR fileName,
PSECURITY_INFORMATION securityInformation,
PSECURITY_DESCRIPTOR securityDescriptor,
ULONG bufferLength,
PULONG lengthNeeded,
PDOKAN_FILE_INFO fileInfo)
{
HANDLE handle;
std::wstring fakePath = getFakePath(fileName);
debugPrint(L"GetFileSecurity %s\n", fakePath);
handle = (HANDLE)fileInfo->Context;
if (!handle || handle == INVALID_HANDLE_VALUE)
{
debugPrint(L"\tinvalid handle \n\n");
return -1;
}
if (!GetUserObjectSecurity(handle, securityInformation, securityDescriptor, bufferLength, lengthNeeded))
{
int error = GetLastError();
if (error == ERROR_INSUFFICIENT_BUFFER)
{
debugPrint(L" GetUserObjectSecurity failed: ERROR_INSUFFICIENT_BUFFER\n");
return error * -1;
} else {
debugPrint(L" GetUserObjectSecurity failed: %d\n", error);
return -1;
}
}
return 0;
}
static int __stdcall sc_getFreeSpace(
PULONGLONG freeBytesAvailable,
PULONGLONG totalNumBytes,
PULONGLONG totalNumFreeBytes,
PDOKAN_FILE_INFO fileInfo)
{
*freeBytesAvailable = (ULONGLONG)0;
*totalNumBytes = (ULONGLONG)0;
*totalNumFreeBytes = (ULONGLONG)(ULONGLONG)0;
return 0;
}
int main(int argc, char** argv)
{
setBaseFakePath(L"C:\\scfs");
PDOKAN_OPTIONS dokanOptions = (PDOKAN_OPTIONS)malloc(sizeof(DOKAN_OPTIONS));
ZeroMemory(dokanOptions, sizeof(DOKAN_OPTIONS));
dokanOptions->Options = DOKAN_OPTION_STDERR;
dokanOptions->Options |= DOKAN_OPTION_DEBUG;
dokanOptions->Options |= DOKAN_OPTION_REMOVABLE;
dokanOptions->Options |= DOKAN_OPTION_KEEP_ALIVE;
dokanOptions->Version = DOKAN_VERSION;
dokanOptions->ThreadCount = 0;
WCHAR MountPoint[MAX_PATH] = L"S:";
dokanOptions->MountPoint = MountPoint;
PDOKAN_OPERATIONS dokanOperations = (PDOKAN_OPERATIONS)malloc(sizeof(DOKAN_OPERATIONS));
ZeroMemory(dokanOperations, sizeof(DOKAN_OPERATIONS));
dokanOperations->CreateFile = &sc_createFile;
dokanOperations->OpenDirectory = &sc_openDirectory;
dokanOperations->CreateDirectory = &sc_createDirectory;
dokanOperations->Cleanup = &sc_cleanup;
dokanOperations->CloseFile = &sc_closeFile;
dokanOperations->ReadFile = &sc_readFile;
dokanOperations->WriteFile = &sc_writeFile;
dokanOperations->FlushFileBuffers = &sc_flushFileBuffers;
dokanOperations->GetFileInformation = &sc_getFileInformation;
dokanOperations->FindFiles = &sc_findFiles;
dokanOperations->FindFilesWithPattern = NULL;
dokanOperations->SetFileAttributes = &sc_setFileAttributes;
dokanOperations->SetFileTime = &sc_setFileTime;
dokanOperations->DeleteFile = &sc_deleteFile;
dokanOperations->DeleteDirectory = &sc_deleteDirectory;
dokanOperations->MoveFile = &sc_moveFile;
dokanOperations->SetEndOfFile = &sc_setEndOfFile;
dokanOperations->SetAllocationSize = &sc_setAllocationSize;
dokanOperations->LockFile = &sc_lockFile;
dokanOperations->UnlockFile = &sc_unlockFile;
dokanOperations->GetFileSecurity = &sc_getFileSecurity;
dokanOperations->SetFileSecurity = &sc_setFileSecurity;
dokanOperations->GetDiskFreeSpace = &sc_getFreeSpace;
dokanOperations->GetVolumeInformation = &sc_getVolumeInformation;
dokanOperations->Unmount = &sc_unmount;
DokanMain(dokanOptions, dokanOperations);
free(dokanOptions);
free(dokanOperations);
return 0;
}
|
60149324572ff1370afd371a7fde433ec49c4052
|
[
"Markdown",
"C++"
] | 6
|
C++
|
Zintinio/SoundCloudFS
|
4c9e6aae9ac64432c5312a34d2c2a89192de8cb9
|
89ae1a823f9ad64bc309a0dc09101cffe53d33f3
|
refs/heads/master
|
<repo_name>tomasruizt/Datasets<file_sep>/setup.py
from distutils.core import setup
setup(
name="datasets",
version="1.0",
packages=["datasets"]
)
<file_sep>/datasets/write.py
import csv
import os
import json
from typing import Iterable, Dict
import datetime
class Writer:
"""
The writer encapsulates all methods needed into an injectable
dependency.
"""
@staticmethod
def save_to_file(header, row_generator, filename, overwrite=False):
if not overwrite and os.path.isfile(filename):
raise FileExistsError("The given filename '%s' already exists and "
"overwrite is set to False".format(filename))
with open(filename, "w") as file:
writer = csv.writer(file, quoting=csv.QUOTE_ALL)
writer.writerow(header)
writer.writerows(row_generator)
@staticmethod
def save_to_json_file(json_iterable: Iterable[Dict], basedir,
overwrite=False):
"""
Dumps a iterable of jsons into a single JSON file, where the
jsons are enclosed in a single list called data.
This function will collect the entire iterable into a list
(in-memory) before attempting to dump it into a file, so be
cautious about the file size.
:param json_iterable: The source of json
:param basedir: The base directory to place the dumped results
:param overwrite: Whether any existing files with the input
filename should be overwritten.
:return:
"""
assert os.path.isdir(basedir), "The base directory doesnt exist."
filename = Writer._generate_results_filename(basedir)
if not overwrite and os.path.isfile(filename):
raise FileExistsError("The given filename '%s' already exists and "
"overwrite is set to False".format(filename))
with open(filename + ".json", "w") as file:
data = {"data": list(json_iterable)}
json.dump(data, file, indent=2)
@staticmethod
def serialize_sparse_vector(array):
serialized_key_values_lst = []
for idx, val in enumerate(array):
if val is not 0:
entry = Writer._serialize_dict_entry(idx, val)
serialized_key_values_lst.append(entry)
serialized_key_values = ",".join(serialized_key_values_lst)
vector_dim = str(len(array))
return vector_dim + "," + serialized_key_values
@staticmethod
def _serialize_dict_entry(key, val):
return str(key) + ":" + "{:.8f}".format(val)
@staticmethod
def _generate_results_filename(basedir) -> str:
"""
Generate a folder named after the current date inside basedir
"""
date = datetime.datetime.today().strftime("%Y-%m-%d_at_%H-%M-%S")
filename = os.path.join(basedir, date)
return filename
<file_sep>/TODO.md
# TODOs
## Testing
* Writer class<file_sep>/README.md
# Datasets
This is a lightweight package with tools to create datasets
<file_sep>/datasets/__init__.py
from datasets.write import Writer
|
8e9793c6e6fac11426edf0ea7e6eedcc265a8726
|
[
"Markdown",
"Python"
] | 5
|
Python
|
tomasruizt/Datasets
|
0b645c35702b6bb08b22d3c7359552f6bbe9e1c5
|
5d14a4a17fc57ca8c673a010d0a974910d2616c6
|
refs/heads/master
|
<repo_name>rsterbin/liturgicalendar<file_sep>/bin/calendar_builder/utils.py
import datetime
import re
def day_to_lookup(day):
"""Turns a day into its lookup key in the full year hash"""
return day.strftime('%Y-%m-%d')
def weekday(day):
"""Returns the day of the week as a lowercase three-character abbreviation (e.g., sun)"""
return day.strftime('%A').lower()[:3]
def ftime(time):
"""Returns a time formatted as 9:00 AM"""
return re.sub(r'^0', '', time.strftime('%I:%M %p'))
<file_sep>/bin/calendar_builder/storage.py
import logging
from sqlalchemy import text
from .models import Calculated, CalculatedService, Cached, CachedService
class Storage:
"""Handles storing a static year to the appropriate table"""
def __init__(self, year, session):
"""Constructor"""
self.year = year
self.session = session
self.logger = logging.getLogger(__name__)
def save_calculated(self, static):
"""Saves a static year to the calculated table"""
self.session.query(Calculated).\
filter(text("extract(year from target_date) = :year")).\
params(year=self.year).\
delete(synchronize_session=False)
for cdate in static.all_days:
static_day = static.all_days[cdate]
if static_day.base_block is not None:
self.session.add(self.new_calc_target(static_day, static_day.base_block, 'base'))
if static_day.vigil_block is not None:
self.session.add(self.new_calc_target(static_day, static_day.vigil_block, 'vigil'))
self.session.commit()
def new_calc_target(self, day, block, which):
"""Creates a Calculated target from a static block"""
calc = Calculated(
target_date=day.day,
target_block=which,
name=block.name,
color=block.color,
note=block.note
)
for service in block.services:
calc.services.append(CalculatedService(
name=service.name,
start_time=service.start_time
))
return calc
def save_cached(self, static):
"""Saves a static year to the cached table"""
self.session.query(Cached).\
filter(text("extract(year from target_date) = :year")).\
params(year=self.year).\
delete(synchronize_session=False)
for cdate in static.all_days:
static_day = static.all_days[cdate]
if static_day.base_block is not None:
self.session.add(self.new_cache_target(static_day, static_day.base_block, 'base'))
if static_day.vigil_block is not None:
self.session.add(self.new_cache_target(static_day, static_day.vigil_block, 'vigil'))
self.session.commit()
def new_cache_target(self, day, block, which):
"""Creates a Cached target from a static block"""
cache = Cached(
target_date=day.day,
target_block=which,
name=block.name,
color=block.color,
note=block.note
)
for service in block.services:
cache.services.append(CachedService(
name=service.name,
start_time=service.start_time
))
return cache
<file_sep>/front/lib/DateRange.js
/**
* Date range handling
*/
var DateRange = function(start, end) {
this.start = start;
this.end = end;
};
Object.assign(DateRange.prototype, {
/**
* Returns the range as a string (for use in logging)
*
* @return string the date range as a string
*/
toString: function () {
return this.start.format('YYYY-MM-DD') + ' to ' + this.end.format('YYYY-MM-DD');
},
/**
* Returns the start date as a ymd string
*
* @return string the start date in ymd format
*/
startYmd: function () {
return this.start.format('YYYY-MM-DD');
},
/**
* Returns the end date as a ymd string
*
* @return string the end date in ymd format
*/
endYmd: function () {
return this.end.format('YYYY-MM-DD');
},
/**
* Returns whether the range is valid (start before end)
*
* @return boolean whether the range is valid
*/
isValid: function () {
return this.end > this.start;
},
/**
* Returns the number of days in this range, inclusive
*
* @return integer the number of days
*/
days: function() {
return this.end.diff(this.start, 'days') + 1;
}
});
module.exports = DateRange;
<file_sep>/front/lib/Calendar.js
/**
* Calendar schedule handling
*/
var moment = require('moment');
var Calendar = function() {
this.schedule = {};
};
Object.assign(Calendar.prototype, {
/**
* Loads up the calendar from the rows given
*
* The ID field is passed in, as this can cover both cached and calculated
* schedules. The expected field names for everything else are:
* - target_date
* - target_block
* - name
* - color
* - note
* - service_name
* - service_start_time
*
* @param Array rows the rows
* @param string idField the field with the ID in it
*/
loadFromRows: function (rows, idField) {
this.schedule = {};
var cdate = null;
var cid = null;
var cblock = null;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (cdate != moment(row['target_date']).format('YYYY-MM-DD')) {
cdate = moment(row['target_date']).format('YYYY-MM-DD');
this.schedule[cdate] = {
date: cdate,
blocks: {}
};
}
if (cid != row[idField]) {
cid = row[idField];
cblock = row['target_block'];
this.schedule[cdate]['blocks'][cblock] = {
name: row['name'],
color: row['color'],
note: row['note'],
services: []
};
}
this.schedule[cdate]['blocks'][cblock]['services'].push({
service_name: row['service_name'],
service_start_time: row['service_start_time']
});
}
},
/**
* Gets the schedule
*
* The schedule format is:
* [YYYY-MM-DD]: {
* blocks: {
* base: {
* name: 'Weekday',
* color: 'green',
* note: 'Today is a day',
* services: [
* { service_name: 'Morning Prayer', service_time: {8:30am} },
* ...etc
* ]
* }
* }
* }
*
* @return object the schedule
*/
getSchedule: function () {
return this.schedule;
},
/**
* Returns the number of days accounted for in this calendar
*
* @return integer the number of days
*/
days: function() {
return Object.keys(this.schedule).length;
}
});
module.exports = Calendar;
<file_sep>/build/dev-vagrant/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Creating a "config.yml" file in this directory allows you to override some
# defaults in this Vagrantfile:
#
# * `front_ip` changes the IPv4 address used by your frontend vm
# * `back_ip` changes the IPv4 address used by your backend vm
# * `db_ip` changes the IPv4 address used by your db vm
#
require 'yaml'
dir = File.dirname(File.expand_path(__FILE__))
cfgpath = "#{dir}/config.yml"
if File.exist?(cfgpath)
cfg = YAML.load_file(cfgpath)
else
cfg = {}
end
Vagrant.configure("2") do |config|
# select our IP addresses
front_ipaddr = cfg['front_ip'] || "192.168.0.23"
back_ipaddr = cfg['back_ip'] || "192.168.0.24"
db_ipaddr = cfg['db_ip'] || "192.168.0.25"
# define our hosts
config.vm.define "front" do |front|
front.vm.box = "ubuntu/trusty64"
front.vm.network "private_network", ip: front_ipaddr
end
config.vm.define "back" do |back|
back.vm.box = "ubuntu/trusty64"
back.vm.network "private_network", ip: back_ipaddr
end
config.vm.define "db" do |db|
db.vm.box = "ubuntu/trusty64"
db.vm.network "private_network", ip: db_ipaddr
end
# write out the hosts.ini file on vagrant up
config.trigger.after :up do
info "Writing the ansible hosts.ini file"
`rm -f ./hosts.ini`
`echo "" >> ./hosts.ini`
`echo "[tag_type_front]" >> ./hosts.ini`
`echo "#{front_ipaddr} ansible_private_key_file=./.vagrant/machines/front/virtualbox/private_key" >> ./hosts.ini`
`echo "" >> ./hosts.ini`
`echo "[tag_type_back]" >> ./hosts.ini`
`echo "#{back_ipaddr} ansible_private_key_file=./.vagrant/machines/back/virtualbox/private_key" >> ./hosts.ini`
`echo "" >> ./hosts.ini`
`echo "[tag_type_db]" >> ./hosts.ini`
`echo "#{db_ipaddr} ansible_private_key_file=./.vagrant/machines/db/virtualbox/private_key" >> ./hosts.ini`
`echo "" >> ./hosts.ini`
`echo "[tag_environment_dev:children]" >> ./hosts.ini`
`echo "tag_type_front" >> ./hosts.ini`
`echo "tag_type_back" >> ./hosts.ini`
`echo "tag_type_db" >> ./hosts.ini`
`echo "" >> ./hosts.ini`
`echo "[vagrant:children]" >> ./hosts.ini`
`echo "tag_environment_dev" >> ./hosts.ini`
end
end
<file_sep>/database/migrations/20170127204345_schema_federal_holidays.sql
-- rambler up
--
-- This table defines the federal holidays, which are calculated according to an
-- algorithm the way feasts are, but do not carry colors or services, just notes
-- and sometimes special church open/close times.
--
CREATE TABLE federal_holidays (
holiday_id serial,
name text NOT NULL,
code text NOT NULL,
calculate_from text NOT NULL,
algorithm text NOT NULL,
distance integer NOT NULL,
placement_index integer,
open_time time,
close_time time,
note text,
skip_name boolean NOT NULL DEFAULT FALSE,
valid_start timestamp with time zone NULL,
valid_end timestamp with time zone NULL,
CONSTRAINT federal_holidays_pk PRIMARY KEY (holiday_id)
);
CREATE INDEX federal_holidays_code_idx ON federal_holidays (code);
CREATE INDEX federal_holidays_placement_idx ON federal_holidays (placement_index);
-- rambler down
DROP TABLE federal_holidays;
<file_sep>/database/migrations/20160810133220_stmarys_seasons.sql
-- rambler up
--
-- Define the liturgical seasons of the year
--
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, continue_counting, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Christmas', 'christmas', 'white', 0,
'christmas', 'days_after', 12, 55,
1, false, 'standard-no-confessions',
'Weekday of Christmas', 'Weekday of Christmas', 'Weekday of Christmas', 'Weekday of Christmas',
'Weekday of Christmas', 'Weekday of Christmas', 'Eve of the %s Sunday after Christmas Day', 'The %s Sunday after Christmas Day',
NULL, NULL, NULL, NULL,
'Friday Abstinence is not observed during the Christmas Season.', 'Confessions are not heard, except by appointment, on the Saturdays of the Christmas Season.', NULL
);
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, continue_counting, has_last_sunday, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Ordinary Time After Epiphany', 'after-epiphany', 'green', 1,
'easter', 'tuesdays_before', 6, 60,
1, false, true, 'standard',
'Weekday', 'Weekday', 'Weekday', 'Weekday',
'Weekday', 'Weekday', 'Eve of the %s Sunday after the Epiphany', 'The %s Sunday after the Epiphany',
NULL, NULL, NULL, NULL,
'Friday Abstinence', NULL, NULL
);
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, continue_counting, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Lent', 'lent', 'purple', 2,
'easter', 'days_before', 8, 45,
1, false, 'standard-stations',
'Weekday of Lent', 'Weekday of Lent', 'Weekday of Lent', 'Weekday of Lent',
'Weekday of Lent', 'Weekday of Lent', 'Eve of the %s Sunday in Lent', 'The %s Sunday in Lent',
'Abstinence', 'Abstinence', 'Abstinence', 'Abstinence',
'Lenten Friday Abstinence', 'Abstinence', 'Abstinence is not observed on Sundays in Lent.'
);
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, continue_counting, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Holy Week', 'holy-week', 'red', 3,
'easter', 'days_before', 1, 15,
1, false, 'standard',
'Monday of Holy Week', 'Tuesday of Holy Week', 'Wednesday of Holy Week', 'Thursday of Holy Week',
'Good Friday', 'Holy Saturday', 'Eve of the Sunday of the Passion: Palm Sunday', 'The Sunday of the Passion: Palm Sunday',
'Abstinence', 'Abstinence', 'Abstinence', 'Abstinence',
'Fast & Abstinence', 'Abstinence', 'Abstinence is not observed on Palm Sunday.'
);
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, continue_counting, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Easter Week', 'easter-week', 'gold', 4,
'easter', 'days_after', 7, 15,
1, false, 'standard-no-confessions',
'Monday in Easter Week', 'Tuesday in Easter Week', 'Wednesday in Easter Week', 'Thursday in Easter Week',
'Friday in Easter Week', 'Saturday in Easter Week', 'Eve of the %s Sunday of Easter', 'The %s Sunday of Easter',
NULL, NULL, NULL, NULL,
'Friday abstinence is not observed in Eastertide.', 'Confessions are heard only by appointment during Easter Week.', NULL
);
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, continue_counting, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Easter', 'easter', 'white', 5,
'easter', 'weeks_after', 7, 60,
1, true, 'standard',
'Weekday of Easter', 'Weekday of Easter', 'Weekday of Easter', 'Weekday of Easter',
'Weekday of Easter', 'Weekday of Easter', 'Eve of the %s Sunday of Easter', 'The %s Sunday of Easter',
NULL, NULL, NULL, NULL,
'Friday abstinence is not observed in Eastertide.', NULL, NULL
);
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, continue_counting, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Ordinary Time After Pentecost (Spring)', 'pentecost-spring', 'green', 6,
'easter', 'weeks_after', 9, 60,
1, false, 'standard',
'Weekday', 'Weekday', 'Weekday', 'Weekday',
'Weekday', 'Weekday', 'Eve of the %s Sunday after Pentecost', 'The %s Sunday after Pentecost',
NULL, NULL, NULL, NULL,
'Friday Abstinence', NULL, NULL
);
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, continue_counting, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Ordinary Time After Pentecost (Summer)', 'pentecost-summer', 'green', 7,
'christmas', 'saturdays_before', 12, 60,
1, true, 'standard-summer',
'Weekday', 'Weekday', 'Weekday', 'Weekday',
'Weekday', 'Weekday', 'Eve of the %s Sunday after Pentecost', 'The %s Sunday after Pentecost',
NULL, NULL, NULL, NULL,
'Friday Abstinence', NULL, NULL
);
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, has_last_sunday, continue_counting, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Ordinary Time After Pentecost (Fall)', 'pentecost-fall', 'green', 8,
'christmas', 'saturdays_before', 4, 60,
1, true, true, 'standard',
'Weekday', 'Weekday', 'Weekday', 'Weekday',
'Weekday', 'Weekday', 'Eve of the %s Sunday after Pentecost', 'The %s Sunday after Pentecost',
NULL, NULL, NULL, NULL,
'Friday Abstinence', NULL, NULL
);
INSERT INTO seasons (name, code, color, sort_order,
calculate_from, algorithm, distance, weekday_precedence,
counting_index, continue_counting, schedule_pattern,
name_pattern_mon, name_pattern_tue, name_pattern_wed, name_pattern_thu,
name_pattern_fri, name_pattern_sat, name_pattern_sat_vigil, name_pattern_sun,
default_note_mon, default_note_tue, default_note_wed, default_note_thu,
default_note_fri, default_note_sat, default_note_sun
) VALUES ('Advent', 'advent', 'purple', 9,
'christmas', 'days_before', 1, 60,
1, false, 'standard',
'Weekday of Advent', 'Weekday of Advent', 'Weekday of Advent', 'Weekday of Advent',
'Weekday of Advent', 'Weekday of Advent', 'Eve of the %s Sunday of Advent', 'The %s Sunday of Advent',
NULL, NULL, NULL, NULL,
'Friday Abstinence', NULL, NULL
);
-- rambler down
TRUNCATE TABLE seasons RESTART IDENTITY;
<file_sep>/front/lib/errors/StateError.js
/**
* Error due to incorrect state of the app
*/
var StateError = function (message) {
this.message = message;
this.stack = (new Error()).stack;
};
StateError.prototype = Object.create(Error.prototype);
StateError.prototype.constructor = StateError;
StateError.prototype.name = 'StateError';
module.exports = StateError;
<file_sep>/database/migrations/20170108223042_schema_floating_feasts.sql
-- rambler up
--
-- This table defines the floating feasts, which are not attached to a
-- particular calendar day, or calculated from a particular holiday, but are
-- placed where they best fit, according to a particular algorithm.
--
CREATE TABLE floating_feasts (
floating_id serial,
name text NOT NULL,
code text NOT NULL,
otype_id integer NOT NULL,
placement_index integer,
algorithm text NOT NULL,
schedule_pattern text,
has_eve boolean NOT NULL DEFAULT FALSE,
eve_schedule_pattern text,
eve_name text,
color text,
note text,
valid_start timestamp with time zone NULL,
valid_end timestamp with time zone NULL,
CONSTRAINT floating_feasts_pk PRIMARY KEY (floating_id),
CONSTRAINT floating_feasts_otype_fk FOREIGN KEY (otype_id)
REFERENCES observance_types (otype_id)
ON DELETE RESTRICT ON UPDATE NO ACTION
);
CREATE INDEX floating_feasts_code_idx ON floating_feasts (code);
CREATE INDEX floating_feasts_placement_idx ON floating_feasts (placement_index);
-- rambler down
DROP TABLE floating_feasts;
<file_sep>/front/server.js
var CalendarApp = require('./app/app.js');
var config = require('./app/config.js');
app = new CalendarApp(config);
app.startup();
app.listen();
<file_sep>/database/migrations/20170204161816_schema_overrides.sql
-- rambler up
--
-- These tables define the overrides used to tweak a particular block in the liturgical calendar
--
CREATE TABLE overrides (
override_id serial,
target_date date NOT NULL,
target_block text NOT NULL CHECK (target_block IN ('base', 'vigil')),
name text,
color text,
note text,
CONSTRAINT overrides_pk PRIMARY KEY (override_id),
CONSTRAINT overrides_target_uq UNIQUE (target_date, target_block)
);
CREATE INDEX overrides_target_date_idx ON overrides (target_date);
CREATE TABLE override_services (
override_service_id serial,
override_id integer NOT NULL,
name text NOT NULL,
start_time time with time zone NOT NULL,
CONSTRAINT override_services_pk PRIMARY KEY (override_service_id),
CONSTRAINT override_services_target_uq FOREIGN KEY (override_id)
REFERENCES overrides (override_id)
ON DELETE CASCADE ON UPDATE NO ACTION
);
-- rambler down
DROP TABLE override_services;
DROP TABLE overrides;
<file_sep>/database/migrations/20160810135100_schema_moveable_feasts.sql
-- rambler up
--
-- This table defines the moveable feasts, which are not attached to a
-- particular calendar day, but are calculated, usually from the date of Easter
-- or the date of Christmas, but sometimes by other means.
--
CREATE TABLE moveable_feasts (
moveable_id serial,
name text NOT NULL,
code text NOT NULL,
otype_id integer NOT NULL,
placement_index integer,
calculate_from text NOT NULL,
algorithm text NOT NULL,
distance integer,
schedule_pattern text,
has_eve boolean NOT NULL DEFAULT FALSE,
eve_schedule_pattern text,
eve_name text,
color text,
note text,
valid_start timestamp with time zone NULL,
valid_end timestamp with time zone NULL,
CONSTRAINT moveable_feasts_pk PRIMARY KEY (moveable_id),
CONSTRAINT moveable_feasts_otype_fk FOREIGN KEY (otype_id)
REFERENCES observance_types (otype_id)
ON DELETE RESTRICT ON UPDATE NO ACTION,
CONSTRAINT moveable_feasts_calc_from CHECK (calculate_from IN ('easter', 'christmas', NULL))
);
CREATE INDEX moveable_feasts_code_idx ON moveable_feasts (code);
CREATE INDEX moveable_feasts_placement_idx ON moveable_feasts (placement_index);
-- rambler down
DROP TABLE moveable_feasts;
<file_sep>/front/app/v1/routes.js
var express = require('express');
var Promise = require('bluebird');
var moment = require('moment');
var DatabaseStorage = require('../../lib/storage/database.js');
var DateRange = require('../../lib/DateRange.js');
var InputError = require('../../lib/errors/InputError.js');
var TemporaryError = require('../../lib/errors/TemporaryError.js');
function checkRange(start, end) {
return new Promise((resolve, reject) => {
if (!start || !end) {
return reject(new InputError('Start and end dates are required', 110));
}
var dts = moment(start, 'YYYY-MM-DD');
var dte = moment(end, 'YYYY-MM-DD');
if (!dts.isValid()) {
return reject(new InputError('Start is not a valid date (use format YYYY-MM-DD)', 120));
}
if (!dte.isValid()) {
return reject(new InputError('End is not a valid date (use format YYYY-MM-DD)', 121));
}
var range = new DateRange(dts, dte);
if (!range.isValid()) {
return reject(new InputError('Date range ' + range + ' is invalid: Start is before end', 122));
}
if (range.days() > 365) {
return reject(new InputError('Date range ' + range + ' is invalid: Range is more than a year long', 141));
}
return resolve(range);
});
}
function findForRange(range, mc, db, mq) {
var storage = new DatabaseStorage(db);
return storage.getForDateRange(range.startYmd(), range.endYmd())
.then(calendar => {
if (calendar.days() < range.days()) {
return mq.writeCalcRequest({ start: range.startYmd(), end: range.endYmd() })
.then(data => { return new TemporaryError('Calculating calendar for date range ' + range, 600); },
error => error);
}
return calendar.getSchedule();
}, error => error);
}
function doOkay(message) {
return new Promise((resolve, reject) => {
if (message instanceof TemporaryError) {
resolve({ status: 'wait', message: message.message, code: message.code });
} else if (message instanceof InputError) {
resolve({ status: 'failure', message: message.message, code: message.code });
} else if (message instanceof Error) {
resolve({ status: 'error', message: message.message });
} else {
resolve({ status: 'success', data: message });
}
});
}
function setupRoutes(registry) {
var router = express.Router();
router.get('/', (req, res, next) => {
checkRange(req.query.start, req.query.end)
.then(range => findForRange(range, registry.getMemcached(), registry.getDatabase(), registry.getMessageQueue()),
error => error)
.then(message => doOkay(message))
.then(json => { res.json(json); })
.catch(next);
});
return router;
}
module.exports = setupRoutes;
<file_sep>/bin/calendar_builder/fetch/floating_feasts.py
import copy
import datetime
from dateutil.easter import *
from sqlalchemy import text
from sqlalchemy.orm import eagerload,joinedload
from ..models import FloatingFeast, ServicePattern
from .. import utils
from ..valid_dates import valid_in_list
class FloatingFeasts:
"""Class for placing floating feasts in a year"""
def __init__(self, session, year):
"""Sets up the placer"""
self.session = session
self.year = year
self.load_feasts()
def load_feasts(self):
"""Loads the feasts for this year"""
self.by_code = {}
self.feasts = []
for instance in self.session.query(FloatingFeast).\
options(joinedload(FloatingFeast.otype)).\
options(joinedload(FloatingFeast.all_patterns)).\
options(joinedload(FloatingFeast.all_eve_patterns)).\
filter(text("valid_for_date(:jan_first, floating_feasts.valid_start, floating_feasts.valid_end)")).\
params(jan_first=datetime.date(self.year, 1, 1).strftime('%Y-%m-%d')).\
order_by(FloatingFeast.placement_index):
code = instance.code
if code not in self.by_code:
self.by_code[code] = []
self.by_code[code].append(instance)
self.feasts.append(code)
def get_for_year(self, year, full_year):
"""Given the current calendar, find the days the floating feasts should be placed"""
by_date = {}
for code in self.feasts:
for feast in self.by_code[code]:
if feast.algorithm == 'of_our_lady':
by_date = self.of_our_lady(feast, year, full_year, by_date)
elif feast.algorithm == 'of_our_lady_old':
by_date = self.of_our_lady_old(feast, year, full_year, by_date)
elif feast.algorithm == 'first_bcp':
by_date = self.first_bcp(feast, year, full_year, by_date)
elif feast.algorithm == 'parish_requiem':
by_date = self.parish_requiem(feast, year, full_year, by_date)
elif feast.algorithm == 'parish_requiem_5_skip':
by_date = self.parish_requiem_5_skip(feast, year, full_year, by_date)
elif feast.algorithm == 'parish_requiem_4_skip':
by_date = self.parish_requiem_4_skip(feast, year, full_year, by_date)
else:
raise ValueError('"{algorithm}" is an unknown algorithm for floating feasts'.format(algorithm=repr(feast.algorithm)))
return by_date.values()
def of_our_lady(self, feast, year, full_year, by_date):
"""Saturdays in a green season without another commemoration are Of Our Lady"""
return self._internal_of_our_lady(feast, year, full_year, by_date, False)
def of_our_lady_old(self, feast, year, full_year, by_date):
"""Year-round, Saturdays without another commemoration were Of Our Lady"""
return self._internal_of_our_lady(feast, year, full_year, by_date, True)
def _internal_of_our_lady(self, feast, year, full_year, by_date, is_old_style):
"""Handles both the old and new versions of Of Our Lady"""
current_day = datetime.date(year, 1, 1)
while current_day.year == year:
# only Saturdays
if utils.weekday(current_day) != 'sat':
current_day = current_day + datetime.timedelta(days=1)
continue
# only if the feast is valid for this day
ok = valid_in_list([feast], current_day)
if ok is None:
current_day = current_day + datetime.timedelta(days=1)
continue
# (new style) only if the season is green
cdate = utils.day_to_lookup(current_day)
if not is_old_style and full_year[cdate].season.color != 'green':
current_day = current_day + datetime.timedelta(days=1)
continue
# only if another feast is not scheduled for that day
if len(full_year[cdate].feasts) == 0:
if cdate not in by_date:
by_date[cdate] = { 'day': copy.deepcopy(current_day) , 'feasts': [] }
by_date[cdate]['feasts'].append(feast)
current_day = current_day + datetime.timedelta(days=1)
return by_date
def first_bcp(self, feast, year, full_year, by_date):
"""First free weekday after Pentecost for which there's no other commemoration"""
current_day = easter(year) + datetime.timedelta(weeks=7)
while current_day.year == year:
# only weekdays
if utils.weekday(current_day) == 'sun':
current_day = current_day + datetime.timedelta(days=1)
continue
# only if the feast is valid for this day
ok = valid_in_list([feast], current_day)
if ok is None:
current_day = current_day + datetime.timedelta(days=1)
continue
# only if another feast is not scheduled for that day
cdate = utils.day_to_lookup(current_day)
if len(full_year[cdate].feasts) == 0:
if cdate not in by_date:
by_date[cdate] = { 'day': copy.deepcopy(current_day) , 'feasts': [] }
by_date[cdate]['feasts'].append(feast)
break
current_day = current_day + datetime.timedelta(days=1)
return by_date
def parish_requiem(self, feast, year, full_year, by_date):
"""First five days available after All Souls, demoting commemorations to notes"""
return self._internal_parish_requiem(feast, year, full_year, by_date, 5, False)
def parish_requiem_5_skip(self, feast, year, full_year, by_date):
"""First five days available after All Souls, skipping commemorations"""
return self._internal_parish_requiem(feast, year, full_year, by_date, 5, True)
def parish_requiem_4_skip(self, feast, year, full_year, by_date):
"""First four days available after All Souls, skipping commemorations"""
return self._internal_parish_requiem(feast, year, full_year, by_date, 4, True)
def _internal_parish_requiem(self, feast, year, full_year, by_date, count_days, skip_comms):
"""Handles the old and new versions of the Parish Requiem"""
current_day = datetime.date(year, 11, 2)
all_souls = None
if count_days == 5:
names = [' (A-E)', ' (F-K)', ' (L-M)', ' (O-Q)', ' (R-Z)']
else:
names = ['', '', '', '']
index = 0
while current_day.year == year:
cdate = utils.day_to_lookup(current_day)
if all_souls is None:
for f in full_year[cdate].feasts:
if f.code() == 'all-souls':
all_souls = full_year[cdate].day
break
else:
ok = True
cname = None
if skip_comms:
if full_year[cdate].current_precedence < 60:
ok = False
else:
if full_year[cdate].current_precedence < 50:
ok = False
else:
if full_year[cdate].current_feast is not None:
cname = '(' + full_year[cdate].current_feast.name() + ')'
if ok:
if index < len(names):
f = copy.deepcopy(feast)
f.name = feast.name + names[index]
f.note = cname
if cdate not in by_date:
by_date[cdate] = { 'day': copy.deepcopy(current_day) , 'feasts': [] }
by_date[cdate]['feasts'].append(f)
index += 1
else:
break
current_day = current_day + datetime.timedelta(days=1)
return by_date
<file_sep>/bin/queue_reader
#!/usr/bin/python
from calendar_builder.process import read_calc_request_queue
read_calc_request_queue.main()
<file_sep>/database/migrations/20160810131200_schema_services.sql
-- rambler up
--
-- These tables define the services, the selection of services that make up a
-- daily (or eve-of) schedule, and the patterns that define which schedule is
-- chosen for which day of the week.
--
CREATE TABLE services (
service_id serial,
name text NOT NULL,
start_time time with time zone NOT NULL,
is_default boolean NOT NULL DEFAULT false,
CONSTRAINT services_pk PRIMARY KEY (service_id)
);
CREATE INDEX services_start_time_idx ON services (start_time);
CREATE INDEX services_default_idx ON services (is_default);
CREATE TABLE schedules (
schedule_id serial,
name text NOT NULL,
code text,
valid_start timestamp with time zone NULL,
valid_end timestamp with time zone NULL,
is_default boolean NOT NULL DEFAULT false,
is_custom boolean NOT NULL DEFAULT false,
CONSTRAINT schedules_pk PRIMARY KEY (schedule_id)
);
CREATE INDEX schedules_code_idx ON schedules (code, valid_start, valid_end);
CREATE INDEX schedules_default_idx ON schedules (is_default, valid_start, valid_end);
CREATE TABLE schedule_services (
schedule_id integer NOT NULL,
service_id integer NOT NULL,
CONSTRAINT schedule_services_pk PRIMARY KEY (schedule_id, service_id),
CONSTRAINT schedule_services_schedule_fk FOREIGN KEY (schedule_id)
REFERENCES schedules (schedule_id)
ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT schedule_services_service_fk FOREIGN KEY (service_id)
REFERENCES services (service_id)
ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE TABLE service_patterns (
pattern_id serial,
name text NOT NULL,
code text NOT NULL,
schedule_code_mon text,
schedule_code_mon_with_vigil text,
schedule_code_mon_vigil text,
schedule_code_tue text,
schedule_code_tue_with_vigil text,
schedule_code_tue_vigil text,
schedule_code_wed text,
schedule_code_wed_with_vigil text,
schedule_code_wed_vigil text,
schedule_code_thu text,
schedule_code_thu_with_vigil text,
schedule_code_thu_vigil text,
schedule_code_fri text,
schedule_code_fri_with_vigil text,
schedule_code_fri_vigil text,
schedule_code_sat text,
schedule_code_sat_with_vigil text,
schedule_code_sat_vigil text,
schedule_code_sun text,
schedule_code_sun_with_vigil text,
schedule_code_sun_vigil text,
valid_start timestamp with time zone,
valid_end timestamp with time zone,
CONSTRAINT service_patterns_pk PRIMARY KEY (pattern_id)
);
CREATE INDEX service_patterns_code_idx ON service_patterns (code, valid_start, valid_end);
--
-- These functions make it easier to pull the right schedules and service patterns
--
CREATE OR REPLACE FUNCTION valid_for_date(
given timestamp with time zone,
valid_start timestamp with time zone,
valid_end timestamp with time zone
) RETURNS boolean AS '
SELECT ( $2 is null and $3 is null )
or ( $2 is null and $3 > $1 )
or ( $3 is null and $2 < $1 )
or ( $2 is not null and $3 is not null and $1 between $2 and $3 );'
LANGUAGE SQL;
CREATE OR REPLACE FUNCTION valid_for_date_range(
given_start timestamp with time zone,
given_end timestamp with time zone,
valid_start timestamp with time zone,
valid_end timestamp with time zone
) RETURNS boolean AS '
SELECT ( $3 is null and $4 is null )
or ( $3 is null and $4 >= $1 )
or ( $4 is null and $3 <= $2 )
or ( $3 is not null and $4 is not null and $3 <= $2 and $4 >= $1 );'
LANGUAGE SQL;
-- rambler down
DROP TABLE service_patterns;
DROP TABLE schedule_services;
DROP TABLE schedules;
DROP TABLE services;
DROP FUNCTION valid_for_date(given timestamp with time zone, valid_start timestamp with time zone, valid_end timestamp with time zone);
DROP FUNCTION valid_for_date_range(given_start timestamp with time zone, given_end timestamp with time zone, valid_start timestamp with time zone, valid_end timestamp with time zone);
<file_sep>/bin/calendar_builder/fetch/moveable_feasts.py
import datetime
from sqlalchemy import text
from sqlalchemy.orm import eagerload,joinedload
from ..models import MoveableFeast, ServicePattern
class MoveableFeasts:
"""Class for placing moveable feasts in a year"""
def __init__(self, session, year):
"""Sets up the placer"""
self.session = session
self.year = year
self.load_feasts()
def load_feasts(self):
"""Loads the feasts for this year"""
self.by_code = {}
self.feasts = []
for instance in self.session.query(MoveableFeast).\
options(joinedload(MoveableFeast.otype)).\
options(joinedload(MoveableFeast.all_patterns)).\
options(joinedload(MoveableFeast.all_eve_patterns)).\
filter(text("valid_for_date(:jan_first, moveable_feasts.valid_start, moveable_feasts.valid_end)")).\
params(jan_first=datetime.date(self.year, 1, 1).strftime('%Y-%m-%d')).\
order_by(MoveableFeast.placement_index):
code = instance.code
if code not in self.by_code:
self.by_code[code] = []
self.by_code[code].append(instance)
self.feasts.append(code)
def feasts_by_date(self):
"""Selects the right feast for each day"""
by_date = []
for code in self.feasts:
f = self.by_code[code][0]
by_date.append({ 'day': f.day(self.year), 'feasts': self.by_code[code] })
return by_date
<file_sep>/bin/calendar_builder/fetch/fixed_feasts.py
import datetime
from sqlalchemy import text
from sqlalchemy.orm import eagerload,joinedload
import sys
from ..models import FixedFeast, ServicePattern
class FixedFeasts:
"""Class for placing fixed feasts in a year"""
def __init__(self, session, year):
"""Sets up the placer"""
self.session = session
self.year = year
self.load_feasts()
def load_feasts(self):
"""Loads the feasts for this year"""
self.by_day = {}
for instance in self.session.query(FixedFeast).\
options(joinedload(FixedFeast.otype)).\
options(joinedload(FixedFeast.all_patterns)).\
options(joinedload(FixedFeast.all_eve_patterns)).\
filter(text("valid_for_date(:jan_first, fixed_feasts.valid_start, fixed_feasts.valid_end)")).\
params(jan_first=datetime.date(self.year, 1, 1).strftime('%Y-%m-%d')).\
order_by(FixedFeast.month, FixedFeast.mday):
day = instance.day(self.year).strftime('%Y-%m-%d')
if day not in self.by_day:
self.by_day[day] = []
self.by_day[day].append(instance)
def feasts_by_date(self):
"""Selects the right feast for each day"""
by_date = []
for day in self.by_day:
f = self.by_day[day][0]
by_date.append({ 'day': f.day(self.year), 'feasts': self.by_day[day] })
return by_date
<file_sep>/database/migrations/20170127204836_stmarys_federal_holidays.sql
-- rambler up
INSERT INTO federal_holidays (name, code,
calculate_from, algorithm, distance, placement_index,
open_time, close_time,
note, skip_name
) VALUES (E'New Year\'s Day', 'new-years',
'1/1', 'closest_weekday', 0, 1,
'10:00:00', '14:00:00',
'The church is open today from 10:00 AM to 2:00 PM.', true
);
INSERT INTO federal_holidays (name, code,
calculate_from, algorithm, distance, placement_index,
open_time, close_time,
note
) VALUES ('<NAME>', 'mlk',
'1/1', 'nth_monday', 3, 2,
'10:00:00', '14:00:00',
'Federal holiday schedule: The Church opens today at 10:00 AM and closes at 2:00 PM.'
);
INSERT INTO federal_holidays (name, code,
calculate_from, algorithm, distance, placement_index,
open_time, close_time,
note
) VALUES (E'President\'s Day', 'presidents',
'2/1', 'nth_monday', 3, 3,
'10:00:00', '14:00:00',
'Federal holiday schedule: The Church opens today at 10:00 AM and closes at 2:00 PM.'
);
INSERT INTO federal_holidays (name, code,
calculate_from, algorithm, distance, placement_index,
open_time, close_time,
note
) VALUES ('Memorial Day', 'memorial',
'5/1', 'last_monday', 0, 4,
'10:00:00', '14:00:00',
'Federal holiday schedule: The Church opens today at 10:00 AM and closes at 2:00 PM.'
);
INSERT INTO federal_holidays (name, code,
calculate_from, algorithm, distance, placement_index,
open_time, close_time,
note, skip_name
) VALUES ('Independence Day', 'independence',
'7/4', 'not_sunday', 0, 5,
'10:00:00', '14:00:00',
'Federal holiday schedule: The Church opens today at 10:00 AM and closes at 2:00 PM.', true
);
INSERT INTO federal_holidays (name, code,
calculate_from, algorithm, distance, placement_index,
open_time, close_time,
note
) VALUES ('Labor Day', 'labor',
'9/1', 'nth_monday', 1, 6,
'10:00:00', '14:00:00',
'Federal holiday schedule: The Church opens today at 10:00 AM and closes at 2:00 PM.'
);
INSERT INTO federal_holidays (name, code,
calculate_from, algorithm, distance, placement_index,
open_time, close_time,
note, skip_name
) VALUES ('Thanksgiving Day', 'thanksgiving',
'11/1', 'nth_thursday', 4, 7,
'10:00:00', '14:00:00',
'Federal holiday schedule: The Church opens today at 10:00 AM and closes at 2:00 PM.', true
);
INSERT INTO federal_holidays (name, code,
calculate_from, algorithm, distance, placement_index,
close_time,
note, skip_name
) VALUES (E'New Year\'s Eve', 'new-years-eve',
'12/31', 'exact', 0, 8,
'14:00:00',
'The church closes today at 2:00 PM because of the New Year celebrations in Times Square.', true
);
-- rambler down
DELETE FROM federal_holidays;
ALTER SEQUENCE federal_holidays_holiday_id_seq RESTART;
<file_sep>/front/lib/MessageQueue.js
/**
* Manage access to the message queue(s)
*/
if (!global.MessageQueue) {
var AWS = require('aws-sdk');
var Promise = require('bluebird');
var StateError = require('../lib/errors/StateError.js');
global.MessageQueue = {
/**
* Start up the message queue handler
*/
startup: function (config) {
this.config = config
this.urls = { calcRequest: this.config.calcRequestUrl };
AWS.config.update({
accessKeyId: this.config.accessKeyId,
secretAccessKey: this.config.secretAccessKey
});
var sqs = new AWS.SQS({ region: this.config.region });
Promise.promisifyAll(Object.getPrototypeOf(sqs));
this.initialized = true;
},
/**
* Requires that the message queue handler be initialized
*
* @throws StateError if it isn't
*/
requireInitialized: function () {
if (!this.initialized) {
throw new StateError('Message queue is not initialized');
}
},
/**
* Gets the primary sqs connection
*
* @return AWS.SQS the sqs connection
* @throws StateError if the handler isn't initialized
*/
getConnection: function () {
if (typeof this.sqs === 'undefined') {
this.sqs = this.newConnection();
}
return this.sqs;
},
/**
* Gets a new sqs connection
*
* @return AWS.SQS the sqs connection
* @throws StateError if the handler isn't initialized
*/
newConnection: function () {
this.requireInitialized();
return new AWS.SQS({ region: this.config.region });
},
/**
* Writes a new calculation request to the queue
*
* @param object message the message to send as a payload
* @return Promise the promise
* @throws StateError if the registry isn't initialized
*/
writeCalcRequest: function (message) {
var sqsParams = {
MessageBody: JSON.stringify(message),
QueueUrl: this.urls.calcRequest
};
return this.getConnection().sendMessageAsync(sqsParams);
}
};
}
module.exports = global.MessageQueue;
<file_sep>/bin/loghuman
#!/usr/bin/python
import json
import string
import sys
for line in sys.stdin:
j = json.loads(line)
if 'timestamp' not in j:
continue
formatted = '[' + j['timestamp'] + '] ' + j['level'].upper() + ' ' + j['message']
j.pop('timestamp', None)
j.pop('level', None)
j.pop('message', None)
s = None
if 'stack' in j:
s = string.replace(j['stack'], '\\n', "\n")
j.pop('stack', None)
if len(j) > 0:
formatted += ' ' + json.dumps(j)
formatted += "\n"
if s is not None:
formatted += ' ' + s + "\n"
sys.stdout.write(formatted)
<file_sep>/build/dev-vagrant/README.md
# Setting up a dev environment ##
This will help you set up a development environment.
## Install list ##
1. Install [Ansible](http://docs.ansible.com/ansible/intro_installation.html#getting-ansible)
2. Install [Vagrant](https://www.vagrantup.com/docs/installation/)
3. Install [VirtualBox](https://www.virtualbox.org/wiki/Downloads)
4. Install the vagrant triggers plugin:
$ vagrant plugin install vagrant-triggers
5. Install the ansible roles:
$ ansible-galaxy install -r ../ansible/install_roles.yml
## Bring up your environment ##
This will set up your vagrant environment:
```
$ vagrant up
```
Your new vagrant environment will contain three virtual boxes:
* `front` - this box serves json for the website to consume
* `back` - this box provides the admin interface
* `db` - this box runs the database
Once you're set up, you can ssh into them by name (e.g. `vagrant ssh back`) or access them via other ports using the IP addresses assigned to them (see below).
## Tweak your private network addresses (optional) ##
By default your virtual boxes will take the following private network addresses:
| Name | Default IP | Config Key |
| ------ | ------------ | ---------- |
| front | 192.168.0.23 | front_ip |
| back | 192.168.0.24 | back_ip |
| db | 192.168.0.25 | db_ip |
You can change these values by creating a file called `config.yml` in this directory:
```
---
# Configure my vagrant
front_ip: 192.168.0.77
db_ip: 192.168.0.102
...
```
After you've changed your config file, you'll need to destroy and reinstate your vagrant to see the changes:
```
$ vagrant destroy -f && vagrant up
```
## Provision your environment ##
For dev, you'll need to use a custom ansible configuration, so run all ansible commands you intend for your vagrant environment from this directory, even though the playbook file is in the ansible directory next to this one.
```
$ ansible-playbook ../ansible/vagrant.yml --ask-vault-pass
```
<file_sep>/build/README.md
# Building this project
This file explains how to build this project on AWS. If you're looking for the dev vagrant, its readme is in the `dev_vagrant` subdirectory.
## Architecture
This project needs the following types of instances to run:
- `tag_Ansible_Db` - runs the postgres database; rambler commands are expected here
- `tag_Ansible_Back` - runs the queue reader service that listens for calculation requests and builds the calendar for a given time frame
- `tag_Ansible_Front` - runs the API that listens for calendar requests and pushes messages to the queue if not found
- `tag_Ansible_Master` - a small instance within the project security group from which Ansible commands are run to update the others
## Boostrapping master
First, you'll need the keys placed in your ssh directory. You can of course copy them from the secrets file, but running the playbook is easier:
```
ANSIBLE_HOST_KEY_CHECKING=false ansible-playbook build/ansible/local.yml --ask-vault-pass
```
Make sure you have Boto; e.g. for mac osx:
```
sudo pip install boto
```
Once you've done that, you can bootstrap the master instance:
```
ANSIBLE_HOST_KEY_CHECKING=false ansible-playbook build/ansible/master.yml --ask-vault-pass --private-key=~/.ssh/ec2_deploy_id_rsa
```
This will spin up a new master instance and run the `ansible_master` role on it. Because we're using localhost rather than a dynamic inventory, it can only find the ansible master when it's first created.
## Setting up production
Use the production playbook on master (go look at the EC2 console to find out where master is) like so:
```
ansible-playbook build/ansible/production.yml --ask-vault-pass --private-key=~/.ssh/id_rsa-deploy
```
<file_sep>/bin/calendar_builder/fetch/calculated.py
import copy
import datetime
from sqlalchemy import text
from sqlalchemy.orm import eagerload,joinedload
import sys
from ..models import Calculated as ModelCalculated
from ..models import Cached as ModelCached
from ..static import StaticRange
from .. import utils
class Calculated:
"""Class for pulling previously calculated years"""
def __init__(self, session):
"""Sets up the fetcher"""
self.session = session
self.by_date = {}
def check_year(self, year):
"""Checks whether the base schedule has been calculated for this year"""
start = datetime.date(year, 1, 1)
end = datetime.date(year, 12, 31)
for instance in self.session.query(ModelCalculated).\
options(joinedload(ModelCalculated.services)).\
filter(text("target_date BETWEEN :year_start AND :year_end")).\
params(year_start=start.strftime('%Y-%m-%d'),\
year_end=end.strftime('%Y-%m-%d')).\
order_by(ModelCalculated.target_date, ModelCalculated.target_block, ModelCalculated.id):
td = utils.day_to_lookup(instance.target_date)
if td not in self.by_date:
self.by_date[td] = []
self.by_date[td].append(instance)
return self.ok_for_range(start, end)
def check_window(self, start, end):
"""Checks whether the schedule has been calculated for this window"""
for instance in self.session.query(ModelCalculated).\
options(joinedload(ModelCalculated.services)).\
filter(text("target_date BETWEEN :start_date AND :end_date")).\
params(start_date=start.strftime('%Y-%m-%d'),\
end_date=end.strftime('%Y-%m-%d')).\
order_by(ModelCalculated.target_date, ModelCalculated.target_block, ModelCalculated.id):
td = utils.day_to_lookup(instance.target_date)
if td not in self.by_date:
self.by_date[td] = []
self.by_date[td].append(instance)
return self.ok_for_range(start, end)
def ok_for_range(self, start, end):
"""Checks that every date in the range has a match in the directory given"""
check_day = copy.deepcopy(start)
while check_day <= end:
cdate = utils.day_to_lookup(check_day)
if cdate not in self.by_date:
return False
check_day = check_day + datetime.timedelta(days=1)
return True
def load_static_range(self, start, end):
"""Builds a StaticRange from the data in the calculated table for a given range"""
static_range = StaticRange(start, end, self.session)
overrides = []
for cdate in sorted(self.by_date.iterkeys()):
objs = self.by_date[cdate]
for obj in objs:
overrides.append(self._obj_to_override(obj))
static_range.override(overrides)
return static_range
def _obj_to_override(self, obj):
"""Converts a calculated object (model from lookup) into a dictionary suitable for static overrides"""
override = {}
override['day'] = obj.target_date
override['target_block'] = obj.target_block
override['color'] = obj.color
override['name'] = obj.name
override['note'] = obj.note
override['services'] = []
for service in obj.services:
override['services'].append({ 'name': service.name, 'start_time': service.start_time })
return override
<file_sep>/front/app/db.js
/**
* pg-promise wants one connection only
*/
if (!global.GLOBAL_OVERRIDE_LOAD_DATABASE_CONNECTION) {
var pgp = require('pg-promise')();
var config = require('./config');
var db = pgp(config.database);
global.GLOBAL_OVERRIDE_LOAD_DATABASE_CONNECTION = true;
}
module.exports = db;
<file_sep>/database/migrations/20160810135105_stmarys_moveable_feasts.sql
-- rambler up
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, has_eve, eve_schedule_pattern, eve_name, color,
valid_start)
VALUES ('Easter Day', 'easter', 1, 1,
'easter', 'exact', null,
'easter', true, 'easter-eve', 'Easter Eve', 'gold',
'2011-01-01 00:00:00' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, has_eve, eve_schedule_pattern, eve_name, color,
valid_end)
VALUES ('The Sunday of the Resurrection: Easter Day', 'easter', 1, 1,
'easter', 'days_before', 1,
'easter', true, 'easter-eve', 'Easter Eve', 'white',
'2010-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_start)
VALUES ('Ash Wednesday', 'ash-wednesday', 1, 2,
'easter', 'wednesdays_before', 6,
'ash-wednesday', 'purple', 'Fast and Abstinence
Imposition of Ashes will be offered throughout the day from 7:00 AM to 8:00 PM.
The Daily Office is not prayed publicly on this day.',
'2013-01-01 00:00:00' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_start, valid_end)
VALUES ('Ash Wednesday', 'ash-wednesday', 1, 2,
'easter', 'wednesdays_before', 6,
'ash-wednesday', 'purple', 'Fast and Abstinence
Imposition of Ashes will be offered throughout the day from 7:00 AM to 8:00 PM.',
'2008-01-01 00:00:00' AT TIME ZONE 'America/New_York',
'2012-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_end)
VALUES ('The First Day of Lent: Ash Wednesday', 'ash-wednesday', 1, 2,
'easter', 'wednesdays_before', 6,
'ash-wednesday', 'purple', 'Fast & Abstinence
Ashes are offered from 7:00 AM to 8:00 PM.
Weekdays in Lent are observed by special acts of discipline and self-denial.
Fridays of Lent are observed by abstinence from flesh meats.',
'2007-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, has_eve, eve_schedule_pattern, color, note,
valid_start)
VALUES ('The Sunday of the Passion: Palm Sunday', 'palm-sunday', 1, 2,
'easter', 'days_before', 7,
'palm-sunday', true, 'palm-sunday-eve', 'red', 'Abstinence is not observed on Palm Sunday.
There is no celebration of Mass at 10:00 AM today.',
'2011-01-01 00:00:00' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, has_eve, eve_schedule_pattern, color, note,
valid_end)
VALUES ('The Sunday of the Passion: Palm Sunday', 'palm-sunday', 1, 2,
'easter', 'days_before', 7,
'palm-sunday', true, 'palm-sunday-eve', 'red', 'There is no 10:00 AM liturgy today.',
'2010-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_start)
VALUES ('Good Friday', 'good-friday', 1, 2,
'easter', 'days_before', 2,
'good-friday', 'red', 'Fast & Abstinence
The parish clergy hear confessions following the liturgies.',
'2014-01-01 00:00:00' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_start, valid_end)
VALUES ('Good Friday', 'good-friday', 1, 2,
'easter', 'days_before', 2,
'good-friday', 'black', 'Fast & Friday Abstinence
Confessions are heard following the liturgies.',
'2011-01-01 00:00:00' AT TIME ZONE 'America/New_York',
'2013-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_end)
VALUES ('Good Friday', 'good-friday', 1, 2,
'easter', 'days_before', 2,
'good-friday', 'red', 'Fast & Lenten Abstinence
The Good Friday Liturgy is celebrated twice for the pastoral needs of the community.
Confessions are heard following both liturgies by the parish clergy.',
'2010-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_start)
VALUES ('Holy Saturday', 'holy-saturday', 1, 3,
'easter', 'days_before', 1,
'holy-saturday', 'red', 'Abstinence',
'2011-01-01 00:00:00' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_end)
VALUES ('Holy Saturday', 'holy-saturday', 1, 3,
'easter', 'days_before', 1,
'holy-saturday', 'red', null,
'2010-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_start)
VALUES ('Maundy Thursday', 'maundy-thursday', 1, 3,
'easter', 'days_before', 3,
'maundy-thursday', 'white', 'Abstinence
There are no noonday services today.
The Watch Before the Blessed Sacrament follows the Mass.',
'2011-01-01 00:00:00' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, color, note,
valid_end)
VALUES ('Maundy Thursday', 'maundy-thursday', 1, 3,
'easter', 'days_before', 3,
'maundy-thursday', 'white', 'There are no noonday services today.
The Watch Before the Blessed Sacrament follows the Mass.',
'2010-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, has_eve, eve_schedule_pattern, color)
VALUES ('Ascension Day', 'ascension-day', 2, 4,
'easter', 'thursdays_after', 6,
'solemn-fixed-feast', true, 'solemn-fixed-feast-eve', 'gold');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color)
VALUES ('The Day of Pentecost: Whitsunday', 'pentecost', 2, 4,
'easter', 'sundays_after', 7, true, 'red');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color)
VALUES ('Trinity Sunday', 'trinity', 2, 4,
'easter', 'sundays_after', 8, true, 'gold');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance,
schedule_pattern, has_eve, color, note)
VALUES ('The Body and Blood of Christ: Corpus Christi', 'corpus-christi', 2, 4,
'easter', 'sundays_after', 9,
'corpus-christi', true, 'gold', 'The Sunday summer schedule begins this evening.');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color)
VALUES ('The Third Sunday of Advent', 'rose-advent', 2, 5,
'christmas', 'sundays_before', 2, true, 'rose');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color)
VALUES ('The Fourth Sunday in Lent', 'rose-lent', 2, 5,
'ash-wednesday', 'sundays_after', 4, true, 'rose');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, eve_schedule_pattern, color,
valid_end)
VALUES ('The Sacred Heart of Jesus', 'sacred-heart', 3, 5,
'pentecost', 'days_after', 19, true, 'said-mass-eve-vigil', 'white',
'2008-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, eve_schedule_pattern, color)
VALUES ('Thanksgiving Day', 'thanksgiving', 3, 5,
'11/1', 'nth_thursday', 4, true, 'sung-mass-eve-vigil', 'white');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color,
valid_end)
VALUES ('Feast of Christ the King', 'christ-the-king', 2, 4,
'christmas', 'sundays_before', 5, true, 'white',
'2007-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color,
valid_start,
valid_end)
VALUES ('The Last Sunday after Pentecost: Christ the King', 'christ-the-king', 2, 4,
'christmas', 'sundays_before', 5, true, 'white',
'2008-01-01 00:00:00' AT TIME ZONE 'America/New_York',
'2012-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color,
valid_start)
VALUES ('The Last Sunday after Pentecost: Christ the King', 'christ-the-king', 2, 4,
'christmas', 'sundays_before', 5, true, 'gold',
'2013-01-01 00:00:00' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color,
valid_end)
VALUES ('The First Sunday after the Epiphany: The Baptism of Our Lord', 'baptism', 2, 5,
'epiphany', 'sundays_after', 1, true, 'white',
'2008-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color,
valid_start,
valid_end)
VALUES ('The First Sunday after the Epiphany: The Baptism of Our Lord Jesus Christ', 'baptism', 2, 5,
'epiphany', 'sundays_after', 1, true, 'white',
'2009-01-01 00:00:00' AT TIME ZONE 'America/New_York',
'2010-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO moveable_feasts (name, code, otype_id, placement_index,
calculate_from, algorithm, distance, has_eve, color,
valid_start)
VALUES ('The First Sunday after the Epiphany: The Baptism of Our Lord Jesus Christ', 'baptism', 2, 5,
'epiphany', 'sundays_after', 1, true, 'gold',
'2011-01-01 00:00:00' AT TIME ZONE 'America/New_York');
-- rambler down
TRUNCATE TABLE moveable_feasts RESTART IDENTITY;
<file_sep>/database/migrations/20160810132316_stmarys_precedence.sql
-- rambler up
INSERT INTO observance_types (name, precedence) VALUES ('Principal Feast or Holy Day', 10); -- 1
INSERT INTO observance_types (name, precedence) VALUES ('Major Feast (can be celebrated on Sunday)', 20); -- 2
INSERT INTO observance_types (name, precedence) VALUES ('Feast (transfers from Sunday)', 40); -- 3
INSERT INTO observance_types (name, precedence) VALUES ('Commemoration', 50); -- 4
INSERT INTO observance_types (name, precedence) VALUES ('Major Feast (celebrated on the nearest Sunday)', 30); -- 5
INSERT INTO observance_types (name, precedence) VALUES ('Lesser Commemoration', 55); -- 6
-- rambler down
TRUNCATE TABLE observance_types RESTART IDENTITY;
-- todo: double check precedence for moveable feasts
<file_sep>/bin/calendar_builder/fetch/federal_holidays.py
import datetime
from sqlalchemy import text
from sqlalchemy.orm import eagerload,joinedload
from ..models import FederalHoliday, ServicePattern
class FederalHolidays:
"""Class for placing federal holidays in a year"""
def __init__(self, session, year):
"""Sets up the placer"""
self.session = session
self.year = year
self.load_holidays()
def load_holidays(self):
"""Loads the holidays for this year"""
self.by_code = {}
self.holidays = []
for instance in self.session.query(FederalHoliday).\
filter(text("valid_for_date(:jan_first, federal_holidays.valid_start, federal_holidays.valid_end)")).\
params(jan_first=datetime.date(self.year, 1, 1).strftime('%Y-%m-%d')).\
order_by(FederalHoliday.placement_index):
code = instance.code
if code not in self.by_code:
self.by_code[code] = []
self.by_code[code].append(instance)
self.holidays.append(code)
def holidays_by_date(self):
"""Selects the right holiday for each day"""
by_date = []
for code in self.holidays:
h = self.by_code[code][0]
d = h.day(self.year)
by_date.append({ 'day': d, 'holidays': self.by_code[code] })
# New Years Day is a special case, because it could place a federal
# holiday in the previous year, so we want to see where next year's New
# Years Day is going to be placed as well as this year's.
if 'new-years' in self.by_code:
h = self.by_code['new-years'][0]
d = h.day(self.year + 1)
by_date.append({ 'day': d, 'holidays': self.by_code['new-years'] })
return by_date
<file_sep>/database/migrations/00_todos.sql
-- rambler up
-- rambler down
-- todo: distinguish notes from abstinence notes
-- todo: by-year overrides
-- Candlemas
-- Assumption
-- 9/11 Requiem
-- Willibrord, Archbishop of Utrecht, Missionary to Frisia, 739 missing in 2006
-- Anniversary of the Dedication of the Church sometimes has an eve and occasionally a nonstandard Mass
-- todo: special cases in 2004:
-- MAUNDY THURSDAY
-- Morning Prayer 8:30 AM
-- There is no 12:15 PM Mass today.
-- THE EVENING MASS OF THE LORD'S SUPPER 6:00 PM
-- The Watch Before the Blessed Sacrament follows the liturgy.
-- Evening Prayer is said only by those who are unable to participate in the Evening Mass of the Lord's Supper.
-- GOOD FRIDAY
-- Morning Prayer 8:30 AM
-- THE CELEBRATION OF THE PASSION OF THE LORD 12:30 PM
-- THE CELEBRATION OF THE PASSION OF THE LORD 6:00 PM
-- Fast & Abstinence
-- The Good Friday Liturgy is celebrated twice for the pastoral needs of the community.
-- Confessions are heard following both liturgies by the parish clergy.
-- Evening Prayer is only said by those who are not able to participate in the Celebration of the Passion of the Lord.
<file_sep>/database/migrations/20170204162938_stmarys_overrides.sql
-- rambler up
--
-- Define overrides
--
INSERT INTO overrides (target_date, target_block, note)
VALUES ('2004-04-08', 'base', E'There is no 12:15 PM Mass today.
The Watch Before the Blessed Sacrament follows the liturgy.
Evening Prayer is said only by those who are unable to participate in the Evening Mass of the Lord\'s Supper.'); -- 1
INSERT INTO override_services (override_id, name, start_time) VALUES
(1, 'Morning Prayer', '08:30:00'),
(1, E'The Evening Mass of the Lord\'s Supper', '18:00:00');
-- rambler down
DELETE FROM override_services;
ALTER SEQUENCE override_services_override_service_id_seq RESTART;
DELETE FROM overrides;
ALTER SEQUENCE overrides_override_id_seq RESTART;
<file_sep>/database/migrations/20160810132300_schema_precedence.sql
-- rambler up
--
-- This table defines the types of observances and their precedence (e.g., if
-- Saint Joseph's Day falls on Monday of Holy Week, is it celebrated then or
-- transferred to another day?)
--
CREATE TABLE observance_types (
otype_id serial,
name text NOT NULL,
precedence integer NOT NULL,
CONSTRAINT observance_types_pk PRIMARY KEY (otype_id)
);
-- rambler down
DROP TABLE observance_types;
<file_sep>/bin/calendar_builder/models.py
import datetime
from dateutil.easter import *
import inflect
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean, Time, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from .config import config
from .algorithms import boundary_algorithms, feast_algorithms, holiday_algorithms
from . import utils
from .valid_dates import valid_in_list
DeclarativeBase = declarative_base()
class Service(DeclarativeBase):
"""Sqlalchemy services model"""
__tablename__ = 'services'
id = Column('service_id', Integer, primary_key=True)
name = Column(String)
start_time = Column(Time, nullable=True)
is_default = Column(Boolean)
def __repr__(self):
return self.name + ' ' + utils.ftime(self.start_time)
class ScheduleServices(DeclarativeBase):
"""Sqlalchemy schedules model"""
__tablename__ = 'schedule_services'
service_id = Column(Integer, ForeignKey('services.service_id'), primary_key=True)
schedule_id = Column(Integer, ForeignKey('schedules.schedule_id'), primary_key=True)
class Schedule(DeclarativeBase):
"""Sqlalchemy schedules model"""
__tablename__ = 'schedules'
id = Column('schedule_id', Integer, primary_key=True)
name = Column(String)
code = Column(String, nullable=True)
valid_start = Column(DateTime, nullable=True)
valid_end = Column(DateTime, nullable=True)
is_default = Column(Boolean)
is_custom = Column(Boolean)
services = relationship('Service', secondary='schedule_services',
foreign_keys=[ScheduleServices.service_id, ScheduleServices.schedule_id], uselist=True)
def sort_services(self):
"""Returns the services, sorted by start time"""
return sorted(self.services, key=lambda service: service.start_time)
def __repr__(self):
return self.name + ' <' + self.code + '>'
class ServicePattern(DeclarativeBase):
"""Sqlalchemy service patterns model"""
__tablename__ = 'service_patterns'
id = Column('pattern_id', Integer, primary_key=True)
name = Column(String)
code = Column(String)
schedule_code_mon = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_mon_with_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_mon_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_tue = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_tue_with_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_tue_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_wed = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_wed_with_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_wed_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_thu = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_thu_with_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_thu_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_fri = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_fri_with_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_fri_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_sat = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_sat_with_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_sat_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_sun = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_sun_with_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
schedule_code_sun_vigil = Column(String, ForeignKey('schedules.code'), nullable=True)
valid_start = Column(DateTime, nullable=True)
valid_end = Column(DateTime, nullable=True)
all_mon = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_mon", uselist=True)
all_mon_with_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_mon_with_vigil", uselist=True)
all_mon_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_mon_vigil", uselist=True)
all_tue = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_tue", uselist=True)
all_tue_with_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_tue_with_vigil", uselist=True)
all_tue_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_tue_vigil", uselist=True)
all_wed = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_wed", uselist=True)
all_wed_with_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_wed_with_vigil", uselist=True)
all_wed_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_wed_vigil", uselist=True)
all_thu = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_thu", uselist=True)
all_thu_with_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_thu_with_vigil", uselist=True)
all_thu_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_thu_vigil", uselist=True)
all_fri = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_fri", uselist=True)
all_fri_with_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_fri_with_vigil", uselist=True)
all_fri_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_fri_vigil", uselist=True)
all_sat = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_sat", uselist=True)
all_sat_with_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_sat_with_vigil", uselist=True)
all_sat_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_sat_vigil", uselist=True)
all_sun = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_sun", uselist=True)
all_sun_with_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_sun_with_vigil", uselist=True)
all_sun_vigil = relationship(Schedule, primaryjoin="Schedule.code==ServicePattern.schedule_code_sun_vigil", uselist=True)
def __repr__(self):
return self.name + ' <' + self.code + '>'
def mon(self, day):
return valid_in_list(self.all_mon, day)
def mon_with_vigil(self, day):
return valid_in_list(self.all_mon_with_vigil, day)
def mon_vigil(self, day):
return valid_in_list(self.all_mon_vigil, day)
def tue(self, day):
return valid_in_list(self.all_tue, day)
def tue_with_vigil(self, day):
return valid_in_list(self.all_tue_with_vigil, day)
def tue_vigil(self, day):
return valid_in_list(self.all_tue_vigil, day)
def wed(self, day):
return valid_in_list(self.all_wed, day)
def wed_with_vigil(self, day):
return valid_in_list(self.all_wed_with_vigil, day)
def wed_vigil(self, day):
return valid_in_list(self.all_wed_vigil, day)
def thu(self, day):
return valid_in_list(self.all_thu, day)
def thu_with_vigil(self, day):
return valid_in_list(self.all_thu_with_vigil, day)
def thu_vigil(self, day):
return valid_in_list(self.all_thu_vigil, day)
def fri(self, day):
return valid_in_list(self.all_fri, day)
def fri_with_vigil(self, day):
return valid_in_list(self.all_fri_with_vigil, day)
def fri_vigil(self, day):
return valid_in_list(self.all_fri_vigil, day)
def sat(self, day):
return valid_in_list(self.all_sat, day)
def sat_with_vigil(self, day):
return valid_in_list(self.all_sat_with_vigil, day)
def sat_vigil(self, day):
return valid_in_list(self.all_sat_vigil, day)
def sun(self, day):
return valid_in_list(self.all_sun, day)
def sun_with_vigil(self, day):
return valid_in_list(self.all_sun_with_vigil, day)
def sun_vigil(self, day):
return valid_in_list(self.all_sun_vigil, day)
def has_vigil(self, day):
param = 'schedule_code_' + day.strftime('%A').lower()[:3] + '_vigil'
code = getattr(self, param)
if code is None:
return False
else:
return True
def schedule(self, day, **kwargs):
method = day.strftime('%A').lower()[:3]
if 'has_vigil' in kwargs and kwargs['has_vigil']:
method += '_with_vigil'
elif 'is_vigil' in kwargs and kwargs['is_vigil']:
method += '_vigil'
return getattr(self, method)(day)
class Season(DeclarativeBase):
"""Sqlalchemy seasons model"""
__tablename__ = "seasons"
id = Column('season_id', Integer, primary_key=True)
name = Column(String)
code = Column(String)
color = Column(String)
weekday_precedence = Column(Integer)
counting_index = Column(Integer)
continue_counting = Column(Boolean)
has_last_sunday = Column(Boolean)
calculate_from = Column(String)
algorithm = Column(String)
distance = Column(Integer)
sort_order = Column(Integer)
schedule_pattern = Column(String, ForeignKey('service_patterns.code'))
name_pattern_mon = Column(String)
name_pattern_tue = Column(String)
name_pattern_wed = Column(String)
name_pattern_thu = Column(String)
name_pattern_fri = Column(String)
name_pattern_sat = Column(String)
name_pattern_sat_vigil = Column(String)
name_pattern_sun = Column(String)
default_note_mon = Column(String)
default_note_tue = Column(String)
default_note_wed = Column(String)
default_note_thu = Column(String)
default_note_fri = Column(String)
default_note_sat = Column(String)
default_note_sun = Column(String)
all_patterns = relationship(ServicePattern, primaryjoin="ServicePattern.code==Season.schedule_pattern", uselist=True)
def __repr__(self):
return self.name + ' <' + self.code + '> // COLOR ' + self.color + ' // PRECEDENCE ' + str(self.weekday_precedence)
def end_date(self, start_date):
"""Gets the end date for this season, given a start date"""
if self.calculate_from == 'easter':
holiday = easter(start_date.year)
elif self.calculate_from == 'christmas':
holiday = datetime.date(start_date.year, 12, 25)
else:
raise ValueError('"{holiday}" is an unknown calculation starting point for seasons; use "christmas" or "easter"'.format(holiday=repr(self.calculate_from)))
return getattr(boundary_algorithms, self.algorithm)(holiday, self.distance)
def precedence(self, day):
"""Gets the precedence for a given date, assumed to be within the season"""
weekday = day.strftime('%A').lower()
if weekday == 'sunday':
return config['sunday_precedence']
else:
return self.weekday_precedence
def pattern(self, day):
return valid_in_list(self.all_patterns, day)
def ordinal(self, number):
p = inflect.engine()
return p.number_to_words(p.ordinal(number))
def day_name(self, day, **kwargs):
weekday = day.strftime('%A').lower()[:3]
param = 'name_pattern_' + weekday
if weekday == 'sat' and 'is_vigil' in kwargs and kwargs['is_vigil']:
param += '_vigil'
name = getattr(self, param)
if 'sunday_count' in kwargs and '%s' in name:
if self.has_last_sunday and 'is_last' in kwargs and kwargs['is_last']:
name = name % 'Last'
else:
name = name % self.ordinal(kwargs['sunday_count']).title()
return name
def day_note(self, day):
return getattr(self, 'default_note_' + day.strftime('%A').lower()[:3])
class ObservanceType(DeclarativeBase):
"""Sqlalchemy observance types model"""
__tablename__ = 'observance_types'
id = Column('otype_id', Integer, primary_key=True)
name = Column(String)
precedence = Column(Integer)
class MoveableFeast(DeclarativeBase):
"""Sqlalchemy moveable feasts model"""
__tablename__ = 'moveable_feasts'
id = Column('moveable_id', Integer, primary_key=True)
name = Column(String)
code = Column(String)
otype_id = Column(Integer, ForeignKey('observance_types.otype_id'))
placement_index = Column(Integer, nullable=True)
calculate_from = Column(String)
algorithm = Column(String)
distance = Column(Integer, nullable=True)
schedule_pattern = Column(String, ForeignKey('service_patterns.code'), nullable=True)
has_eve = Column(Boolean)
eve_schedule_pattern = Column(String, ForeignKey('service_patterns.code'), nullable=True)
eve_name = Column(String, nullable=True)
color = Column(String, nullable=True)
note = Column(String, nullable=True)
valid_start = Column(DateTime, nullable=True)
valid_end = Column(DateTime, nullable=True)
otype = relationship(ObservanceType)
all_patterns = relationship(ServicePattern, primaryjoin="ServicePattern.code==MoveableFeast.schedule_pattern", uselist=True)
all_eve_patterns = relationship(ServicePattern, primaryjoin="ServicePattern.code==MoveableFeast.eve_schedule_pattern", uselist=True)
def __repr__(self):
return self.name + ' <' + self.code + '>'
def pattern(self, day):
return valid_in_list(self.all_patterns, day)
def eve_pattern(self, day):
return valid_in_list(self.all_eve_patterns, day)
def day(self, year):
"""Gets the date of this feast, given a year"""
if self.calculate_from == 'easter':
holiday = easter(year)
elif self.calculate_from == 'christmas':
holiday = datetime.date(year, 12, 25)
elif self.calculate_from == 'epiphany':
holiday = datetime.date(year, 1, 6)
elif self.calculate_from == 'ash-wednesday':
# Ash Wednesday is the sixth Wednesday before Easter
eas = easter(year)
holiday = eas - datetime.timedelta(days=eas.weekday()) + datetime.timedelta(days=2, weeks=-6)
elif self.calculate_from == 'pentecost':
# Pentecost is the seventh Sunday after Easter
eas = easter(year)
holiday = eas + datetime.timedelta(weeks=7)
elif self.calculate_from == '11/1':
holiday = datetime.date(year, 11, 1)
else:
raise ValueError('"{holiday}" is an unknown calculation starting point for moveable feasts; use "christmas" or "easter"'.format(holiday=repr(self.calculate_from)))
return getattr(feast_algorithms, self.algorithm)(holiday, self.distance)
class FixedFeast(DeclarativeBase):
"""Sqlalchemy fixed feasts model"""
__tablename__ = 'fixed_feasts'
id = Column('fixed_id', Integer, primary_key=True)
name = Column(String)
code = Column(String)
otype_id = Column(Integer, ForeignKey('observance_types.otype_id'))
month = Column(Integer)
mday = Column('day', Integer)
schedule_pattern = Column(String, ForeignKey('service_patterns.code'), nullable=True)
has_eve = Column(Boolean)
eve_schedule_pattern = Column(String, ForeignKey('service_patterns.code'), nullable=True)
eve_name = Column(String, nullable=True)
color = Column(String, nullable=True)
note = Column(String, nullable=True)
valid_start = Column(DateTime, nullable=True)
valid_end = Column(DateTime, nullable=True)
otype = relationship(ObservanceType)
all_patterns = relationship(ServicePattern, primaryjoin="ServicePattern.code==FixedFeast.schedule_pattern", uselist=True)
all_eve_patterns = relationship(ServicePattern, primaryjoin="ServicePattern.code==FixedFeast.eve_schedule_pattern", uselist=True)
def __repr__(self):
if self.code:
return self.name + ' <' + self.code + '>'
else:
return self.name
def pattern(self, day):
return valid_in_list(self.all_patterns, day)
def eve_pattern(self, day):
return valid_in_list(self.all_eve_patterns, day)
def day(self, year):
"""Gets the date of this feast, given a year"""
return datetime.date(year, self.month, self.mday)
class FloatingFeast(DeclarativeBase):
"""Sqlalchemy floating feasts model"""
__tablename__ = 'floating_feasts'
id = Column('floating_id', Integer, primary_key=True)
name = Column(String)
code = Column(String)
otype_id = Column(Integer, ForeignKey('observance_types.otype_id'))
placement_index = Column(Integer, nullable=True)
algorithm = Column(String)
schedule_pattern = Column(String, ForeignKey('service_patterns.code'), nullable=True)
has_eve = Column(Boolean)
eve_schedule_pattern = Column(String, ForeignKey('service_patterns.code'), nullable=True)
eve_name = Column(String, nullable=True)
color = Column(String, nullable=True)
note = Column(String, nullable=True)
valid_start = Column(DateTime, nullable=True)
valid_end = Column(DateTime, nullable=True)
otype = relationship(ObservanceType)
all_patterns = relationship(ServicePattern, primaryjoin="ServicePattern.code==FloatingFeast.schedule_pattern", uselist=True)
all_eve_patterns = relationship(ServicePattern, primaryjoin="ServicePattern.code==FloatingFeast.eve_schedule_pattern", uselist=True)
def __repr__(self):
return self.name + ' <' + self.code + '>'
def pattern(self, day):
return valid_in_list(self.all_patterns, day)
def eve_pattern(self, day):
return valid_in_list(self.all_eve_patterns, day)
class FederalHoliday(DeclarativeBase):
"""Sqlalchemy federal holidays model"""
__tablename__ = 'federal_holidays'
id = Column('holiday_id', Integer, primary_key=True)
name = Column(String)
code = Column(String)
calculate_from = Column(String)
algorithm = Column(String)
distance = Column(Integer, nullable=True)
placement_index = Column(Integer, nullable=True)
open_time = Column(Time, nullable=True)
close_time = Column(Time, nullable=True)
note = Column(String, nullable=True)
skip_name = Column(Boolean)
valid_start = Column(DateTime, nullable=True)
valid_end = Column(DateTime, nullable=True)
def __repr__(self):
return self.name + ' <' + self.code + '>'
def _get_calc_from(self, year):
"""Converts the calculate_from column into a day to calculate from, given a year"""
parts = self.calculate_from.split('/')
if len(parts) != 2:
return None
try:
month = int(parts[0])
day = int(parts[1])
except ValueError:
return None
if month < 1 or month > 12:
return None
if day < 1 or day > 31:
return None
calc_from = datetime.date(year, month, day)
if calc_from.year != year or calc_from.month != month or calc_from.day != day:
return None
return calc_from
def day(self, year):
"""Gets the date of this holiday, given a year"""
calc_from = self._get_calc_from(year)
if calc_from is None:
raise ValueError('"{calc_from}" is an unknown calculation starting point for federal holidays; use "MM-DD"'.format(calc_from=repr(self.calculate_from)))
return getattr(holiday_algorithms, self.algorithm)(calc_from, self.distance)
class OverrideService(DeclarativeBase):
"""Sqlalchemy override services model"""
__tablename__ = 'override_services'
id = Column('override_service_id', Integer, primary_key=True)
override_id = Column(Integer, ForeignKey('overrides.override_id'))
name = Column(String)
start_time = Column(Time, nullable=True)
def __repr__(self):
return self.name + ' ' + str(self.startTime)
class Override(DeclarativeBase):
"""Sqlalchemy overrides model"""
__tablename__ = 'overrides'
id = Column('override_id', Integer, primary_key=True)
target_date = Column(Date)
target_block = Column(String)
name = Column(String, nullable=True)
color = Column(String, nullable=True)
note = Column(String, nullable=True)
services = relationship(OverrideService, primaryjoin="OverrideService.override_id==Override.id", uselist=True)
def __repr__(self):
return self.name + ' [' + self.color + '] ' + self.note
class CalculatedService(DeclarativeBase):
"""Sqlalchemy calculated services model"""
__tablename__ = 'calculated_services'
id = Column('calculated_service_id', Integer, primary_key=True)
calculated_id = Column(Integer, ForeignKey('calculated.calculated_id'))
name = Column(String)
start_time = Column(Time, nullable=True)
def __repr__(self):
return self.name + ' ' + str(self.startTime)
class Calculated(DeclarativeBase):
"""Sqlalchemy calculated calendar model"""
__tablename__ = 'calculated'
id = Column('calculated_id', Integer, primary_key=True)
target_date = Column(Date)
target_block = Column(String)
name = Column(String, nullable=True)
color = Column(String, nullable=True)
note = Column(String, nullable=True)
services = relationship(CalculatedService, primaryjoin="CalculatedService.calculated_id==Calculated.id", uselist=True)
def __repr__(self):
return self.name + ' [' + self.color + '] ' + self.note
class CachedService(DeclarativeBase):
"""Sqlalchemy cached services model"""
__tablename__ = 'cached_services'
id = Column('cached_service_id', Integer, primary_key=True)
cached_id = Column(Integer, ForeignKey('cached.cached_id'))
name = Column(String)
start_time = Column(Time, nullable=True)
def __repr__(self):
return self.name + ' ' + str(self.startTime)
class Cached(DeclarativeBase):
"""Sqlalchemy cached calendar model"""
__tablename__ = 'cached'
id = Column('cached_id', Integer, primary_key=True)
target_date = Column(Date)
target_block = Column(String)
name = Column(String, nullable=True)
color = Column(String, nullable=True)
note = Column(String, nullable=True)
services = relationship(CachedService, primaryjoin="CachedService.cached_id==Cached.id", uselist=True)
def __repr__(self):
return self.name + ' [' + self.color + '] ' + self.note
<file_sep>/bin/year_builder
#!/usr/bin/python
from calendar_builder.process import calculate_year
calculate_year.main()
<file_sep>/database/migrations/20170225143814_schema_calculated.sql
-- rambler up
--
-- These tables define the calculated and cached results for the liturgical calendar
--
CREATE TABLE calculated (
calculated_id serial,
target_date date NOT NULL,
target_block text NOT NULL CHECK (target_block IN ('base', 'vigil')),
name text,
color text,
note text,
CONSTRAINT calculated_pk PRIMARY KEY (calculated_id),
CONSTRAINT calculated_target_uq UNIQUE (target_date, target_block)
);
CREATE INDEX calculated_target_date_idx ON calculated (target_date);
CREATE TABLE calculated_services (
calculated_service_id serial,
calculated_id integer NOT NULL,
name text NOT NULL,
start_time time with time zone NOT NULL,
CONSTRAINT calculated_services_pk PRIMARY KEY (calculated_service_id),
CONSTRAINT calculated_services_target_uq FOREIGN KEY (calculated_id)
REFERENCES calculated (calculated_id)
ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE TABLE cached (
cached_id serial,
target_date date NOT NULL,
target_block text NOT NULL CHECK (target_block IN ('base', 'vigil')),
name text,
color text,
note text,
CONSTRAINT cached_pk PRIMARY KEY (cached_id),
CONSTRAINT cached_target_uq UNIQUE (target_date, target_block)
);
CREATE INDEX cached_target_date_idx ON cached (target_date);
CREATE TABLE cached_services (
cached_service_id serial,
cached_id integer NOT NULL,
name text NOT NULL,
start_time time with time zone NOT NULL,
CONSTRAINT cached_services_pk PRIMARY KEY (cached_service_id),
CONSTRAINT cached_services_target_uq FOREIGN KEY (cached_id)
REFERENCES cached (cached_id)
ON DELETE CASCADE ON UPDATE NO ACTION
);
-- rambler down
DROP TABLE cached_services;
DROP TABLE cached;
DROP TABLE calculated_services;
DROP TABLE calculated;
<file_sep>/database/migrations/20160810134300_schema_fixed_feasts.sql
-- rambler up
--
-- This table defines the fixed feasts, which are attached to a particular
-- calendar day, but can (depending on precedence) be transferred to another
-- day and/or have an associated "eve-of" service.
--
CREATE TABLE fixed_feasts (
fixed_id serial,
name text NOT NULL,
code text,
otype_id integer NOT NULL,
month integer NOT NULL,
day integer NOT NULL,
schedule_pattern text,
has_eve boolean NOT NULL DEFAULT FALSE,
eve_schedule_pattern text,
eve_name text,
color text,
note text,
valid_start timestamp with time zone NULL,
valid_end timestamp with time zone NULL,
CONSTRAINT fixed_feasts_pk PRIMARY KEY (fixed_id),
CONSTRAINT fixed_feasts_otype_fk FOREIGN KEY (otype_id)
REFERENCES observance_types (otype_id)
ON DELETE RESTRICT ON UPDATE NO ACTION
);
CREATE INDEX fixed_feasts_month_idx ON fixed_feasts (month);
CREATE INDEX fixed_feasts_date_idx ON fixed_feasts (month, day);
-- rambler down
DROP TABLE fixed_feasts;
<file_sep>/bin/calendar_builder/process/calculate_year.py
import argparse
import datetime
import logging
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine.url import URL
from ..resolution import Resolution
from ..fetch.overrides import Overrides
from ..storage import Storage
# Make sure we have a config
try:
from ..config import config
except IOError:
raise RuntimeError("Cannot find database configuration")
def handle_args():
""" Gathers commmand line options and sets up logging according to the verbose param. Returns the parsed args """
parser = argparse.ArgumentParser(description='Calculate the liturgical calendar for a given year')
parser.add_argument('year', type=int, help='the year you want to build')
parser.add_argument('--dry-run', '-d', action='store_true', help='print the calculated year rather than storing it')
parser.add_argument('--rules-only', '-r', action='store_true', help='use regular rules only: do not include any one-time overrides')
parser.add_argument('--show-extras', action='store_true', help='after calculating, print any feasts/holidays that fell outside the year (used only on dry run)')
parser.add_argument('--verbose', '-v', action='count')
args = parser.parse_args()
if args.verbose == 1:
logging.basicConfig(level=logging.INFO)
elif args.verbose == 2:
logging.basicConfig(level=logging.DEBUG)
elif args.verbose >= 3:
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
else:
logging.basicConfig(level=logging.WARNING)
return args
def db_connect():
""" Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """
return create_engine(URL(**config['database']))
def print_year(static, add_extras=False):
""" Prints out the full year, with blank lines between months """
current_month = 1
for cdate in sorted(static.all_days.iterkeys()):
if current_month != static.all_days[cdate].day.month:
print ""
current_month = static.all_days[cdate].day.month
print static.all_days[cdate]
if add_extras:
print ""
print "Any extras:"
for cdate in sorted(resolution.extras.iterkeys()):
print cdate + ": "
for f in resolution.extras[cdate]:
print f
def store_calculated(year, logger, static, session):
""" Stores the calculated year """
def main():
""" Runs the whole shebang """
logger = logging.getLogger(__name__)
args = handle_args()
# DB Setup
engine = db_connect()
Session = sessionmaker(bind=engine)
# Calculate for this year
CALC_YEAR = args.year
# Primary calculation
logger.info('Calculating year...')
fetching_session = Session()
resolution = Resolution(fetching_session)
static = resolution.calculate_year(CALC_YEAR)
logger.info('done')
# If this is not a dry run, save to the database as a calculated year
if not args.dry_run:
logger.info('Saving the cacluclated year...')
calc_save_session = Session()
storage = Storage(CALC_YEAR, calc_save_session)
storage.save_calculated(static)
calc_save_session.commit()
logger.info('done')
pass
# Rules only: stop here
if args.rules_only:
if args.dry_run:
print_year(static, args.show_extras)
return
# Add overrides
overrides = Overrides(fetching_session)
static.override(overrides.get_year(CALC_YEAR))
logger.debug('Added overrides')
# If this is a dry run, print and stop
if args.dry_run:
print_year(static, args.show_extras)
return
# Store to database as a cached year
logger.info('Saving the calcuclated year...')
cache_save_session = Session()
storage = Storage(CALC_YEAR, cache_save_session)
storage.save_cached(static)
cache_save_session.commit()
logger.info('done')
<file_sep>/front/lib/queries/select_calendar_by_dates.sql
--
-- Select the calendar for a date range out of the cached table
--
SELECT c.cached_id, c.target_date, c.target_block, c.name,
c.color, c.note, s.name AS service_name,
s.start_time AS service_start_time
FROM cached c
LEFT JOIN cached_services s ON (c.cached_id = s.cached_id)
WHERE c.target_date BETWEEN $1 AND $2
ORDER BY c.target_date, c.target_block, s.start_time
<file_sep>/database/migrations/20160811165200_schema_completed.sql
-- rambler up
--
-- These tables define the title, schedule of services, and color to be used for a particular day.
--
CREATE TABLE completed (
completed_id serial,
title text NOT NULL,
day date NOT NULL,
is_vigil boolean NOT NULL DEFAULT false,
color text NOT NULL,
note text,
CONSTRAINT completed_pk PRIMARY KEY (completed_id),
CONSTRAINT completed_uq UNIQUE (day, is_vigil)
);
CREATE TABLE completed_services (
cservice_id serial,
completed_id integer NOT NULL,
name text NOT NULL,
start_time time with time zone NOT NULL,
CONSTRAINT completed_services_pk PRIMARY KEY (cservice_id),
CONSTRAINT completed_services_completed_fk FOREIGN KEY (completed_id)
REFERENCES completed (completed_id)
ON DELETE CASCADE ON UPDATE NO ACTION
);
-- rambler down
DROP TABLE completed_services;
DROP TABLE completed;
<file_sep>/bin/calendar_builder/static.py
import copy
import datetime
import logging
from . import utils
class StaticRange:
"""Describes a resolved date range"""
def __init__(self, start, end, session):
"""Constructor"""
self.start = start
self.end = end
self.session = session
self.logger = logging.getLogger(__name__)
self.all_days = {}
c = copy.deepcopy(self.start)
while c <= self.end:
cdate = utils.day_to_lookup(c)
sday = StaticDay(c, self.logger)
self.all_days[cdate] = sday
c = c + datetime.timedelta(days=1)
def override(self, overrides):
"""Sets overrides on this range"""
for ovr in overrides:
cdate = utils.day_to_lookup(ovr['day'])
if cdate in self.all_days:
self.all_days[cdate].override(ovr)
else:
self.logger.warn('Trying to override on wrong date {date}'.format(date=str(ovr['day'])))
class StaticYear(StaticRange):
"""Describes a resolved year"""
def __init__(self, year, session):
"""Constructor"""
self.year = year
self.start = datetime.date(year, 1, 1)
self.end = datetime.date(year, 12, 31)
self.session = session
self.logger = logging.getLogger(__name__)
self.all_days = {}
c = datetime.date(year, 1, 1)
c = copy.deepcopy(self.start)
while c <= self.end:
cdate = utils.day_to_lookup(c)
sday = StaticDay(c, self.logger)
self.all_days[cdate] = sday
c = c + datetime.timedelta(days=1)
class StaticDay:
"""Describes a resolved day"""
def __init__(self, day, logger):
"""Constructor"""
self.day = copy.deepcopy(day)
self.base_block = None
self.vigil_block = None
self.logger = logger
def has_vigil(self):
"""Returns whether the day has a vigil"""
return self.vigil_block is not None
def override(self, ovr):
"""Sets overrides on this day"""
if ovr['target_block'] == 'vigil':
if self.vigil_block is None:
self.vigil_block = StaticBlock(self.logger)
self.vigil_block.override(ovr)
elif ovr['target_block'] == 'base':
if self.base_block is None:
self.base_block = StaticBlock(self.logger)
self.base_block.override(ovr)
else:
self.logger.warn('Trying to override on target block {block}'.format(block=ovr['target_block']))
def __repr__(self):
"""Displays the day as a string"""
rep = self.day.strftime('%Y-%m-%d') + ' (' + utils.weekday(self.day) + '):'
rep += "\n\t" + str(self.base_block)
if self.vigil_block is not None:
rep += "\n\t" + str(self.vigil_block)
return rep
class StaticBlock:
"""Describes a resolved block"""
def __init__(self, logger):
"""Constructor"""
self.color = None
self.name = None
self.note = None
self.services = []
self.logger = logger
def override(self, override):
"""Sets an override on this block"""
if 'color' in override:
self.color = override['color']
if 'name' in override:
self.name = override['name']
if 'note' in override:
self.note = override['note']
if 'services' in override:
self.services = []
for ovr_service in override['services']:
self.services.append(StaticService(ovr_service['name'], ovr_service['start_time']))
def __repr__(self):
"""Displays the block as a string"""
rep = '[' + str(self.color) + '] ' + str(self.name)
if self.note is not None:
lines = self.note.split("\n")
rep += "\n\t\t(" + "\n\t\t ".join(lines) + ')'
for service in self.services:
rep += "\n\t\t* " + str(service)
return rep
class StaticService:
"""Describes a resolved service"""
def __init__(self, name, start_time):
"""Constructor"""
self.name = name
self.start_time = start_time
def __repr__(self):
return self.name + ' ' + utils.ftime(self.start_time)
<file_sep>/bin/calendar_builder/fetch/overrides.py
import datetime
from sqlalchemy import text
from sqlalchemy.orm import eagerload,joinedload
import sys
from ..models import Override
class Overrides:
"""Class for fetching custom overrides to be placed over the static calendar"""
def __init__(self, session):
"""Sets up the placer"""
self.session = session
def get_year(self, year):
"""Gets the overrides for a year as dictionaries suitable for overriding the static calendar"""
for_year = []
for instance in self.session.query(Override).\
options(joinedload(Override.services)).\
filter(text("target_date BETWEEN :year_start AND :year_end")).\
params(year_start=datetime.date(year, 1, 1).strftime('%Y-%m-%d'),\
year_end=datetime.date(year, 12, 31).strftime('%Y-%m-%d')).\
order_by(Override.target_date, Override.target_block, Override.id):
for_year.append(instance)
all_overrides = []
for o in for_year:
override = {}
override['day'] = o.target_date
override['target_block'] = o.target_block
override['color'] = o.color
override['name'] = o.name
override['services'] = []
for s in o.services:
override['services'].append({ 'name': s.name, 'start_time': s.start_time })
all_overrides.append(override)
return all_overrides
def get_range(self, start, end):
"""Gets the overrides for a time range as dictionaries suitable for overriding the static calendar"""
for_range = []
for instance in self.session.query(Override).\
options(joinedload(Override.services)).\
filter(text("target_date BETWEEN :range_start AND :range_end")).\
params(range_start=start.strftime('%Y-%m-%d'),\
range_end=end.strftime('%Y-%m-%d')).\
order_by(Override.target_date, Override.target_block, Override.id):
for_range.append(instance)
all_overrides = []
for o in for_range:
override = {}
override['day'] = o.target_date
override['target_block'] = o.target_block
override['color'] = o.color
override['name'] = o.name
override['services'] = []
for s in o.services:
override['services'].append({ 'name': s.name, 'start_time': s.start_time })
all_overrides.append(override)
return all_overrides
<file_sep>/bin/calendar_builder/process/read_calc_request_queue.py
import argparse
import boto3
import datetime
import dateutil
import json
import logging
import signal
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine.url import URL
import sys
import time
from ..fetch.calculated import Calculated
from ..fetch.overrides import Overrides
from ..resolution import Resolution
from ..storage import Storage
# Make sure we have a config
try:
from ..config import config
except IOError:
raise RuntimeError("Cannot find configuration")
def handle_args():
""" Gathers commmand line options and sets up logging according to the verbose param. Returns the parsed args """
parser = argparse.ArgumentParser(description='Checks the queue for new messages and caclulates the calendar as needed')
parser.add_argument('--verbose', '-v', action='count')
args = parser.parse_args()
if args.verbose == 1:
logging.basicConfig(level=logging.INFO)
elif args.verbose == 2:
logging.basicConfig(level=logging.DEBUG)
elif args.verbose >= 3:
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
else:
logging.basicConfig(level=logging.WARNING)
return args
def handle_signal(signal, frame):
"""Finish properly in case of signal"""
logger.info('Stopped')
sys.exit(0)
def db_connect():
""" Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """
return create_engine(URL(**config['database']))
def fetch_message(sqs, queue_url):
"""Fetches a message from the queue and parses it into a dictionary (keys: ok, start, end, handle)"""
response = sqs.receive_message(
QueueUrl = queue_url,
AttributeNames = [ 'SentTimestamp' ],
MaxNumberOfMessages = 1,
MessageAttributeNames = [ 'All' ],
WaitTimeSeconds = 5
)
parsed = { 'ok': True }
if response.get('Messages'):
m = response.get('Messages')[0]
body = m['Body']
receipt_handle = m['ReceiptHandle']
try:
query = json.loads(body)
except ValueError:
logger.warn('Message recieved was not valid json: ' + body)
if query and 'start' in query and 'end' in query:
dts = dateutil.parser.parse(query['start'])
if dts is None:
logger.warn('Could not parse start date string ' + query['start'])
parsed['ok'] = False
dte = dateutil.parser.parse(query['end'])
if dte is None:
logger.warn('Could not parse end date string ' + query['start'])
parsed['ok'] = False
if parsed['ok']:
logger.info('Received message: ' + dts.isoformat() + ' to ' + dte.isoformat())
parsed['start'] = dts
parsed['end'] = dte
else:
logger.warn('Message recieved was not a valid calc request: ' + body)
parsed['ok'] = False
parsed['handle'] = receipt_handle
return parsed
else:
logger.debug('No message')
return None
def handle_request(message):
"""Looks at the start and end dates and builds as needed"""
if not message['ok']:
logger.error('Cannot handle bad request')
return
engine = db_connect()
Session = sessionmaker(bind=engine)
check_session = Session()
calc = Calculated(check_session)
# Static calendar already calculated? Skip the calculation step
if calc.check_window(message['start'], message['end']):
logger.info('Date range has been calculated')
# No? Calculate each year that we need
else:
logger.info('Start year: ' + str(message['start'].year))
logger.info('End year: ' + str(message['end'].year))
plural = message['start'].year != message['end'].year
if plural:
logger.info('Checking years...')
else:
logger.info('Checking year...')
curr = message['start'].year
found = {}
while curr <= message['end'].year:
found[curr] = calc.check_year(curr)
curr += 1
logger.info('done')
for y in found:
if not found[y]:
# If we need to calculate this year, do so
logger.info('Year ' + str(y) + ': calculating base schedule...')
fetching_session = Session()
resolution = Resolution(fetching_session)
static = resolution.calculate_year(y)
logger.info('done')
# Save what we did
logger.info('Saving the cacluclated year...')
calc_save_session = Session()
storage = Storage(y, calc_save_session)
storage.save_calculated(static)
calc_save_session.commit()
logger.info('done')
# Load up the requested window
static = calc.load_static_range(message['start'], message['end'])
logger.debug('Loaded the static range')
# Add overrides
fetching_session = Session()
overrides = Overrides(fetching_session)
static.override(overrides.get_range(message['start'], message['end']))
logger.debug('Added overrides')
# Save to the cache
logger.info('Saving the completed year...')
cache_save_session = Session()
storage = Storage(message['start'].year, cache_save_session)
storage.save_cached(static)
cache_save_session.commit()
logger.info('done')
def main():
"""Checks the queue for new messages and caclulates as needed"""
global logger
logger = logging.getLogger(__name__)
logger.info('Reading from the queue...')
args = handle_args()
signal.signal(signal.SIGINT, handle_signal)
sqs = boto3.client('sqs')
queue_url = config['message_queue']['calc_request_url']
while True:
message = fetch_message(sqs, queue_url)
if message is not None:
if message['ok']:
handle_request(message)
sqs.delete_message(
QueueUrl = queue_url,
ReceiptHandle = message['handle']
)
time.sleep(1)
<file_sep>/bin/calendar_builder/config.py
# Loads the config file and sets some constants
import os
import yaml
CONFIG_PATH = os.path.dirname(os.path.realpath(__file__)) + '/../config.yml'
config = yaml.safe_load(open(CONFIG_PATH))
<file_sep>/front/lib/Memcached.js
/**
* Manage access to memcached
*/
if (!global.Memcached) {
var Cache = require('memcached-promisify');
global.Memcached = new Cache();
}
module.exports = global.Memcached;
<file_sep>/README.md
# liturgicalendar
provides a basic liturgical calendar, with the option of overriding services as needed
<file_sep>/bin/calendar_builder/valid_dates.py
import datetime
def valid_in_list(collection, date):
"""For each item in the collection, check its valid start and end dates against the date given"""
for elem in collection:
if elem.valid_start is None and elem.valid_end is None:
return elem
elif elem.valid_start is None:
if date < elem.valid_end.date():
return elem
elif elem.valid_end is None:
if date > elem.valid_start.date():
return elem
elif date > elem.valid_start.date() and date < elem.valid_end.date():
return elem
return None
<file_sep>/bin/calendar_builder/resolution.py
import copy
import datetime
import logging
from .config import config
from .fetch.federal_holidays import FederalHolidays
from .fetch.fixed_feasts import FixedFeasts
from .fetch.floating_feasts import FloatingFeasts
from .fetch.moveable_feasts import MoveableFeasts
from .season import YearIterator
from .static import StaticYear
from . import utils
from .valid_dates import valid_in_list
class Resolution:
"""Calculate the liturgical calendar for a full year"""
def __init__(self, session):
"""Constructor"""
self.session = session
self.logger = logging.getLogger(__name__)
def calculate_year(self, year):
"""Calculates the liturgical calendar and returns it as a StaticYear"""
# Start up Resolution for this year
self.logger.info('Starting resolution for ' + str(year))
resolution = ResolutionYear(year, self.session, self.logger)
# Set up the season framework
self.logger.info('Importing seasons...')
resolution.import_seasons()
self.logger.info('done')
# Add moveable feasts
self.logger.info('Adding moveable feasts...')
resolution.import_moveable_feasts()
self.logger.info('done')
# Add fixed feasts
self.logger.info('Adding fixed feasts...')
resolution.import_fixed_feasts()
self.logger.info('done')
# Add federal holidays
self.logger.info('Adding federal holidays...')
resolution.import_federal_holidays()
self.logger.info('done')
# Resolve
self.logger.info('Resolving...')
for cdate in sorted(resolution.full_year.iterkeys()):
resolution.full_year[cdate].resolve()
self.logger.info('done')
# Add floating feasts and re-resolve
self.logger.info('Adding floating feasts...')
resolution.import_floating_feasts()
for cdate in sorted(resolution.full_year.iterkeys()):
resolution.full_year[cdate].resolve()
self.logger.info('done')
# Freeze the current state
self.logger.info('Freezing current state...')
static = resolution.freeze()
self.logger.info('done')
return static
class ResolutionYear:
"""Describes a year in the resolution process"""
def __init__(self, year, session, logger):
"""Constructor"""
self.year = year
self.session = session
self.logger = logger
self.full_year = {}
self.extras = {}
def import_seasons(self):
"""Walk though the year and lay down our defaults according to the season on that date"""
self.season_ticker = YearIterator(self.session, self.year)
self.logger.debug('Fetched season iterator and began initial walk')
while self.season_ticker.day.year == self.year:
cdate = utils.day_to_lookup(self.season_ticker.day)
self.full_year[cdate] = ResolutionDay(self.season_ticker.day, self)
self.full_year[cdate].set_season(self.season_ticker.current(), self.season_ticker.sunday_count, self.season_ticker.is_last_week())
self.season_ticker.advance_by_day()
self.logger.debug('Completed initial walk')
# We also need one day of the next year, in case of vigil
alt_season_ticker = YearIterator(self.session, self.year + 1)
self.logger.debug('Fetched season iterator for day one of next year')
self.next_year_first = ResolutionDay(alt_season_ticker.day, self)
self.next_year_first.set_season(alt_season_ticker.current(), alt_season_ticker.sunday_count, alt_season_ticker.is_last_week())
def import_moveable_feasts(self):
"""Fetch moveable feasts and place them on the proper days"""
self.moveable = MoveableFeasts(self.session, self.year)
mf = self.moveable.feasts_by_date()
self.logger.debug('Found moveable feasts on {days} days'.format(days=len(mf)))
for info in mf:
cdate = utils.day_to_lookup(info['day'])
if cdate in self.full_year:
self.full_year[cdate].add_feast(ResolutionFeast(info['feasts'], info['day']))
else:
if cdate not in self.extras:
self.extras[cdate] = []
self.extras[cdate].append(ResolutionFeast(info['feasts'], info['day']))
self.logger.debug('Added moveable feasts')
def import_fixed_feasts(self):
"""Fetch fixed feasts and place them on the proper days"""
self.fixed = FixedFeasts(self.session, self.year)
ff = self.fixed.feasts_by_date()
self.logger.debug('Found fixed feasts on {days} days'.format(days=len(ff)))
for info in ff:
cdate = utils.day_to_lookup(info['day'])
if cdate in self.full_year:
self.full_year[cdate].add_feast(ResolutionFeast(info['feasts'], info['day']))
else:
if cdate not in self.extras:
self.extras[cdate] = []
self.extras[cdate].append(ResolutionFeast(info['feasts'], info['day']))
self.logger.debug('Added fixed feasts')
def import_floating_feasts(self):
"""Fetch floating feasts and place them on the proper days"""
self.floating = FloatingFeasts(self.session, self.year)
ff = self.floating.get_for_year(self.year, self.full_year)
self.logger.debug('Found floating feasts on {days} days'.format(days=len(ff)))
for info in ff:
cdate = utils.day_to_lookup(info['day'])
if cdate in self.full_year:
self.full_year[cdate].add_feast(ResolutionFeast(info['feasts'], info['day']))
else:
if cdate not in self.extras:
self.extras[cdate] = []
self.extras[cdate].append(ResolutionFeast(info['feasts'], info['day']))
self.logger.debug('Added floating feasts')
def import_federal_holidays(self):
"""Fetch federal holidays and place them on the proper days"""
self.federal = FederalHolidays(self.session, self.year)
fh = self.federal.holidays_by_date()
self.logger.debug('Found federal holidays on {days} days'.format(days=len(fh)))
for info in fh:
cdate = utils.day_to_lookup(info['day'])
if cdate in self.full_year:
self.full_year[cdate].add_holiday(ResolutionHoliday(info['holidays'], info['day']))
else:
if cdate not in self.extras:
self.extras[cdate] = []
self.extras[cdate].append(ResolutionHoliday(info['holidays'], info['day']))
self.logger.debug('Added federal holidays')
def freeze(self):
"""Freezes the current resolution and returns the static year"""
static_year = StaticYear(self.year, self.session)
overrides = []
for cdate in sorted(self.full_year.iterkeys()):
res_day = self.full_year[cdate]
if res_day.base_block is not None:
overrides.append(self._block_to_override(res_day.day, res_day.base_block, False))
if res_day.vigil_block is not None:
overrides.append(self._block_to_override(res_day.day, res_day.vigil_block, True))
static_year.override(overrides)
self.logger.debug('Froze year')
return static_year
def _block_to_override(self, day, block, is_vigil):
"""Converts a resolution block into a dictionary suitable for static overrides"""
override = {}
override['day'] = day
if is_vigil:
override['target_block'] = 'vigil'
else:
override['target_block'] = 'base'
override['color'] = block.color
override['name'] = block.name
override['note'] = block.note
override['services'] = []
for service in block.services:
override['services'].append({ 'name': service.name, 'start_time': service.start_time })
return override
def before(self, day):
"""Returns the day before the day given"""
target = copy.deepcopy(day)
target = target - datetime.timedelta(days=1)
return self.full_year[utils.day_to_lookup(target)]
def after(self, day):
"""Returns the day after the day given"""
target = copy.deepcopy(day)
target = target + datetime.timedelta(days=1)
cdate = utils.day_to_lookup(target)
if cdate in self.full_year:
return self.full_year[cdate]
class ResolutionDay:
"""Describes a day in the resolution process"""
def __init__(self, day, year):
"""Sets up a day within a year"""
self.day = copy.deepcopy(day)
self.year = year
self.season = None
self.current_feast = None
self.current_precedence = 100
self.has_vigil = False
self.feasts = []
self.holidays = []
self.base_block = None
self.vigil_block = None
self.logger = year.logger
def set_season(self, season, sunday_count, is_last_week):
"""Sets the season info for this day"""
self.season = season
self.sunday_count = sunday_count
self.is_last_week = is_last_week
def add_feast(self, feast):
"""Adds a feast"""
feast.change_day(self.day)
self.feasts.append(feast)
def add_holiday(self, holiday):
"""Adds a holiday"""
holiday.change_day(self.day)
self.holidays.append(holiday)
def resolve(self):
"""Look at today's season and any feasts, then set the main and vigil blocks accordingly"""
if self.season is None:
self.logger.warn('No season data for ' + utils.day_to_lookup(self.day))
return
pattern = self.season.pattern(self.day)
if pattern.has_vigil(self.day):
self._set_vigil_for_season()
else:
self._make_block_from_season()
self.current_precedence = self.season.precedence(self.day)
current_feast = None
for feast in self.feasts:
if feast.precedence() <= self.current_precedence:
self.current_precedence = feast.precedence()
current_feast = feast
elif feast.precedence() <= config['transfer_precedence']:
tomorrow = self.year.after(self.day)
tomorrow.add_feast(feast)
self.feasts.remove(feast)
self.logger.debug('Transferring ' + feast.name() + ' to ' + utils.day_to_lookup(tomorrow.day))
if current_feast is not None:
self.current_feast = current_feast
self._make_block_from_feast()
if self.current_feast.has_eve():
# Look back to yesterday and set the vigil
yesterday = self.year.before(self.day)
yesterday._set_vigil_for_feast(self.current_feast)
for holiday in self.holidays:
if holiday.open_time() is not None or holiday.close_time() is not None:
if self.base_block.check_open_hours(holiday.open_time(), holiday.close_time()):
self.base_block.set_open_hours(holiday.open_time(), holiday.close_time())
else:
self.base_block = None
if self.vigil_block is not None:
if self.vigil_block.check_open_hours(holiday.open_time(), holiday.close_time()):
self.vigil_block.set_open_hours(holiday.open_time(), holiday.close_time())
else:
self.vigil_block = None
if self.base_block is not None:
note_lines = []
if not holiday.skip_name():
note_lines.append(holiday.name())
if holiday.note() is not None:
note_lines.append(holiday.note())
if self.base_block.note is not None and len(note_lines) > 0:
self.base_block.note = "\n".join(note_lines) + "\n" + self.base_block.note
elif len(note_lines) > 0:
self.base_block.note = "\n".join(note_lines)
def _make_block_from_feast(self):
"""Use the current feast to set today's main block"""
if self.current_feast is None:
self.logger.warn('Attempting to make block from missing feast on ' + utils.day_to_lookup(self.day))
return
pattern = self.current_feast.pattern()
if pattern is None:
pattern = self.season.pattern(self.day)
if pattern is None:
self.logger.warn('Missing pattern for ' + self.current_feast.name() + ' on ' + utils.day_to_lookup(self.day))
schedule = pattern.schedule(self.day, has_vigil = self.has_vigil)
if schedule is None:
self.logger.warn('Missing schedule for ' + self.current_feast.name() + ' on ' + utils.day_to_lookup(self.day))
return
self.base_block = ResolutionBlock(
color = self.current_feast.color(),
name = self.current_feast.name(),
note = self.current_feast.note(),
schedule = schedule
)
def _make_block_from_season(self):
"""Use the current season to set today's main block"""
if self.season is None:
self.logger.warn('Attempting to make block from missing season on ' + utils.day_to_lookup(self.day))
return
pattern = self.season.pattern(self.day)
if pattern is None:
self.logger.warn('Missing season pattern on ' + utils.day_to_lookup(self.day))
schedule = pattern.schedule(self.day, has_vigil = self.has_vigil)
if schedule is None:
self.logger.warn('Missing season schedule on ' + utils.day_to_lookup(self.day))
return
self.base_block = ResolutionBlock(
color = self.season.color,
name = self.season.day_name(self.day, sunday_count = self.sunday_count, is_last = self.is_last_week),
note = self.season.day_note(self.day),
schedule = schedule
)
def _set_vigil_for_feast(self, feast):
"""Sets the vigil block on this day for a feast happening tomorrow"""
pattern = feast.eve_pattern()
if pattern is None:
pattern = self.season.pattern(self.day)
vigil_name = feast.eve_name()
if vigil_name is None:
vigil_name = 'Eve of ' + feast.name()
vigil_schedule = pattern.schedule(self.day, is_vigil = True)
if vigil_schedule is None:
self.logger.warn('Missing vigil schedule for ' + feast.name() + ' on ' + utils.day_to_lookup(self.day))
return
cp = self.season.precedence(self.day)
for f in self.feasts:
if cp > f.precedence():
cp = f.precedence()
if cp < feast.precedence():
return
self.has_vigil = True
self.vigil_block = ResolutionBlock(
color = feast.color(),
name = vigil_name,
schedule = vigil_schedule
)
if self.current_feast:
self._make_block_from_feast()
else:
self._make_block_from_season()
def _set_vigil_for_season(self):
"""Sets the vigil block on this day using tomorrow's season info"""
tomorrow = self.year.after(self.day)
if tomorrow is None:
self.logger.info('Setting vigil from the first day of next year')
tomorrow = self.year.next_year_first
self.has_vigil = True
tpattern = tomorrow.season.pattern(self.day)
self.vigil_block = ResolutionBlock(
color = tomorrow.season.color,
name = tomorrow.season.day_name(self.day, is_vigil = True, sunday_count = tomorrow.sunday_count, is_last = tomorrow.is_last_week),
schedule = tpattern.schedule(self.day, is_vigil = True)
)
if self.current_feast:
self._make_block_from_feast()
else:
self._make_block_from_season()
def __repr__(self):
"""Displays the day as a string"""
rep = self.day.strftime('%Y-%m-%d') + ' (' + utils.weekday(self.day) + '):'
rep += "\n\t" + str(self.base_block)
if self.vigil_block is not None:
rep += "\n\t" + str(self.vigil_block)
return rep
class ResolutionBlock:
"""Describes a service block on a particular day"""
def __init__(self, **kwargs):
"""Constructor"""
if 'color' in kwargs:
self.color = kwargs['color']
else:
self.color = None
if 'name' in kwargs:
self.name = kwargs['name']
else:
self.name = None
if 'note' in kwargs:
self.note = kwargs['note']
else:
self.note = None
if 'schedule' in kwargs:
self.schedule = kwargs['schedule']
self.services = self.schedule.sort_services()
else:
self.schedule = None
self.services = []
def check_open_hours(self, open_time, close_time):
"""Check the open hours against the service times to see if this block will have any services left"""
ok = []
if open_time is None:
open_time = datetime.time(0, 0, 0)
if close_time is None:
close_time = datetime.time(23, 59, 59)
for s in self.services:
n = s.start_time.replace(tzinfo=None)
if n > open_time and n < close_time:
ok.append(s)
return len(ok) > 0
def set_open_hours(self, open_time, close_time):
"""Slice off services outside the open hours"""
ok = []
if open_time is None:
open_time = datetime.time(0, 0, 0)
if close_time is None:
close_time = datetime.time(23, 59, 59)
for s in self.services:
n = s.start_time.replace(tzinfo=None)
if n > open_time and n < close_time:
ok.append(s)
self.services = ok
def __repr__(self):
"""Displays the block as a string"""
rep = '[' + str(self.color) + '] ' + str(self.name)
if self.note is not None:
lines = self.note.split("\n")
rep += "\n\t\t(" + "\n\t\t ".join(lines) + ')'
for service in self.services:
rep += "\n\t\t* " + str(service)
return rep
class ResolutionFeast:
"""Describes a feast we're putting on the calendar"""
def __init__(self, feasts, day):
"""Constructor"""
self.feasts = feasts
self.original_day = day
self.current_day = day
def _get_for_day(self, day):
"""Selects the feast model that's valid for a given day"""
return valid_in_list(self.feasts, day)
def change_day(self, day):
"""Changes the current day"""
self.current_day = day
def precedence(self):
"""Selects the precedence for this feast"""
f = self._get_for_day(self.current_day);
if f:
return f.otype.precedence
else:
return -1
def code(self):
"""Selects the code for this feast"""
f = self._get_for_day(self.current_day);
if f:
return f.code
else:
return ''
def color(self):
"""Selects the color for this feast"""
f = self._get_for_day(self.current_day);
if f:
return f.color
else:
return ''
def name(self):
"""Selects the name for this feast"""
f = self._get_for_day(self.current_day);
if f:
return f.name
else:
return ''
def note(self):
"""Selects the note for this feast"""
f = self._get_for_day(self.current_day);
if f:
return f.note
else:
return ''
def pattern(self):
"""Selects the pattern for this feast"""
f = self._get_for_day(self.current_day);
if f:
return f.pattern(self.current_day)
else:
return ''
def has_eve(self):
"""Selects the eve flag for this feast"""
f = self._get_for_day(self.current_day);
if f:
return f.has_eve
else:
return ''
def eve_name(self):
"""Selects the eve name for this feast"""
f = self._get_for_day(self.current_day);
if f:
return f.eve_name
else:
return ''
def eve_pattern(self):
"""Selects the eve pattern for this feast"""
f = self._get_for_day(self.current_day);
if f:
return f.eve_pattern(self.current_day)
else:
return ''
def __repr__(self):
"""Displays the feast as a string"""
rep = '[' + str(self.color()) + '] ' + str(self.name())
if self.note() is not None:
lines = self.note().split("\n")
rep += "\n\t\t(" + "\n\t\t ".join(lines) + ')'
if self.pattern():
rep += "\n\t\t* " + str(self.pattern().schedule(self.current_day))
return rep
class ResolutionHoliday:
"""Describes a holiday we're putting on the calendar"""
def __init__(self, holidays, day):
"""Constructor"""
self.holidays = holidays
self.original_day = day
self.current_day = day
def _get_for_day(self, day):
"""Selects the holiday model that's valid for a given day"""
return valid_in_list(self.holidays, day)
def change_day(self, day):
"""Changes the current day"""
self.current_day = day
def name(self):
"""Selects the name for this holiday"""
h = self._get_for_day(self.current_day);
if h:
return h.name
else:
return ''
def code(self):
"""Selects the code for this holiday"""
h = self._get_for_day(self.current_day);
if h:
return h.code
else:
return ''
def note(self):
"""Selects the note for this holiday"""
h = self._get_for_day(self.current_day);
if h:
return h.note
else:
return ''
def open_time(self):
"""Selects the church open time for this holiday"""
h = self._get_for_day(self.current_day);
if h:
return h.open_time
else:
return ''
def close_time(self):
"""Selects the church close time for this holiday"""
h = self._get_for_day(self.current_day);
if h:
return h.close_time
else:
return ''
def skip_name(self):
"""Selects the skip-name flag for this holiday"""
h = self._get_for_day(self.current_day);
if h:
return h.skip_name
else:
return False
def __repr__(self):
"""Displays the holiday as a string"""
rep = str(self.name()) + ' <' + str(self.code()) + '>: Church open ' + str(self.open_time()) + ' to ' + str(self.close_time())
if self.note() is not None:
lines = self.note().split("\n")
rep += "\n\t\t(" + "\n\t\t ".join(lines) + ')'
return rep
<file_sep>/bin/calendar_builder/season.py
import copy
import datetime
from sqlalchemy import text
from sqlalchemy.orm import joinedload
from .models import Season
class YearIterator:
"""Class for stepping through seasons in a year"""
def __init__(self, session, year):
"""Sets up the iterator"""
self.session = session
self.day = datetime.date(year, 1, 1)
self.load_seasons()
# The year starts in the Christmas season of the previous year, so load that up as our current season
self.current_index = 0
self.started = datetime.date(year - 1, 12, 25)
self.ends = self.current().end_date(self.started)
self.sunday_count = 0
check_day = copy.deepcopy(self.started)
while check_day < self.day:
if check_day.strftime('%A').lower()[:3] == 'sun':
self.sunday_count += 1
check_day = check_day + datetime.timedelta(days=1)
def load_seasons(self):
"""Fetches the seasons from the database needed for this year"""
# Arbitrary rule: seasons for a year are noted valid for the first of that year,
# even though the church year properly begins with Advent.
self.by_code = {}
self.loop = []
for instance in self.session.query(Season).\
options(joinedload(Season.all_patterns)).\
filter(text("valid_for_date(:jan_first, seasons.valid_start, seasons.valid_end)")).\
params(jan_first=datetime.date(self.day.year, 1, 1).strftime('%Y-%m-%d')).\
order_by(Season.sort_order):
code = instance.code
self.by_code[code] = instance
self.loop.append(code)
def current(self):
"""Returns the current season"""
code = self.loop[self.current_index]
return self.by_code[code]
def is_last_week(self):
"""Returns whether this is the last week of the season"""
return (self.ends - self.day).days < 7
def advance_by_day(self):
"""Pushes the day up by one"""
self.day = self.day + datetime.timedelta(days=1)
if self.day.strftime('%A').lower()[:3] == 'sun':
self.sunday_count += 1
if (self.day > self.ends):
self.next_season()
def next_season(self):
"""Tick forward by one season"""
start = self.ends + datetime.timedelta(days=1)
if (self.current_index + 1 < len(self.loop)):
self.current_index = self.current_index + 1
else:
self.current_index = 0
self.started = start
self.ends = self.current().end_date(start)
if not self.current().continue_counting:
self.sunday_count = 0
if self.day.strftime('%A').lower()[:3] == 'sun' and self.current().counting_index:
self.sunday_count += 1
<file_sep>/database/migrations/20160810131215_stmarys_services.sql
-- rambler up
--
-- Define services
--
INSERT INTO services (name, start_time, is_default) VALUES ('Morning Prayer', '08:30:00', true); -- 1
INSERT INTO services (name, start_time, is_default) VALUES ('Noonday Prayer', '12:00:00', true); -- 2
INSERT INTO services (name, start_time, is_default) VALUES ('Mass', '12:10:00', true); -- 3
INSERT INTO services (name, start_time, is_default) VALUES ('Mass with Healing Service', '12:10:00', true); -- 4
INSERT INTO services (name, start_time, is_default) VALUES ('Evening Prayer', '18:00:00', true); -- 5
INSERT INTO services (name, start_time, is_default) VALUES ('Confessions', '11:30:00', true); -- 6
INSERT INTO services (name, start_time, is_default) VALUES ('Confessions', '16:00:00', true); -- 7
INSERT INTO services (name, start_time, is_default) VALUES ('Evening Prayer', '17:00:00', true); -- 8
INSERT INTO services (name, start_time, is_default) VALUES ('Sunday Vigil Mass', '17:20:00', true); -- 9
INSERT INTO services (name, start_time, is_default) VALUES ('<NAME>', '08:30:00', true); -- 10
INSERT INTO services (name, start_time, is_default) VALUES ('Mass', '09:00:00', true); -- 11
INSERT INTO services (name, start_time, is_default) VALUES ('Mass', '10:00:00', true); -- 12
INSERT INTO services (name, start_time, is_default) VALUES ('Solemn Mass', '11:00:00', true); -- 13
INSERT INTO services (name, start_time, is_default) VALUES ('Organ Recital', '16:40:00', true); -- 14
INSERT INTO services (name, start_time, is_default) VALUES ('Solemn Evensong & Benediction', '17:00:00', true); -- 15
INSERT INTO services (name, start_time, is_default) VALUES ('Solemn Evensong & Benediction', '18:00:00', false); -- 16
INSERT INTO services (name, start_time, is_default) VALUES ('Solemn Evensong', '18:00:00', false); -- 17
INSERT INTO services (name, start_time, is_default) VALUES ('Sung Mass', '12:10:00', true); -- 18
INSERT INTO services (name, start_time, is_default) VALUES ('Organ Recital', '17:30:00', true); -- 19
INSERT INTO services (name, start_time, is_default) VALUES ('Mass', '18:20:00', true); -- 20
INSERT INTO services (name, start_time, is_default) VALUES ('Solemn Mass', '18:00:00', true); -- 21
INSERT INTO services (name, start_time, is_default) VALUES ('Blessing of Candles & Sung Mass', '12:10:00', false); -- 22
INSERT INTO services (name, start_time, is_default) VALUES ('Blessing of Candles, Procession & Solemn Mass', '18:00:00', false); -- 23
INSERT INTO services (name, start_time, is_default) VALUES ('Sung Mass with Blessing of Throats', '12:10:00', false); -- 24
INSERT INTO services (name, start_time, is_default) VALUES ('Evening Prayer with Blessing of Throats', '18:00:00', false); -- 25
INSERT INTO services (name, start_time, is_default) VALUES ('Stations of the Cross', '18:30:00', true); -- 26
INSERT INTO services (name, start_time, is_default) VALUES ('Sung Requiem Mass', '12:10:00', true); -- 27
INSERT INTO services (name, start_time, is_default) VALUES ('Requiem Mass', '18:20:00', true); -- 28
INSERT INTO services (name, start_time, is_default) VALUES ('Mass', '17:20:00', true); -- 29
INSERT INTO services (name, start_time, is_default) VALUES ('Procession through Times Square & Solemn Mass', '11:00:00', true); -- 30
INSERT INTO services (name, start_time, is_default) VALUES ('Blessing of Candles & Sung Mass', '09:00:00', false); -- 31
INSERT INTO services (name, start_time, is_default) VALUES ('Blessing of Candles, Procession & Solemn Mass', '11:00:00', false); -- 32
INSERT INTO services (name, start_time, is_default) VALUES ('Solemn Mass and the Blessing of the Vault', '18:00:00', false); -- 33
INSERT INTO services (name, start_time, is_default) VALUES ('Sung Mass & Blessing of the Vault', '11:00:00', false); -- 34
INSERT INTO services (name, start_time, is_default) VALUES ('Solemn Mass & Procession to the Creche', '11:00:00', false); -- 35
INSERT INTO services (name, start_time, is_default) VALUES ('Christmas Music', '16:30:00', false); -- 36
INSERT INTO services (name, start_time, is_default) VALUES ('Sung Mass of the Nativity', '17:00:00', false); -- 37
INSERT INTO services (name, start_time, is_default) VALUES ('Christmas Music', '22:30:00', false); -- 38
INSERT INTO services (name, start_time, is_default) VALUES ('Procession & Solemn Mass of the Nativity', '23:00:00', false); -- 39
INSERT INTO services (name, start_time, is_default) VALUES ('Evensong', '15:30:00', false); -- 40
INSERT INTO services (name, start_time, is_default) VALUES ('Choral Music & Carols', '16:30:00', false); -- 41
INSERT INTO services (name, start_time, is_default) VALUES ('Choral Music & Carols', '22:30:00', false); -- 42
INSERT INTO services (name, start_time, is_default) VALUES ('Carols for Choir & Congregation', '16:30:00', false); -- 43
INSERT INTO services (name, start_time, is_default) VALUES ('Sung Mass with Hymns and Carols', '17:00:00', false); -- 44
INSERT INTO services (name, start_time, is_default) VALUES ('Carols for Choir & Congregation', '22:30:00', false); -- 45
INSERT INTO services (name, start_time, is_default) VALUES ('The Great Vigil of Easter', '19:00:00', false); -- 46
INSERT INTO services (name, start_time, is_default) VALUES ('Mass with Hymns', '09:00:00', false); -- 47
INSERT INTO services (name, start_time, is_default) VALUES ('Mass with Hymns', '10:00:00', false); -- 48
INSERT INTO services (name, start_time, is_default) VALUES ('Said Mass with Hymns', '09:00:00', false); -- 49
INSERT INTO services (name, start_time, is_default) VALUES ('Sung Mass', '10:00:00', false); -- 50
INSERT INTO services (name, start_time, is_default) VALUES ('Organ Recital', '16:30:00', true); -- 51
INSERT INTO services (name, start_time, is_default) VALUES ('Solemn Paschal Evensong & Benediction', '17:00:00', true); -- 52
INSERT INTO services (name, start_time, is_default) VALUES ('Mass', '07:00:00', false); -- 53
INSERT INTO services (name, start_time, is_default) VALUES ('Mass', '08:00:00', false); -- 54
INSERT INTO services (name, start_time, is_default) VALUES ('Said Mass', '07:00:00', false); -- 55
INSERT INTO services (name, start_time, is_default) VALUES ('Said Mass', '08:00:00', false); -- 56
INSERT INTO services (name, start_time, is_default) VALUES ('Liturgy of Good Friday', '12:30:00', false); -- 57
INSERT INTO services (name, start_time, is_default) VALUES ('Liturgy of Good Friday', '18:00:00', false); -- 58
INSERT INTO services (name, start_time, is_default) VALUES ('Celebration of the Passion', '12:30:00', false); -- 59
INSERT INTO services (name, start_time, is_default) VALUES ('Celebration of the Passion', '18:00:00', false); -- 60
INSERT INTO services (name, start_time, is_default) VALUES ('The Celebration of the Passion of the Lord', '12:30:00', false); -- 61
INSERT INTO services (name, start_time, is_default) VALUES ('The Celebration of the Passion of the Lord', '18:00:00', false); -- 62
INSERT INTO services (name, start_time, is_default) VALUES ('The Holy Eucharist', '18:00:00', false); -- 63
INSERT INTO services (name, start_time, is_default) VALUES (E'Evening Mass of the Lord\'s Supper', '18:00:00', false); -- 64
INSERT INTO services (name, start_time, is_default) VALUES ('Solemn Mass, Procession through Times Square & Benediction', '11:00:00', false); -- 65
INSERT INTO services (name, start_time, is_default) VALUES ('Blessing of Palms & Mass', '17:20:00', false); -- 66
INSERT INTO services (name, start_time, is_default) VALUES ('Blessing of Palms & Mass', '17:00:00', false); -- 67
INSERT INTO services (name, start_time, is_default) VALUES ('The Liturgy of the Palms & Sung Mass', '17:00:00', false); -- 68
INSERT INTO services (name, start_time, is_default) VALUES ('The Liturgy of the Palms & Said Mass', '09:00:00', false); -- 69
INSERT INTO services (name, start_time, is_default) VALUES ('The Liturgy of the Palms & Sung Mass of the Passion', '09:00:00', false); -- 70
INSERT INTO services (name, start_time, is_default) VALUES ('Blessing of the Palms & Sung Mass', '09:00:00', false); -- 71
INSERT INTO services (name, start_time, is_default) VALUES ('The Liturgy of the Palms, Procession through Times Square & Solemn Mass', '11:00:00', false); -- 72
INSERT INTO services (name, start_time, is_default) VALUES ('The Liturgy of the Palms, Procession through Times Square & Solemn Mass of the Passion', '11:00:00', false); -- 73
INSERT INTO services (name, start_time, is_default) VALUES ('Blessing of the Palms, Procession through Times Square & Solemn Mass', '11:00:00', false); -- 74
INSERT INTO services (name, start_time, is_default) VALUES ('Sung Mass', '18:00:00', true); -- 75
INSERT INTO services (name, start_time, is_default) VALUES ('Said Mass', '18:20:00', true); -- 76
INSERT INTO services (name, start_time, is_default) VALUES ('Mass with Healing Service', '18:20:00', true); -- 77
--
-- Define types of service schedules
--
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Weekday Basic', 'weekday', true, '2009-06-14 00:00:00' AT TIME ZONE 'America/New_York'); -- 1
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Thursday Basic', 'thursday', true, '2009-06-14 00:00:00' AT TIME ZONE 'America/New_York'); -- 2
INSERT INTO schedules (name, code, is_default) VALUES ('Saturday Basic', 'saturday', true); -- 3
INSERT INTO schedules (name, code, is_default) VALUES ('Saturday Vigil Basic', 'vigil', true); -- 4
INSERT INTO schedules (name, code, is_default) VALUES ('Sunday Basic', 'sunday', true); -- 5
INSERT INTO schedules (name, code, is_default) VALUES ('Summer Sunday Basic', 'summer-sunday', true); -- 6
INSERT INTO schedules (name, code, is_default) VALUES ('E&B Only', 'eb-only', true); -- 7
INSERT INTO schedules (name, code, is_default) VALUES ('Evensong Only', 'es-only', true); -- 8
INSERT INTO schedules (name, code, is_default) VALUES ('Evening Prayer Only', 'ep-only', true); -- 9
INSERT INTO schedules (name, code, is_default) VALUES ('Weekday Feast', 'weekday-feast', true); -- 10
INSERT INTO schedules (name, code, is_default) VALUES ('Solemn Weekday Feast', 'solemn-weekday-feast', true); -- 11
INSERT INTO schedules (name, code, is_default) VALUES ('Candlemas', 'candlemas', false); -- 12
INSERT INTO schedules (name, code, is_default) VALUES ('Saint Blase', 'blase', false); -- 13
INSERT INTO schedules (name, code, is_default) VALUES ('Eve of Candlemas on Friday', 'candlemas-eve', false); -- 14
INSERT INTO schedules (name, code, is_default) VALUES ('"Eve of" Solemn Mass on Friday', 'solemn-friday-eve', false); -- 15
INSERT INTO schedules (name, code, is_default) VALUES ('"Eve of" Mass on Friday', 'friday-eve', false); -- 16
INSERT INTO schedules (name, code, is_default) VALUES ('Weekday Basic With Vigil', 'weekday-vigil', true); -- 17
INSERT INTO schedules (name, code, is_default) VALUES ('Thursday Basic With Vigil', 'thursday-vigil', true); -- 18
INSERT INTO schedules (name, code, is_default) VALUES ('Lenten Friday', 'lent-friday', true); -- 19
INSERT INTO schedules (name, code, is_default) VALUES ('Saturday Without Confessions', 'saturday-no-confessions', true); -- 20
INSERT INTO schedules (name, code, is_default) VALUES ('Requiem Weekday', 'requiem-weekday', false); -- 21
INSERT INTO schedules (name, code, is_default) VALUES ('Thursday Feast', 'thursday-feast', true); -- 22
INSERT INTO schedules (name, code, is_default) VALUES ('Saturday Vigil Mass', 'saturday-vigil-mass', true); -- 23
INSERT INTO schedules (name, code, is_default) VALUES ('Evening Prayer and Vigil Mass', 'ep-vigil-mass', false); -- 24
INSERT INTO schedules (name, code, is_default) VALUES ('Summer Sunday With Procession', 'summer-sunday-procession', true); -- 25
INSERT INTO schedules (name, code, is_default) VALUES ('Candlemas Saturday', 'candlemas-saturday', true); -- 26
INSERT INTO schedules (name, code, is_default) VALUES ('Candlemas Sunday', 'candlemas-sunday', true); -- 27
INSERT INTO schedules (name, code, is_default) VALUES ('E&B with Recital', 'eb-recital', true); -- 28
INSERT INTO schedules (name, code, is_default) VALUES ('Saint Blase With Vigil', 'blase-vigil', false); -- 29
INSERT INTO schedules (name, code, is_default) VALUES ('Saint Blase Saturday', 'blase-saturday', false); -- 30
INSERT INTO schedules (name, code, is_default) VALUES ('Requiem Weekday With Vigil', 'requiem-vigil', false); -- 31
INSERT INTO schedules (name, code, is_default) VALUES ('Requiem Saturday', 'requiem-saturday', false); -- 32
INSERT INTO schedules (name, code, is_default) VALUES ('All Souls', 'all-souls', true); -- 33
INSERT INTO schedules (name, code, is_default) VALUES ('All Souls Saturday', 'all-souls-saturday', true); -- 34
INSERT INTO schedules (name, code, is_default) VALUES ('Christmas Day', 'christmas', true); -- 35
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Christmas Eve', 'christmas-eve', true, '2013-01-01 00:00:00' AT TIME ZONE 'America/New_York'); -- 36
INSERT INTO schedules (name, code, is_default, valid_start, valid_end) VALUES ('Christmas Eve', 'christmas-eve', true, '2011-01-01 00:00:00' AT TIME ZONE 'America/New_York', '2012-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 37
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Christmas Eve', 'christmas-eve', true, '2010-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 38
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Wednesday Basic', 'wednesday', true, '2009-06-14 00:00:00' AT TIME ZONE 'America/New_York'); -- 39
INSERT INTO schedules (name, code, is_default) VALUES ('Wednesday Basic With Vigil', 'wednesday-vigil', true); -- 40
INSERT INTO schedules (name, code, is_default) VALUES ('Wednesday Feast', 'wednesday-feast', true); -- 41
INSERT INTO schedules (name, code, is_default) VALUES ('Weekday Basic Without Prayers', 'weekday-no-prayers', true); -- 42
INSERT INTO schedules (name, code, is_default) VALUES ('Thursday Basic Without Prayers', 'thursday-no-prayers', true); -- 43
INSERT INTO schedules (name, code, is_default) VALUES ('Easter Vigil', 'easter-vigil', true); -- 44
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Easter Day', 'easter-day', true, '2014-01-01 00:00:00' AT TIME ZONE 'America/New_York'); -- 45
INSERT INTO schedules (name, code, is_default, valid_start, valid_end) VALUES ('Easter Day', 'easter-day', true, '2008-01-01 00:00:00' AT TIME ZONE 'America/New_York', '2013-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 46
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Easter Day', 'easter-day', true, '2007-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 47
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Ash Wednesday', 'ash-wednesday', true, '2013-01-01 00:00:00' AT TIME ZONE 'America/New_York'); -- 48
INSERT INTO schedules (name, code, is_default, valid_start, valid_end) VALUES ('Ash Wednesday', 'ash-wednesday', true, '2007-01-01 00:00:00' AT TIME ZONE 'America/New_York', '2012-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 49
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Ash Wednesday', 'ash-wednesday', true, '2006-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 50
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Good Friday', 'good-friday', true, '2015-01-01 00:00:00' AT TIME ZONE 'America/New_York'); -- 51
INSERT INTO schedules (name, code, is_default, valid_start, valid_end) VALUES ('Good Friday', 'good-friday', true, '2011-01-01 00:00:00' AT TIME ZONE 'America/New_York', '2014-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 52
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Good Friday', 'good-friday', true, '2010-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 53
INSERT INTO schedules (name, code, is_default) VALUES ('Holy Saturday', 'holy-saturday', true); -- 54
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Maundy Thursday', 'maundy-thursday', true, '2015-01-01 00:00:00' AT TIME ZONE 'America/New_York'); -- 55
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Maundy Thursday', 'maundy-thursday', true, '2014-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 56
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Corpus Christi', 'corpus-christi', true, '2009-01-01 00:00:00' AT TIME ZONE 'America/New_York'); -- 57
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Corpus Christi', 'corpus-christi', true, '2008-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 58
INSERT INTO schedules (name, code, is_default) VALUES ('Holy Name', 'holy-name', true); -- 59
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Palm Sunday Eve', 'palm-sunday-eve', true, '2012-01-01 00:00:00' AT TIME ZONE 'America/New_York'); -- 60
INSERT INTO schedules (name, code, is_default, valid_start, valid_end) VALUES ('Palm Sunday Eve', 'palm-sunday-eve', true, '2008-01-01 00:00:00' AT TIME ZONE 'America/New_York', '2011-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 61
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Palm Sunday Eve', 'palm-sunday-eve', true, '2007-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 62
INSERT INTO schedules (name, code, is_default, valid_start) VALUES ('Palm Sunday', 'palm-sunday', true, '2014-01-01 00:00:00' AT TIME ZONE 'America/New_York'); -- 63
INSERT INTO schedules (name, code, is_default, valid_start, valid_end) VALUES ('Palm Sunday', 'palm-sunday', true, '2012-01-01 00:00:00' AT TIME ZONE 'America/New_York', '2013-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 64
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Palm Sunday', 'palm-sunday', true, '2011-12-31 23:59:59' AT TIME ZONE 'America/New_York'); -- 65
INSERT INTO schedules (name, code, is_default) VALUES ('Sunday With Vigil', 'sunday-with-vigil', true); -- 66
INSERT INTO schedules (name, code, is_default) VALUES ('Summer Sunday With Vigil', 'summer-sunday-with-vigil', true); -- 67
INSERT INTO schedules (name, code, is_default) VALUES ('Sung Mass Vigil', 'sung-mass-vigil', true); -- 68
INSERT INTO schedules (name, code, is_default) VALUES ('Said Mass Vigil', 'said-mass-vigil', true); -- 69
INSERT INTO schedules (name, code, is_default) VALUES ('Thursday Mass Vigil', 'thursday-mass-vigil', false); -- 70
INSERT INTO schedules (name, code, is_default) VALUES ('Mass Vigil', 'mass-vigil', false); -- 71
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Weekday Basic', 'weekday', true, '2009-06-13 23:59:59' AT TIME ZONE 'America/New_York'); -- 72
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Wednesday Basic', 'wednesday', true, '2009-06-13 23:59:59' AT TIME ZONE 'America/New_York'); -- 73
INSERT INTO schedules (name, code, is_default, valid_end) VALUES ('Thursday Basic', 'thursday', true, '2009-06-13 23:59:59' AT TIME ZONE 'America/New_York'); -- 74
--
-- Map services to schedules
--
INSERT INTO schedule_services (schedule_id, service_id) VALUES (1, 1); -- weekday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (1, 2); -- weekday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (1, 3); -- weekday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (1, 5); -- weekday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (2, 1); -- thursday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (2, 2); -- thursday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (2, 4); -- thursday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (2, 5); -- thursday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (3, 6); -- saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (3, 2); -- saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (3, 3); -- saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (3, 7); -- saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (4, 8); -- vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (4, 9); -- vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (5, 10); -- sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (5, 11); -- sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (5, 12); -- sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (5, 13); -- sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (5, 14); -- sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (5, 15); -- sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (6, 1); -- summer-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (6, 11); -- summer-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (6, 12); -- summer-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (6, 13); -- summer-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (6, 8); -- summer-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (7, 16); -- eb-only
INSERT INTO schedule_services (schedule_id, service_id) VALUES (8, 17); -- es-only
INSERT INTO schedule_services (schedule_id, service_id) VALUES (9, 5); -- ep-only
INSERT INTO schedule_services (schedule_id, service_id) VALUES (10, 1); -- weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (10, 2); -- weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (10, 3); -- weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (10, 5); -- weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (10, 20); -- weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (11, 10); -- solemn-weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (11, 2); -- solemn-weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (11, 18); -- solemn-weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (11, 19); -- solemn-weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (11, 21); -- solemn-weekday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (12, 10); -- candlemas
INSERT INTO schedule_services (schedule_id, service_id) VALUES (12, 2); -- candlemas
INSERT INTO schedule_services (schedule_id, service_id) VALUES (12, 22); -- candlemas
INSERT INTO schedule_services (schedule_id, service_id) VALUES (12, 19); -- candlemas
INSERT INTO schedule_services (schedule_id, service_id) VALUES (12, 23); -- candlemas
INSERT INTO schedule_services (schedule_id, service_id) VALUES (13, 1); -- blase
INSERT INTO schedule_services (schedule_id, service_id) VALUES (13, 2); -- blase
INSERT INTO schedule_services (schedule_id, service_id) VALUES (13, 24); -- blase
INSERT INTO schedule_services (schedule_id, service_id) VALUES (13, 25); -- blase
INSERT INTO schedule_services (schedule_id, service_id) VALUES (14, 19); -- candlemas-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (14, 23); -- candlemas-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (15, 19); -- solemn-friday-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (15, 21); -- solemn-friday-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (16, 5); -- friday-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (16, 20); -- friday-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (17, 1); -- weekday-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (17, 2); -- weekday-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (17, 3); -- weekday-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (18, 1); -- thursday-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (18, 2); -- thursday-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (18, 4); -- thursday-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (19, 1); -- lent-friday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (19, 2); -- lent-friday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (19, 3); -- lent-friday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (19, 5); -- lent-friday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (19, 26); -- lent-friday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (20, 2); -- saturday-no-confessions
INSERT INTO schedule_services (schedule_id, service_id) VALUES (20, 3); -- saturday-no-confessions
INSERT INTO schedule_services (schedule_id, service_id) VALUES (21, 1); -- requiem-weekday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (21, 2); -- requiem-weekday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (21, 27); -- requiem-weekday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (21, 5); -- requiem-weekday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (21, 28); -- requiem-weekday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (22, 1); -- thursday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (22, 2); -- thursday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (22, 5); -- thursday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (22, 20); -- thursday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (23, 8); -- saturday-vigil-mass
INSERT INTO schedule_services (schedule_id, service_id) VALUES (23, 29); -- saturday-vigil-mass
INSERT INTO schedule_services (schedule_id, service_id) VALUES (24, 5); -- ep-vigil-mass
INSERT INTO schedule_services (schedule_id, service_id) VALUES (24, 20); -- ep-vigil-mass
INSERT INTO schedule_services (schedule_id, service_id) VALUES (25, 1); -- summer-sunday-procession
INSERT INTO schedule_services (schedule_id, service_id) VALUES (25, 11); -- summer-sunday-procession
INSERT INTO schedule_services (schedule_id, service_id) VALUES (25, 12); -- summer-sunday-procession
INSERT INTO schedule_services (schedule_id, service_id) VALUES (25, 30); -- summer-sunday-procession
INSERT INTO schedule_services (schedule_id, service_id) VALUES (25, 8); -- summer-sunday-procession
INSERT INTO schedule_services (schedule_id, service_id) VALUES (26, 6); -- candlemas-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (26, 2); -- candlemas-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (26, 22); -- candlemas-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (26, 7); -- candlemas-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (27, 10); -- candlemas-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (27, 31); -- candlemas-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (27, 32); -- candlemas-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (27, 15); -- candlemas-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (28, 14); -- eb-recital
INSERT INTO schedule_services (schedule_id, service_id) VALUES (28, 15); -- eb-recital
INSERT INTO schedule_services (schedule_id, service_id) VALUES (29, 1); -- blase-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (29, 2); -- blase-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (29, 24); -- blase-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (30, 6); -- blase-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (30, 2); -- blase-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (30, 22); -- blase-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (30, 7); -- blase-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (31, 1); -- requiem-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (31, 2); -- requiem-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (31, 27); -- requiem-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (32, 6); -- requiem-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (32, 2); -- requiem-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (32, 27); -- requiem-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (32, 7); -- requiem-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (33, 10); -- all-souls
INSERT INTO schedule_services (schedule_id, service_id) VALUES (33, 2); -- all-souls
INSERT INTO schedule_services (schedule_id, service_id) VALUES (33, 18); -- all-souls
INSERT INTO schedule_services (schedule_id, service_id) VALUES (33, 33); -- all-souls
INSERT INTO schedule_services (schedule_id, service_id) VALUES (34, 34); -- all-souls-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (34, 7); -- all-souls-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (35, 35); -- christmas
INSERT INTO schedule_services (schedule_id, service_id) VALUES (36, 36); -- christmas-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (36, 37); -- christmas-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (36, 38); -- christmas-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (36, 39); -- christmas-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (37, 40); -- christmas-eve (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (37, 41); -- christmas-eve (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (37, 37); -- christmas-eve (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (37, 42); -- christmas-eve (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (37, 39); -- christmas-eve (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (38, 43); -- christmas-eve (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (38, 44); -- christmas-eve (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (38, 45); -- christmas-eve (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (38, 39); -- christmas-eve (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (39, 1); -- wednesday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (39, 2); -- wednesday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (39, 18); -- wednesday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (39, 5); -- wednesday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (40, 1); -- wednesday-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (40, 2); -- wednesday-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (40, 18); -- wednesday-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (41, 1); -- wednesday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (41, 2); -- wednesday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (41, 18); -- wednesday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (41, 5); -- wednesday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (41, 20); -- wednesday-feast
INSERT INTO schedule_services (schedule_id, service_id) VALUES (42, 2); -- weekday-no-prayers
INSERT INTO schedule_services (schedule_id, service_id) VALUES (42, 3); -- weekday-no-prayers
INSERT INTO schedule_services (schedule_id, service_id) VALUES (43, 2); -- thursday-no-prayers
INSERT INTO schedule_services (schedule_id, service_id) VALUES (43, 4); -- thursday-no-prayers
INSERT INTO schedule_services (schedule_id, service_id) VALUES (44, 46); -- easter-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (45, 10); -- easter-day
INSERT INTO schedule_services (schedule_id, service_id) VALUES (45, 47); -- easter-day
INSERT INTO schedule_services (schedule_id, service_id) VALUES (45, 48); -- easter-day
INSERT INTO schedule_services (schedule_id, service_id) VALUES (45, 13); -- easter-day
INSERT INTO schedule_services (schedule_id, service_id) VALUES (45, 51); -- easter-day
INSERT INTO schedule_services (schedule_id, service_id) VALUES (45, 52); -- easter-day
INSERT INTO schedule_services (schedule_id, service_id) VALUES (46, 10); -- easter-day (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (46, 11); -- easter-day (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (46, 12); -- easter-day (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (46, 13); -- easter-day (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (46, 51); -- easter-day (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (46, 52); -- easter-day (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (47, 10); -- easter-day (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (47, 49); -- easter-day (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (47, 50); -- easter-day (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (47, 13); -- easter-day (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (47, 52); -- easter-day (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (48, 53); -- ash-wednesday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (48, 54); -- ash-wednesday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (48, 18); -- ash-wednesday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (48, 21); -- ash-wednesday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (49, 53); -- ash-wednesday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (49, 54); -- ash-wednesday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (49, 2); -- ash-wednesday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (49, 18); -- ash-wednesday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (49, 21); -- ash-wednesday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (50, 55); -- ash-wednesday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (50, 56); -- ash-wednesday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (50, 18); -- ash-wednesday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (50, 21); -- ash-wednesday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (51, 10); -- good-friday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (51, 57); -- good-friday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (51, 58); -- good-friday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (52, 10); -- good-friday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (52, 59); -- good-friday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (52, 60); -- good-friday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (53, 10); -- good-friday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (53, 61); -- good-friday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (53, 62); -- good-friday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (54, 10); -- holy-saturday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (55, 10); -- maundy-thursday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (55, 63); -- maundy-thursday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (56, 10); -- maundy-thursday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (56, 64); -- maundy-thursday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (57, 10); -- corpus-christi
INSERT INTO schedule_services (schedule_id, service_id) VALUES (57, 11); -- corpus-christi
INSERT INTO schedule_services (schedule_id, service_id) VALUES (57, 12); -- corpus-christi
INSERT INTO schedule_services (schedule_id, service_id) VALUES (57, 65); -- corpus-christi
INSERT INTO schedule_services (schedule_id, service_id) VALUES (57, 8); -- corpus-christi
INSERT INTO schedule_services (schedule_id, service_id) VALUES (58, 10); -- corpus-christi (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (58, 11); -- corpus-christi (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (58, 12); -- corpus-christi (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (58, 65); -- corpus-christi (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (58, 8); -- corpus-christi (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (58, 29); -- corpus-christi (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (59, 13); -- holy-name
INSERT INTO schedule_services (schedule_id, service_id) VALUES (60, 68); -- palm-sunday-eve
INSERT INTO schedule_services (schedule_id, service_id) VALUES (61, 67); -- palm-sunday-eve (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (62, 8); -- palm-sunday-eve (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (62, 66); -- palm-sunday-eve (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (63, 10); -- palm-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (63, 69); -- palm-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (63, 72); -- palm-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (63, 15); -- palm-sunday
INSERT INTO schedule_services (schedule_id, service_id) VALUES (64, 10); -- palm-sunday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (64, 70); -- palm-sunday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (64, 73); -- palm-sunday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (64, 15); -- palm-sunday (older)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (65, 10); -- palm-sunday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (65, 71); -- palm-sunday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (65, 74); -- palm-sunday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (65, 15); -- palm-sunday (oldest)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (66, 10); -- sunday-with-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (66, 11); -- sunday-with-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (66, 12); -- sunday-with-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (66, 13); -- sunday-with-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (67, 1); -- summer-sunday-with-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (67, 11); -- summer-sunday-with-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (67, 12); -- summer-sunday-with-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (67, 13); -- summer-sunday-with-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (68, 75); -- sung-mass-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (69, 5); -- said-mass-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (69, 76); -- said-mass-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (70, 5); -- thursday-mass-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (70, 77); -- thursday-mass-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (71, 5); -- mass-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (71, 20); -- mass-vigil
INSERT INTO schedule_services (schedule_id, service_id) VALUES (72, 1); -- weekday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (72, 2); -- weekday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (72, 3); -- weekday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (72, 5); -- weekday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (72, 20); -- weekday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (73, 1); -- wednesday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (73, 2); -- wednesday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (73, 18); -- wednesday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (73, 5); -- wednesday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (73, 20); -- wednesday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (74, 1); -- thursday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (74, 2); -- thursday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (74, 4); -- thursday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (74, 5); -- thursday (old)
INSERT INTO schedule_services (schedule_id, service_id) VALUES (74, 77); -- thursday (old)
--
-- Define service patterns for seasons, fixed feasts, and moveable feasts, as
-- they can vary by day of the week
--
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Standard', 'standard',
'weekday', 'weekday-vigil', null,
'weekday', 'weekday-vigil', null,
'wednesday', 'wednesday-vigil', null,
'thursday', 'thursday-vigil', null,
'weekday', 'weekday-vigil', null,
'saturday', 'saturday', 'vigil',
'sunday', 'sunday-with-vigil', null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Standard Summer', 'standard-summer',
'weekday', 'weekday-vigil', null,
'weekday', 'weekday-vigil', null,
'wednesday', 'wednesday-vigil', null,
'thursday', 'thursday-vigil', null,
'weekday', 'weekday-vigil', null,
'saturday', 'saturday', 'vigil',
'summer-sunday', 'summer-sunday-with-vigil', null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Standard Without Confessions', 'standard-no-confessions',
'weekday', 'weekday-vigil', null,
'weekday', 'weekday-vigil', null,
'wednesday', 'wednesday-vigil', null,
'thursday', 'thursday-vigil', null,
'weekday', 'weekday-vigil', null,
'saturday-no-confessions', 'saturday-no-confessions', 'vigil',
'sunday', 'sunday-with-vigil', null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Standard With Stations', 'standard-stations',
'weekday', 'weekday-vigil', null,
'weekday', 'weekday-vigil', null,
'wednesday', 'wednesday-vigil', null,
'thursday', 'thursday-vigil', null,
'lent-friday', 'weekday-vigil', null,
'saturday', 'saturday', 'vigil',
'sunday', 'sunday-with-vigil', null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Major Fixed Feast', 'major-fixed-feast',
'weekday-feast', 'weekday-feast', null,
'weekday-feast', 'weekday-feast', null,
'wednesday-feast', 'wednesday-feast', null,
'thursday-feast', 'thursday-feast', null,
'weekday-feast', 'weekday-feast', null,
'saturday', 'saturday', null,
'sunday', 'sunday-with-vigil', null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Major Fixed Feast Eve', 'major-fixed-feast-eve',
null, null, 'ep-only',
null, null, 'ep-only',
null, null, 'ep-only',
null, null, 'ep-only',
null, null, 'friday-eve',
null, null, 'vigil',
null, null, 'ep-only'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Solemn Fixed Feast', 'solemn-fixed-feast',
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'saturday', 'saturday', null,
'sunday', 'sunday-with-vigil', null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Solemn Fixed Feast Eve', 'solemn-fixed-feast-eve',
null, null, 'es-only',
null, null, 'es-only',
null, null, 'es-only',
null, null, 'es-only',
null, null, 'solemn-friday-eve',
null, null, 'vigil',
null, null, 'es-only'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Candlemas', 'candlemas',
'candlemas', 'candlemas', null,
'candlemas', 'candlemas', null,
'candlemas', 'candlemas', null,
'candlemas', 'candlemas', null,
'candlemas', 'candlemas', null,
'candlemas-saturday', 'candlemas-saturday', null,
'candlemas-sunday', 'candlemas-sunday', null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Candlemas Eve', 'candlemas-eve',
null, null, 'eb-recital',
null, null, 'eb-recital',
null, null, 'eb-recital',
null, null, 'eb-recital',
null, null, 'candlemas-eve',
null, null, 'saturday-vigil-mass',
null, null, 'eb-only'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil,
valid_start
) VALUES ('Assumption', 'assumption',
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'saturday', 'saturday', null,
'summer-sunday', 'summer-sunday-with-vigil', null,
'2009-01-01 00:00:00' AT TIME ZONE 'America/New_York'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil,
valid_start
) VALUES ('Assumption Eve', 'assumption-eve',
null, null, 'ep-only',
null, null, 'ep-only',
null, null, 'ep-only',
null, null, 'ep-only',
null, null, 'solemn-friday-eve',
null, null, 'saturday-vigil-mass',
null, null, 'ep-only',
'2008-01-01 00:00:00' AT TIME ZONE 'America/New_York'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil,
valid_end
) VALUES ('Assumption', 'assumption',
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'solemn-weekday-feast', 'solemn-weekday-feast', null,
'saturday', 'saturday', null,
'summer-sunday-procession', 'summer-sunday-procession', null,
'2009-12-31 23:59:59' AT TIME ZONE 'America/New_York'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil,
valid_end
) VALUES ('Assumption Eve', 'assumption-eve',
null, null, 'ep-vigil-mass',
null, null, 'ep-vigil-mass',
null, null, 'ep-vigil-mass',
null, null, 'es-only',
null, null, 'ep-vigil-mass',
null, null, 'ep-vigil-mass',
null, null, 'ep-vigil-mass',
'2008-12-31 23:59:59' AT TIME ZONE 'America/New_York'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('St. Blase', 'blase',
'blase', 'blase-vigil', null,
'blase', 'blase-vigil', null,
'blase', 'blase-vigil', null,
'blase', 'blase-vigil', null,
'blase', 'blase-vigil', null,
'blase-saturday', 'blase-saturday', null,
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Parish Requiem', 'parish-requiem',
'requiem-weekday', 'requiem-vigil', null,
'requiem-weekday', 'requiem-vigil', null,
'requiem-weekday', 'requiem-vigil', null,
'requiem-weekday', 'requiem-vigil', null,
'requiem-weekday', 'requiem-vigil', null,
'requiem-saturday', 'requiem-saturday', null,
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('All Souls', 'all-souls',
'all-souls', null, null,
'all-souls', null, null,
'all-souls', null, null,
'all-souls', null, null,
'all-souls', null, null,
'all-souls-saturday', null, null,
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Christmas', 'christmas',
'christmas', 'christmas', null,
'christmas', 'christmas', null,
'christmas', 'christmas', null,
'christmas', 'christmas', null,
'christmas', 'christmas', null,
'christmas', 'christmas', null,
'christmas', 'christmas', null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Christmas Eve', 'christmas-eve',
null, null, 'christmas-eve',
null, null, 'christmas-eve',
null, null, 'christmas-eve',
null, null, 'christmas-eve',
null, null, 'christmas-eve',
null, null, 'christmas-eve',
null, null, 'christmas-eve'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Without Prayers', 'without-prayers',
'weekday-no-prayers', 'weekday-no-prayers', null,
'weekday-no-prayers', 'weekday-no-prayers', null,
'weekday-no-prayers', 'weekday-no-prayers', null,
'thursday-no-prayers', 'thursday-no-prayers', null,
'weekday-no-prayers', 'weekday-no-prayers', null,
'saturday-no-confessions', 'saturday-no-confessions', null,
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Easter Eve', 'easter-eve',
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, 'easter-vigil',
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Easter Day', 'easter',
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null,
'easter-day', null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Ash Wednesday', 'ash-wednesday',
null, null, null,
null, null, null,
'ash-wednesday', null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Good Friday', 'good-friday',
null, null, null,
null, null, null,
null, null, null,
null, null, null,
'good-friday', null, null,
null, null, null,
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Holy Saturday', 'holy-saturday',
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, 'holy-saturday', null,
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Maundy Thursday', 'maundy-thursday',
null, null, null,
null, null, null,
null, null, null,
'maundy-thursday', null, null,
null, null, null,
null, null, null,
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('<NAME>', 'corpus-christi',
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null,
'corpus-christi', null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Holy Name', 'holy-name',
'holy-name', 'holy-name', null,
'holy-name', 'holy-name', null,
'holy-name', 'holy-name', null,
'holy-name', 'holy-name', null,
'holy-name', 'holy-name', null,
'holy-name', 'holy-name', null,
'holy-name', 'holy-name', null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Palm Sunday Eve', 'palm-sunday-eve',
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, 'palm-sunday-eve',
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Palm Sunday', 'palm-sunday',
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null,
null, null, null,
'palm-sunday', null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Sung Mass Eve-of Vigil', 'sung-mass-eve-vigil',
null, null, 'sung-mass-vigil',
null, null, 'sung-mass-vigil',
null, null, 'sung-mass-vigil',
null, null, 'sung-mass-vigil',
null, null, 'sung-mass-vigil',
null, null, 'sung-mass-vigil',
null, null, null
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil,
valid_start
) VALUES ('Said Mass Eve-of Vigil', 'said-mass-eve-vigil',
null, null, 'said-mass-vigil',
null, null, 'said-mass-vigil',
null, null, 'said-mass-vigil',
null, null, 'said-mass-vigil',
null, null, 'said-mass-vigil',
null, null, 'said-mass-vigil',
null, null, null,
'2008-01-01 00:00:00' AT TIME ZONE 'America/New_York'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil,
valid_end
) VALUES ('Said Mass Eve-of Vigil', 'said-mass-eve-vigil',
null, null, 'said-mass-vigil',
null, null, 'said-mass-vigil',
null, null, 'said-mass-vigil',
null, null, 'thursday-mass-vigil',
null, null, 'said-mass-vigil',
null, null, 'said-mass-vigil',
null, null, null,
'2007-12-31 23:59:59' AT TIME ZONE 'America/New_York'
);
INSERT INTO service_patterns (name, code,
schedule_code_mon, schedule_code_mon_with_vigil, schedule_code_mon_vigil,
schedule_code_tue, schedule_code_tue_with_vigil, schedule_code_tue_vigil,
schedule_code_wed, schedule_code_wed_with_vigil, schedule_code_wed_vigil,
schedule_code_thu, schedule_code_thu_with_vigil, schedule_code_thu_vigil,
schedule_code_fri, schedule_code_fri_with_vigil, schedule_code_fri_vigil,
schedule_code_sat, schedule_code_sat_with_vigil, schedule_code_sat_vigil,
schedule_code_sun, schedule_code_sun_with_vigil, schedule_code_sun_vigil
) VALUES ('Mass Eve-of Vigil', 'mass-eve-vigil',
null, null, 'mass-vigil',
null, null, 'mass-vigil',
null, null, 'mass-vigil',
null, null, 'thursday-mass-vigil',
null, null, 'mass-vigil',
null, null, 'mass-vigil',
null, null, null
);
-- rambler down
DELETE FROM service_patterns;
ALTER SEQUENCE service_patterns_pattern_id_seq RESTART;
DELETE FROM schedule_services;
DELETE FROM schedules;
ALTER SEQUENCE schedules_schedule_id_seq RESTART;
DELETE FROM services;
ALTER SEQUENCE services_service_id_seq RESTART;
-- todo: old summer sunday schedule
-- todo: Blase with old weekday schedule
<file_sep>/database/migrations/20170108223353_stmarys_floating_feasts.sql
-- rambler up
INSERT INTO floating_feasts (name, code, otype_id, placement_index,
algorithm, color,
valid_start)
VALUES ('Of Our Lady', 'of-our-lady', 4, 1,
'of_our_lady', 'white',
'2012-12-01 00:00:00' AT TIME ZONE 'America/New_York');
INSERT INTO floating_feasts (name, code, otype_id, placement_index,
algorithm, color,
valid_end)
VALUES ('Of Our Lady', 'of-our-lady', 4, 1,
'of_our_lady_old', 'white',
'2012-11-30 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO floating_feasts (name, code, otype_id, placement_index, algorithm, color)
VALUES ('The First Book of Common Prayer, 1549', 'first-bcp', 4, 1, 'first_bcp', 'white');
INSERT INTO floating_feasts (name, code, otype_id, placement_index, algorithm, color,
valid_start)
VALUES ('Parish Requiem', 'parish-requiem', 4, 1, 'parish_requiem', 'black',
'2016-01-01 00:00:00' AT TIME ZONE 'America/New_York');
INSERT INTO floating_feasts (name, code, otype_id, placement_index, algorithm, color,
valid_start, valid_end)
VALUES ('Parish Requiem', 'parish-requiem', 6, 1, 'parish_requiem_5_skip', 'black',
'2015-01-01 00:00:00' AT TIME ZONE 'America/New_York',
'2015-12-31 23:59:59' AT TIME ZONE 'America/New_York');
INSERT INTO floating_feasts (name, code, otype_id, placement_index, algorithm, color,
valid_end)
VALUES ('Parish Requiem', 'parish-requiem', 6, 1, 'parish_requiem_4_skip', 'black',
'2014-12-31 23:59:59' AT TIME ZONE 'America/New_York');
-- rambler down
TRUNCATE TABLE floating_feasts RESTART IDENTITY;
<file_sep>/database/migrations/20160810133200_schema_seasons.sql
-- rambler up
--
-- This table defines the liturgical seasons that set the base color, name,
-- notes, and services for each part of the year
--
CREATE TABLE seasons (
season_id serial,
name text NOT NULL,
code text NOT NULL,
color text NOT NULL,
sort_order integer NOT NULL,
calculate_from text NOT NULL,
algorithm text NOT NULL,
distance integer,
weekday_precedence integer NOT NULL,
has_last_sunday boolean NOT NULL DEFAULT FALSE,
counting_index integer NOT NULL DEFAULT 1,
continue_counting boolean NOT NULL,
schedule_pattern text NOT NULL,
name_pattern_mon text NOT NULL,
name_pattern_tue text NOT NULL,
name_pattern_wed text NOT NULL,
name_pattern_thu text NOT NULL,
name_pattern_fri text NOT NULL,
name_pattern_sat text NOT NULL,
name_pattern_sat_vigil text NOT NULL,
name_pattern_sun text NOT NULL,
default_note_mon text,
default_note_tue text,
default_note_wed text,
default_note_thu text,
default_note_fri text,
default_note_sat text,
default_note_sun text,
valid_start timestamp with time zone NULL,
valid_end timestamp with time zone NULL,
CONSTRAINT liturigal_seasons_pk PRIMARY KEY (season_id),
CONSTRAINT liturigal_seasons_calc_from CHECK (calculate_from IN ('easter', 'christmas', NULL))
);
-- rambler down
DROP TABLE seasons;
<file_sep>/front/lib/errorHandler.js
var winston = require('winston');
var standard = require('./standard.js');
/**
* Handles errors the default way
*
* To create a failure response, reject with a BasicFailure or a string
* To create an error response, reject with a BasicError or any object with
* a `message` element (or throw a javascript error)
* If you reject with anything else, you'll get an error with a message
* "Unknown error"
*
* @param mixed err the error
* @param expressRequest req the request
* @param expressResponse res the response
* @param callback next the next callback
*/
const errorHandler = function (err, req, res, next) {
var json = { status: 'error', message: 'Unknown error' };
var status = 500;
var logto = null;
var logmeta = null;
if (err instanceof standard.BasicFailure || err instanceof standard.BasicError) {
json['message'] = err.message;
if (err.code) {
json['code'] = err.code;
}
}
if (err instanceof standard.BasicFailure) {
status = 200;
json['status'] = 'fail';
if (err.doLog) {
logto = 'failure';
logmeta = { code: err.code, context: err.context };
}
} else if (err instanceof standard.BasicError) {
status = 501;
logto = 'error';
logmeta = { code: err.code, context: err.context };
} else if (typeof err == 'object' && 'message' in err) {
json['message'] = err.message
logto = 'error';
logmeta = {};
} else if (typeof err == 'string') {
status = 200;
json['status'] = 'fail';
json['message'] = err;
} else {
logto = 'error';
logmeta = { 'raw': err };
}
if ('stack' in err) {
console.error(err.stack);
if (logto) {
logmeta['stack'] = err.stack;
}
}
if (logto) {
var logger = winston.loggers.get(logto);
logger.log('error', json['message'], logmeta);
}
res.status(status).json(json);
}
module.exports = errorHandler;
<file_sep>/bin/calendar_builder/algorithms.py
import datetime
from dateutil import relativedelta
class boundary_algorithms:
"""Algorithms for calculating season boundaries"""
@staticmethod
def days_before(holiday_date, number):
"""Finds a number of days before the given holiday"""
return holiday_date - datetime.timedelta(days=number)
@staticmethod
def days_after(holiday_date, number):
"""Finds a number of days after the given holiday"""
return holiday_date + datetime.timedelta(days=number)
@staticmethod
def weeks_before(holiday_date, number):
"""Finds a number of weeks before the given holiday"""
return holiday_date - datetime.timedelta(weeks=number)
@staticmethod
def weeks_after(holiday_date, number):
"""Finds a number of weeks after the given holiday"""
return holiday_date + datetime.timedelta(weeks=number)
@staticmethod
def tuesdays_before(holiday_date, number):
"""Finds the nth Tuesday before the holiday"""
return holiday_date - datetime.timedelta(days=holiday_date.weekday()) + datetime.timedelta(days=1, weeks=-1*number)
@staticmethod
def saturdays_before(holiday_date, number):
"""Finds the nth Saturday before the holiday"""
return holiday_date - datetime.timedelta(days=holiday_date.weekday()) + datetime.timedelta(days=5, weeks=-1*number)
class feast_algorithms:
"""Algorithms for calculating moveable feasts"""
@staticmethod
def days_before(holiday_date, number):
"""Finds a number of days before the given holiday"""
return holiday_date - datetime.timedelta(days=number)
@staticmethod
def days_after(holiday_date, number):
"""Finds a number of days after the given holiday"""
return holiday_date + datetime.timedelta(days=number)
@staticmethod
def wednesdays_before(holiday_date, number):
"""Finds the nth Wednesday before the holiday"""
return holiday_date - datetime.timedelta(days=holiday_date.weekday()) + datetime.timedelta(days=2, weeks=-1*number)
@staticmethod
def thursdays_after(holiday_date, number):
"""Finds the nth Thursday after the holiday"""
return helpers.nth_weekdays_after(holiday_date, 3, number)
@staticmethod
def sundays_before(holiday_date, number):
"""Finds the nth Sunday before the holiday"""
return holiday_date - datetime.timedelta(days=holiday_date.weekday()) + datetime.timedelta(days=6, weeks=-1*number)
@staticmethod
def sundays_after(holiday_date, number):
"""Finds the nth Sunday after the holiday"""
return helpers.nth_weekdays_after(holiday_date, 6, number)
@staticmethod
def nth_thursday(holiday_date, number):
"""Finds the nth Thursday of the calc-from day's month"""
return helpers.nth_weekday_of_month(holiday_date, 3, number)
@staticmethod
def exact(holiday_date, number):
"""Exactly on the given holiday"""
return holiday_date
class holiday_algorithms:
"""Algorithms for calculating federal holidays"""
@staticmethod
def nth_monday(calc_from, number):
"""Finds the nth Monday of the calc-from day's month"""
return helpers.nth_weekday_of_month(calc_from, 0, number)
@staticmethod
def last_monday(calc_from, number):
"""Finds the last Monday of the calc-from day's month"""
return calc_from + relativedelta.relativedelta(day=31, weekday=relativedelta.MO(-1))
@staticmethod
def nth_thursday(calc_from, number):
"""Finds the nth Thursday of the calc-from day's month"""
return helpers.nth_weekday_of_month(calc_from, 3, number)
@staticmethod
def closest_weekday(calc_from, number):
"""Finds the closest weekday to the calc-from day"""
if calc_from.weekday() == 6:
return calc_from + datetime.timedelta(days=1)
if calc_from.weekday() == 5:
return calc_from - datetime.timedelta(days=1)
return calc_from
@staticmethod
def not_sunday(calc_from, number):
"""Finds the closest non-Sunday to the calc-from day"""
if calc_from.weekday() == 6:
return calc_from + datetime.timedelta(days=1)
return calc_from
@staticmethod
def exact(calc_from, number):
"""Exactly on the given calc-from day"""
return calc_from
class helpers:
"""Helper methods for calculating dates"""
@staticmethod
def nth_weekday_of_month(calc_from, target_weekday, number):
"""Finds the nth target weekday of the month (e.g., 3rd Monday in January)"""
start = datetime.date(calc_from.year, calc_from.month, 1)
days_ahead = target_weekday - start.weekday()
if days_ahead < 0:
days_ahead += 7
return start + datetime.timedelta(days=days_ahead, weeks=(number - 1))
@staticmethod
def nth_weekdays_after(start, target_weekday, number):
"""Finds the nth target weekday after the given day"""
days_ahead = target_weekday - start.weekday()
if days_ahead <= 0:
days_ahead += 7
return start + datetime.timedelta(days=days_ahead, weeks=(number - 1))
|
14e0d9e25c1119999d77ee925490aa1b24768a2a
|
[
"SQL",
"Ruby",
"JavaScript",
"Markdown",
"Python"
] | 52
|
Python
|
rsterbin/liturgicalendar
|
9ac1d779cf9bedaaeeb00eea83deff98445d0af2
|
89bfe633f4608d0c40caf707732416c7e270bf67
|
refs/heads/master
|
<repo_name>maui-project/index<file_sep>/app/main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
//#include <QQuickStyle>
#include <QIcon>
#include <QCommandLineParser>
#include <QFileInfo>
#include <QDebug>
#include <index.h>
#include "inx.h"
#ifdef Q_OS_ANDROID
#include <QGuiApplication>
#include <QIcon>
#else
#include <QApplication>
#endif
#ifdef STATIC_KIRIGAMI
#include "./../3rdparty/kirigami/src/kirigamiplugin.h"
#endif
#ifdef STATIC_MAUIKIT
#include "./../mauikit/src/mauikit.h"
#include "tagging.h"
#include "fm.h"
#else
#include "MauiKit/tagging.h"
#include "MauiKit/fm.h"
#endif
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#ifdef Q_OS_ANDROID
QGuiApplication app(argc, argv);
#else
QApplication app(argc, argv);
#endif
app.setApplicationName(INX::app);
app.setApplicationVersion(INX::version);
app.setApplicationDisplayName(INX::app);
app.setWindowIcon(QIcon(":/index.png"));
QCommandLineParser parser;
parser.setApplicationDescription(INX::description);
const QCommandLineOption versionOption = parser.addVersionOption();
parser.addOption(versionOption);
parser.process(app);
const QStringList args = parser.positionalArguments();
QStringList paths;
if(!args.isEmpty())
paths = args;
Index index;
auto tag = Tagging::getInstance(INX::app, INX::version, "org.kde.index");
QQmlApplicationEngine engine;
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, [&]()
{
if(!paths.isEmpty())
index.openPaths(paths);
});
auto context = engine.rootContext();
context->setContextProperty("inx", &index);
context->setContextProperty("tag", tag);
#ifdef STATIC_KIRIGAMI
KirigamiPlugin::getInstance().registerTypes();
#endif
#ifdef STATIC_MAUIKIT
MauiKit::getInstance().registerTypes();
#endif
#ifdef Q_OS_ANDROID
QIcon::setThemeName("Luv");
#else
QStringList importPathList = engine.importPathList();
importPathList.prepend(QCoreApplication::applicationDirPath() + "/kde/qmltermwidget");
engine.setImportPathList(importPathList);
// QQuickStyle::setStyle("material");
#endif
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
<file_sep>/app/Index.js
function bookmarkFolders(urls)
{
}
function showPreviews()
{
browser.previews = !browser.previews
Maui.FM.setDirConf(browser.currentPath+"/.directory", "MAUIFM", "ShowThumbnail", browser.previews)
}
function showHiddenFiles()
{
var state = Maui.FM.dirConf(browser.currentPath+"/.directory").hidden
Maui.FM.setDirConf(browser.currentPath+"/.directory", "Settings", "HiddenFilesShown", !state)
browser.refresh()
}
function createFolder()
{
newFolderDialog.open()
}
function createFile()
{
newFileDialog.open()
}
function bookmarkFolder()
{
browser.bookmarkFolder([browser.currentPath])
}
<file_sep>/kde/notify.cpp
/***
Pix Copyright (C) 2018 <NAME>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "notify.h"
Notify::Notify(QObject *parent) : QObject(parent)
{}
Notify::~Notify()
{
qDebug()<<"DELETING KNOTIFY";
}
void Notify::notify(const QString &title, const QString &body)
{
// notification->setComponentName(QStringLiteral("Babe"));
auto notification = new KNotification(QStringLiteral("Notify"),KNotification::CloseOnTimeout, this);
connect(notification, &KNotification::closed, notification, &KNotification::deleteLater);
notification->setTitle(QStringLiteral("%1").arg(title));
notification->setText(QStringLiteral("%1").arg(body));
notification->sendEvent();
}
<file_sep>/kde/kde.cpp
/***
Pix Copyright (C) 2018 <NAME>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include "kde.h"
#include <KService>
#include <KMimeTypeTrader>
#include <KToolInvocation>
#include <KLocalizedString>
#include <QDebug>
#include <KRun>
#include <QFileInfo>
#include <KService>
#include <KServiceGroup>
#include <QDebug>
#include "../app/inx.h"
KDE::KDE(QObject *parent) : QObject(parent) {}
QVariantList KDE::getApps()
{
QVariantList res;
KServiceGroup::Ptr group = KServiceGroup::root();
bool sortByGenericName = false;
KServiceGroup::List list = group->entries(true /* sorted */, true /* excludeNoDisplay */,
true /* allowSeparators */, sortByGenericName /* sortByGenericName */);
for (KServiceGroup::List::ConstIterator it = list.constBegin(); it != list.constEnd(); it++)
{
const KSycocaEntry::Ptr p = (*it);
if (p->isType(KST_KServiceGroup))
{
KServiceGroup::Ptr s(static_cast<KServiceGroup*>(p.data()));
if (!s->noDisplay() && s->childCount() > 0)
{
qDebug()<< "Getting app"<<s->icon();
res << QVariantMap
{
{INX::MODEL_NAME[INX::MODEL_KEY::ICON], s->icon()},
{INX::MODEL_NAME[INX::MODEL_KEY::LABEL], s->name()},
{INX::MODEL_NAME[INX::MODEL_KEY::PATH], INX::CUSTOMPATH_PATH[INX::CUSTOMPATH::APPS]+"/"+s->entryPath()}
};
}
}
}
return res;
}
QVariantList KDE::getApps(const QString &groupStr)
{
if(groupStr.isEmpty()) return getApps();
QVariantList res;
// const KServiceGroup::Ptr group(static_cast<KServiceGroup*>(groupStr));
auto group = new KServiceGroup(groupStr);
KServiceGroup::List list = group->entries(true /* sorted */,
true /* excludeNoDisplay */,
false /* allowSeparators */,
true /* sortByGenericName */);
for (KServiceGroup::List::ConstIterator it = list.constBegin(); it != list.constEnd(); it++)
{
const KSycocaEntry::Ptr p = (*it);
if (p->isType(KST_KService))
{
const KService::Ptr s(static_cast<KService*>(p.data()));
if (s->noDisplay())
continue;
res << QVariantMap {
{INX::MODEL_NAME[INX::MODEL_KEY::ICON], s->icon()},
{INX::MODEL_NAME[INX::MODEL_KEY::LABEL], s->name()},
{INX::MODEL_NAME[INX::MODEL_KEY::PATH], s->entryPath()}
};
} else if (p->isType(KST_KServiceSeparator))
{
qDebug()<< "separator wtf";
} else if (p->isType(KST_KServiceGroup))
{
const KServiceGroup::Ptr s(static_cast<KServiceGroup*>(p.data()));
if (s->childCount() == 0)
continue;
res << QVariantMap {
{INX::MODEL_NAME[INX::MODEL_KEY::ICON], s->icon()},
{INX::MODEL_NAME[INX::MODEL_KEY::LABEL], s->name()},
{INX::MODEL_NAME[INX::MODEL_KEY::PATH], INX::CUSTOMPATH_PATH[INX::CUSTOMPATH::APPS]+"/"+s->entryPath()}
};
}
}
return res;
}
void KDE::launchApp(const QString &app)
{
KService service(app);
KRun::runApplication(service,{}, nullptr);
}
<file_sep>/app/inx.h
#ifndef INX_H
#define INX_H
#include <QString>
#include <QDebug>
#include <QStandardPaths>
#include <QFileInfo>
#include <QImage>
#include <QTime>
#include <QSettings>
#include <QDirIterator>
#include <QVariantList>
#include <QMimeType>
#include <QMimeData>
#include <QMimeDatabase>
#if defined(Q_OS_ANDROID)
#include "../mauikit/src/android/mauiandroid.h"
#endif
namespace INX
{
Q_NAMESPACE
inline bool isMobile()
{
#if defined(Q_OS_ANDROID)
return true;
#elif defined(Q_OS_LINUX)
return false;
#elif defined(Q_OS_WIN32)
return false;
#elif defined(Q_OS_WIN64)
return false;
#elif defined(Q_OS_MACOS)
return false;
#elif defined(Q_OS_IOS)
return true;
#elif defined(Q_OS_HAIKU)
return false;
#endif
}
inline bool isAndroid()
{
#if defined(Q_OS_ANDROID)
return true;
#elif defined(Q_OS_LINUX)
return false;
#elif defined(Q_OS_WIN32)
return false;
#elif defined(Q_OS_WIN64)
return false;
#elif defined(Q_OS_MACOS)
return false;
#elif defined(Q_OS_IOS)
return false;
#elif defined(Q_OS_HAIKU)
return false;
#endif
}
#if defined(Q_OS_ANDROID)
const QString PicturesPath = PATHS::PicturesPath;
const QString DownloadsPath = PATHS::DownloadsPath;
const QString DocumentsPath = PATHS::DocumentsPath;
const QString HomePath = PATHS::HomePath;
const QString MusicPath = PATHS::MusicPath;
const QString VideosPath = PATHS::VideosPath;
const QStringList defaultPaths =
{
HomePath,
DocumentsPath,
PicturesPath,
MusicPath,
VideosPath,
DownloadsPath
};
const QMap<QString, QString> folderIcon
{
{PicturesPath, "folder-pictures"},
{DownloadsPath, "folder-download"},
{DocumentsPath, "folder-documents"},
{HomePath, "user-home"},
{MusicPath, "folder-music"},
{VideosPath, "folder-videos"},
};
#else
const QString PicturesPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
const QString DownloadsPath = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
const QString DocumentsPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
const QString HomePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
const QString MusicPath = QStandardPaths::writableLocation(QStandardPaths::MusicLocation);
const QString VideosPath = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
const QString DesktopPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
const QString AppsPath = QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation);
const QString RootPath = "/";
const QStringList defaultPaths =
{
HomePath,
DesktopPath,
DocumentsPath,
PicturesPath,
MusicPath,
VideosPath,
DownloadsPath
};
const QMap<QString, QString> folderIcon
{
{PicturesPath, "folder-pictures"},
{DownloadsPath, "folder-download"},
{DocumentsPath, "folder-documents"},
{HomePath, "user-home"},
{MusicPath, "folder-music"},
{VideosPath, "folder-videos"},
{DesktopPath, "user-desktop"},
{AppsPath, "system-run"},
{RootPath, "folder-root"}
};
#endif
inline QString getIconName(const QString &path)
{
if(QFileInfo(path).isDir())
{
if(folderIcon.contains(path))
return folderIcon[path];
else return "folder";
}else
{
QMimeDatabase mime;
auto type = mime.mimeTypeForFile(path);
return isAndroid() ? type.genericIconName() : type.iconName();
}
return "unkown";
}
enum class MODEL_KEY : uint_fast8_t
{
ICON,
LABEL,
PATH,
TYPE,
GROUP,
OWNER,
SUFFIX,
NAME,
DATE,
MODIFIED,
MIME,
TAGS,
PERMISSIONS
};
static const QMap<MODEL_KEY, QString> MODEL_NAME =
{
{MODEL_KEY::ICON, "icon"},
{MODEL_KEY::LABEL, "label"},
{MODEL_KEY::PATH, "path"},
{MODEL_KEY::TYPE, "type"},
{MODEL_KEY::GROUP, "group"},
{MODEL_KEY::OWNER, "owner"},
{MODEL_KEY::SUFFIX, "suffix"},
{MODEL_KEY::NAME, "name"},
{MODEL_KEY::DATE, "date"},
{MODEL_KEY::MODIFIED, "modified"},
{MODEL_KEY::MIME, "mime"},
{MODEL_KEY::TAGS, "tags"},
{MODEL_KEY::PERMISSIONS, "permissions"}
};
enum class CUSTOMPATH : uint_fast8_t
{
APPS,
TAGS,
TRASH
};
static const QMap<CUSTOMPATH, QString> CUSTOMPATH_PATH =
{
{CUSTOMPATH::APPS, "#apps"},
{CUSTOMPATH::TAGS, "#tags"},
{CUSTOMPATH::TRASH, "#trash"}
};
static const QMap<CUSTOMPATH, QString> CUSTOMPATH_NAME =
{
{CUSTOMPATH::APPS, "Apps"},
{CUSTOMPATH::TAGS, "Tags"},
{CUSTOMPATH::TRASH, "Trash"}
};
enum class PATHTYPE_KEY : uint_fast8_t
{
PLACES,
DRIVES,
BOOKMARKS,
TAGS
};
static const QMap<PATHTYPE_KEY, QString> PATHTYPE_NAME =
{
{PATHTYPE_KEY::PLACES, "Places"},
{PATHTYPE_KEY::DRIVES, "Drives"},
{PATHTYPE_KEY::BOOKMARKS, "Bookmarks"},
{PATHTYPE_KEY::TAGS, "Tags"}
};
const QString SettingPath = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)+"/pix/";
const QString CachePath = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation)+"/pix/";
const QString NotifyDir = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
const QString app = "Index";
const QString version = "0.1.0";
const QString description = "File manager";
inline void saveSettings(const QString &key, const QVariant &value, const QString &group)
{
QSettings setting(INX::app,INX::app);
setting.beginGroup(group);
setting.setValue(key,value);
setting.endGroup();
}
inline QVariant loadSettings(const QString &key, const QString &group, const QVariant &defaultValue)
{
QVariant variant;
QSettings setting(INX::app,INX::app);
setting.beginGroup(group);
variant = setting.value(key,defaultValue);
setting.endGroup();
return variant;
}
}
#endif // INX_H
<file_sep>/app/index.h
#ifndef INDEX_H
#define INDEX_H
#include <QObject>
#include <QVariantList>
#include <QStringList>
#include <QFileSystemWatcher>
#ifdef STATIC_KIRIGAMI
#include "fm.h"
#else
#include "MauiKit/fm.h"
#endif
class Index : public FM
{
Q_OBJECT
public:
explicit Index(QObject *parent = nullptr);
Q_INVOKABLE static QVariantList getCustomPathContent(const QString &path);
Q_INVOKABLE static bool isCustom(const QString &path);
Q_INVOKABLE static bool isApp(const QString &path);
Q_INVOKABLE static bool openFile(const QString &path);
Q_INVOKABLE void openPaths(const QStringList &paths);
Q_INVOKABLE static QVariantList getCustomPaths();
Q_INVOKABLE static void saveSettings(const QString &key, const QVariant &value, const QString &group);
Q_INVOKABLE static QVariant loadSettings(const QString &key, const QString &group, const QVariant &defaultValue);
Q_INVOKABLE static QVariantMap getDirInfo(const QString &path, const QString &type);
Q_INVOKABLE static QVariantMap getFileInfo(const QString &path);
/*KDE*/
Q_INVOKABLE static void runApplication(const QString &exec, const QString &url);
signals:
void openPath(QStringList paths);
public slots:
};
#endif // INDEX_H
<file_sep>/README.md
# Index
Maui File manager
Index is a file manager that works on desktops, Android and Plasma Mobile.
Index lets you browse your system files and applications and preview your music, text, image and video files and share them with external applications.
## Build
### Dependencies
#### Qt core deps:
QT += qml, quick, sql
#### KF5 deps:
QT += KService KNotifications KNotifications KI18n KIOCore KIOFileWidgets KIOWidgets KNTLM
#### Submodules
##### MauiKit:
https://github.com/maui-project/mauikit.git
##### qmltermwidget:
https://github.com/Swordfish90/qmltermwidget
### Compilation
After all the dependencies are met you can throw the following command lines to build Index and test it
git clone https://github.com/maui-project/index --recursive
cd index && mkdir build && cd build
qmake ..
make
A binary should be created and be ready to use.
## Contribute
If you like the Maui project or Index and would like to get involve ther are several ways you can join us.
- UI/UX design for desktop and mobile platforms
- Plasma, KIO and Baloo integration
- Deployment on other platforms like Mac OSX, IOS, Windows.. etc.
- Work on data analysis and on the tagging system
And also whatever else you would like to see on a convergent file manager.
You can get in touch with me by opening an issue or email me:
<EMAIL>
## Screenshots




<file_sep>/kde/kde.h
/***
Pix Copyright (C) 2018 <NAME>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef KDE_H
#define KDE_H
#include <QObject>
#include <QVariantList>
#include <KFileItem>
class KDE : public QObject
{
Q_OBJECT
public:
explicit KDE(QObject *parent = nullptr);
static QVariantList getApps();
static QVariantList getApps(const QString &groupStr);
static void launchApp(const QString &app);
signals:
public slots:
};
#endif // KDE_H
<file_sep>/kde/notify.h
/***
Pix Copyright (C) 2018 <NAME>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef NOTIFY_H
#define NOTIFY_H
#include <QObject>
#include <QByteArray>
#include <klocalizedstring.h>
#include <knotifyconfig.h>
#include <knotification.h>
#include <QStandardPaths>
#include <QPixmap>
#include <QDebug>
#include <QMap>
class Notify : public QObject
{
Q_OBJECT
public:
explicit Notify(QObject *parent = nullptr);
~Notify();
void notify(const QString &title, const QString &body);
private:
};
#endif // NOTIFY_H
<file_sep>/app/index.cpp
#include "index.h"
#include <QFileInfo>
#include <QMimeType>
#include <QDirIterator>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>
#include "inx.h"
#if (defined (Q_OS_LINUX) && !defined (Q_OS_ANDROID))
#include "../kde/notify.h"
#include "../kde/kde.h"
#endif
Index::Index(QObject *parent) : FM(parent)
{
}
QVariantList Index::getCustomPathContent(const QString &path)
{
QVariantList res;
#if (defined (Q_OS_LINUX) && !defined (Q_OS_ANDROID))
if(path.startsWith(INX::CUSTOMPATH_PATH[INX::CUSTOMPATH::APPS]+"/"))
return KDE::getApps(QString(path).replace(INX::CUSTOMPATH_PATH[INX::CUSTOMPATH::APPS]+"/",""));
else
return KDE::getApps();
#endif
return res;
}
bool Index::isCustom(const QString &path)
{
return path.startsWith("#");
}
bool Index::isApp(const QString &path)
{
return /*QFileInfo(path).isExecutable() ||*/ path.endsWith(".desktop");
}
bool Index::openFile(const QString &path)
{
return QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}
void Index::openPaths(const QStringList &paths)
{
QStringList urls;
for(auto path : paths)
{
QFileInfo file(path);
if(file.isDir())
urls << path;
else
urls << file.dir().absolutePath();
}
emit this->openPath(urls);
}
QVariantList Index::getCustomPaths()
{
#ifdef Q_OS_ANDROID
return QVariantList();
#endif
return QVariantList
{
QVariantMap
{
{INX::MODEL_NAME[INX::MODEL_KEY::ICON], "system-run"},
{INX::MODEL_NAME[INX::MODEL_KEY::LABEL], INX::CUSTOMPATH_NAME[INX::CUSTOMPATH::APPS]},
{INX::MODEL_NAME[INX::MODEL_KEY::PATH], INX::CUSTOMPATH_PATH[INX::CUSTOMPATH::APPS]},
{INX::MODEL_NAME[INX::MODEL_KEY::TYPE], INX::PATHTYPE_NAME[INX::PATHTYPE_KEY::PLACES]}
}
};
}
QVariantMap Index::getDirInfo(const QString &path, const QString &type)
{
QFileInfo file (path);
QVariantMap data =
{
{INX::MODEL_NAME[INX::MODEL_KEY::ICON], INX::getIconName(path)},
{INX::MODEL_NAME[INX::MODEL_KEY::LABEL], file.baseName()},
{INX::MODEL_NAME[INX::MODEL_KEY::PATH], path},
{INX::MODEL_NAME[INX::MODEL_KEY::TYPE], type}
};
return data;
}
QVariantMap Index::getFileInfo(const QString &path)
{
QFileInfo file(path);
if(!file.exists()) return QVariantMap();
auto mime = FMH::getMime(path);
QVariantMap res =
{
{INX::MODEL_NAME[INX::MODEL_KEY::GROUP], file.group()},
{INX::MODEL_NAME[INX::MODEL_KEY::OWNER], file.owner()},
{INX::MODEL_NAME[INX::MODEL_KEY::SUFFIX], file.completeSuffix()},
{INX::MODEL_NAME[INX::MODEL_KEY::LABEL], file.completeBaseName()},
{INX::MODEL_NAME[INX::MODEL_KEY::NAME], file.fileName()},
{INX::MODEL_NAME[INX::MODEL_KEY::DATE], file.birthTime().toString()},
{INX::MODEL_NAME[INX::MODEL_KEY::MODIFIED], file.lastModified().toString()},
{INX::MODEL_NAME[INX::MODEL_KEY::MIME], mime },
{INX::MODEL_NAME[INX::MODEL_KEY::ICON], INX::getIconName(path)}
};
return res;
}
void Index::runApplication(const QString &exec, const QString &url)
{
#if (defined (Q_OS_LINUX) && !defined (Q_OS_ANDROID))
return KDE::launchApp(exec);
#endif
}
void Index::saveSettings(const QString &key, const QVariant &value, const QString &group)
{
INX::saveSettings(key, value, group);
}
QVariant Index::loadSettings(const QString &key, const QString &group, const QVariant &defaultValue)
{
return INX::loadSettings(key, group, defaultValue);
}
|
671966cac32d5cbb7487555e6b9decb40dcdd4f2
|
[
"JavaScript",
"C++",
"Markdown"
] | 10
|
C++
|
maui-project/index
|
0b83407e0193459702465042afc1c790b2d510dc
|
9dad1d72e2497b483001f7c2c97eacb59163141f
|
refs/heads/main
|
<file_sep>import React from 'react';
import "./Contact.css";
const Contact = () => {
return (
<div>
<div className="container">
<div className="row">
<div className="col-sm-12" id="contact-details">
<h2 id="contact">Contact Me</h2>
<h2><i className="fa fa-envelope"></i></h2>
<h3><EMAIL></h3>
<h2><i className="fa fa-phone"></i></h2>
<h3>9522004354</h3>
</div>
</div>
</div>
</div>
);
};
export default Contact;<file_sep># Navdeep-Portfolio
## The Repository
The link to the website repository: [Website Repo link](https://github.com/NavdeepDP/navdeeppuri-portfolio)
The site is published at [Published Website link]( https://navdeepdp.github.io/navdeeppuri-portfolio/)
## Development Environment
Code is developed in VS code Studio using React.
## Website Structure
Website consists of three pages:
- Contact
- Portfolio

- About
These pages are accessible through the Navbar links.
## Installation
- Code is developed using VS Code studio.
- Code is available at the GITHub repository link: [Website Repo link](https://github.com/NavdeepDP/navdeeppuri-portfolio)
- Get the code code in your local machine by using the clone option in the repository link.
- Click "Code" and copy the Clone with SSH key link.
- In Git bash, go to the appropriate directory and get the code using "git clone" command.
- Go to the project folder in VS Code studio and run 'npm install'
- To lauch the webpage run 'npm start'
## References
- [w3schools.com](https://www.w3schools.com/)
- [Bootstrap documentation: https://getbootstrap.com/](https://getbootstrap.com/)
- React documentation
<file_sep>import React from "react";
import "./Project.css";
const Project = (props) => {
return (
<div className="container">
<div className="row">
<div className="col-sm-6 text-left">
<h3>{props.title}</h3>
<p>{props.tech}</p>
<div id="project-links">
<a
href={props.website}
className="btn btn-secondary btn-sm "
target="_blank"
role="button"
aria-disabled="true"
>
View Website
</a>
<a
href={props.source}
className="btn btn-secondary btn-sm "
target="_blank"
role="button"
aria-disabled="true"
>
View Source
</a>
</div>
</div>
<div className="col-sm-6">
<div>
<img
id="project-pic"
src={props.image}
alt="project pic"
className="img-responsive"
/>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<hr id="hr" />
</div>
</div>
</div>
);
};
export default Project;
<file_sep>import React from "react";
import "./Home.css";
import pdf from "./Navdeep_Resume.pdf";
import image from "./ProfilePicture.jpg";
import Footer from "../../components/Footer/Footer";
const Home = () => {
return (
<div>
<div className="container" id="page-content">
<div className="row" id="top-row"></div>
<div className="row">
<div class="col-sm-12">
<h3>
Hi! My name is Navdeep. I am Software Developer living in Cumming,
Georgia.
</h3>
<div class="text-center" id="image">
<img id="profile-pic" src={image} class="" alt="profile pic" />
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12" id="about">
<h4>About: </h4>
<div>
<p>
My name is <NAME>. I Live in Cumming, Georgia with my
family. I did my schooling and graduation in India. Moved to
Minnesota, United States in 2015 and in Georgia since 2018. I
worked as a Software Engineer for around 10 years. Have
experience working in embedded C, C++, ADA and C#. I love to
code and debug. As a Software Engineer, I worked in product
companies throughout the 10 year career, with end to end
Software Development Life Cycle experience involving requirement
analysis, software architecture and design, coding, unit/system
testing and maintenance/support.
</p>
</div>
</div>
</div>
<div className="row">
<div class="col-sm-12">
<h4 id="work">Work Experience: </h4>
<div id="leftAlign">
<a
href="https://www.linkedin.com/in/navdeep-puri/"
class="btn btn-secondary "
target="_blank"
role="button"
aria-disabled="true"
><i className="fa fa-linkedin-square"> </i>
LinkedIn
</a>
<a
href={pdf}
class="btn btn-secondary"
target="_blank"
role="button"
aria-disabled="true"
><i className="fa fa-file"></i>
Resume
</a>
<a
href="https://github.com/NavdeepDP"
class="btn btn-secondary"
target="_blank"
role="button"
aria-disabled="true"
> <i className="fa fa-github-square"></i>
GitHub
</a>
</div>
</div>
</div>
</div>
</div>
);
};
export default Home;
<file_sep>import { BrowserRouter as Router, Switch, Route} from "react-router-dom";
import Home from "./containers/Home/Home";
import Contact from "./containers/Contact/Contact";
import Portfolio from "./containers/Portfolio/Portfolio";
import Navbar from "./components/Navbar/Navbar"
import Footer from "./components/Footer/Footer"
import "./App.css";
function App() {
return (
<div className="App">
<div id="page-container">
<div id="content-wrap">
<Router>
<Navbar/>
<Switch>
<Route exact path="/contact" component={Contact} />
<Route exact path="/portfolio" component={Portfolio} />
<Route path="/" component={Home} />
</Switch>
</Router>
</div>
<Footer />
</div>
</div>
);
}
export default App;
<file_sep>import React from "react";
import "./Footer.css";
const Footer = () => {
return (
<div>
<footer id="sticky-footer" class="py-4 text-white-50">
<div class="container text-center" id="footer-div">
<small>Copyright © 2020</small>
</div>
</footer>
</div>
);
};
export default Footer;
<file_sep>import React from "react";
import Project from "../../components/Project/Project";
import Footer from "../../components/Footer/Footer";
import "./Portfolio.css";
import StraightSets from "./../images/straightSets-1.gif";
import WeatherDashboard from "./../images/Weather-Dashboard.gif";
import EmployeeDirectory from "./../images/emp-dir.gif";
import CodeQuiz from "./../images/Coding-Quiz.gif";
import TeamGenerator from "./../images/team.png";
import Adventure from "./../images/FindYourAdventure1.png";
import GoogleBookSearch from "./../images/google-book-search.gif";
const Portfolio = () => {
return (
// <div id="page-container">
// <div id="content-wrap">
<div className="container">
<div className="row">
<div class="col-sm-12">
<div className="text-center">
<h2 id="projects-title">Projects</h2>
</div>
<Project
title="Straight Sets"
image={StraightSets}
tech="MySQL, Node, Express, Handlebars and Sequelize ORM"
source="https://github.com/NavdeepDP/Straight-Sets"
website="https://straight-sets.herokuapp.com/"
/>
<Project
title="Weather Dashboard"
image={WeatherDashboard}
tech="OpenWeatherMap API services, JQuery, Moment.js"
source="https://github.com/NavdeepDP/Weather-Dashboard"
website="https://navdeepdp.github.io/Weather-Dashboard/"
/>
<Project
title="Google Book Search"
image={GoogleBookSearch}
tech="React, MongoDB, Nodejs, Express, Google Books API"
source="https://github.com/NavdeepDP/google-book-search"
website="https://tranquil-scrubland-79336.herokuapp.com/"
/>
<Project
title="Employee Directory"
image={EmployeeDirectory}
tech="React, axios, gh-pages, moment"
source="https://github.com/NavdeepDP/employee-directory-app"
website="https://navdeepdp.github.io/employee-directory-app/"
/>
<Project
title="Code Quiz"
image={CodeQuiz}
tech="JavaScript"
source="https://github.com/NavdeepDP/Code-Quiz"
website="https://navdeepdp.github.io/Code-Quiz/"
/>
{/* <Project
title="Team Generator"
image={TeamGenerator}
tech="inquirer, Nodejs"
source="https://github.com/NavdeepDP/Engineering-Team-Generator"
website=""
/> */}
<Project
title="Find Your Adventure"
image={Adventure}
tech="National Park Service API , JQuery, Bootstrap"
source="https://github.com/NavdeepDP/Find-Your-Adventure"
website="https://navdeepdp.github.io/Find-Your-Adventure/"
/>
</div>
</div>
</div>
// </div>
// <Footer />
// </div>
);
};
export default Portfolio;
|
a7f5d204a796848361c2105b7d01570241738c79
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
NavdeepDP/navdeeppuri-portfolio
|
5e1d9615defa27ed922e409c50b02dd04ff3b5a8
|
3789e08101a8c56e325e8c3603f40f6b1679d62a
|
refs/heads/master
|
<file_sep><div class="destaque grid-fluid clear">
<div class="grid-12 spaceBox">
<div id="blog" class="grid-fluid">
<h2>ÚLTIMAS DO BLOG</h2>
<?php foreach ($posts as $post): ?>
<div class="grid-4 spaceBox">
<a href="<?php print base_url(); ?>blog/<?php print $post['url']; ?>"><img src="<?php print base_url(); ?>uploads/blog/<?php print $post['imagem']; ?>" alt="<?php print $post['titulo']; ?>"></a>
<a href="<?php print base_url(); ?>blog/<?php print $post['url']; ?>" class="link"><h3><?php print $post['titulo']; ?></h3></a>
<p><?php print word_limiter($post['subtitulo'], 14); ?></p>
<p><a href="<?php print base_url(); ?>blog/<?php print $post['url']; ?>" class="link"><i class="fa fa-external-link-square"></i> Leia na Íntegra</a></p>
</div>
<?php endforeach; ?>
</div>
</div>
</div><file_sep><div class="grid-fluid clear">
<div class="grid-6 spaceBox">
<h2>CADASTRE SUA QUADRA NO JOGUE LÁ. É MUITO RÁPIDO!</h2>
<form>
<div class="grid-12 spaceBox">
<label for="name">Nome do Responsável</label><br>
<input type="text" class="grid-12 formInput" id="name" placeholder="Insira sue nome" pattern="[A-Za-z]{3}" required>
</div>
<div class="grid-6 spaceBox">
<label for="email">Email do Responsável</label><br>
<input type="email" class="grid-12 formInput" id="email" placeholder="<EMAIL>" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required>
</div>
<div class="grid-6 spaceBox">
<label for="telefone">Telefone do Responsável</label>
<input type="tel" class="grid-12 formInput" id="telefone" placeholder="00 00000 0000" pattern="[000][0-9]{8,9}" required>
</div>
<div class="grid-12 spaceBox">
<label for="name">Nome do Local</label><br>
<input type="text" class="grid-12 formInput" id="name" placeholder="Insira sue nome" pattern="[A-Za-z]{3}" required>
</div>
<div class="grid-6 spaceBox">
<label for="endereco">Endereço do Local</label><br>
<input type="text" class="grid-12 formInput" id="endereco" placeholder="Ex: <NAME> do Nascimento - Nº10" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required>
</div>
<div class="grid-6 spaceBox">
<label for="bairro">Bairro</label>
<input type="text" class="grid-12 formInput" id="telefone" placeholder="Ex: <NAME>" pattern="[A-Za-z]{3}" required>
</div>
<div class="grid-6 spaceBox">
<label for="cidade">Cidade</label>
<input type="text" class="grid-12 formInput" id="telefone" placeholder="Ex: São Paulo" pattern="[A-Za-z]{3}" required>
</div>
<div class="grid-6 spaceBox">
<label for="estado">Estado</label>
<select name="estado" class="grid-12 formInput" title="Selecione o Estado" tabindex="10" required>
<option selected label="Selecione o Estado"></option>
<option value="ac">Acre</option>
<option value="al">Alagoas</option>
<option value="am">Amazonas</option>
<option value="ap">Amapá</option>
<option value="ba">Bahia</option>
<option value="ce">Ceará</option>
<option value="df">Distrito Federal</option>
<option value="es">Espírito Santo</option>
<option value="go">Goiás</option>
<option value="ma">Maranhão</option>
<option value="mt">Mato Grosso</option>
<option value="ms">Mato Grosso do Sul</option>
<option value="mg">Minas Gerais</option>
<option value="pa">Pará</option>
<option value="pb">Paraíba</option>
<option value="pr">Paraná</option>
<option value="pe">Pernambuco</option>
<option value="pi">Piauí</option>
<option value="rj">Rio de Janeiro</option>
<option value="rn">Rio Grande do Norte</option>
<option value="ro">Rondônia</option>
<option value="rs">Rio Grande do Sul</option>
<option value="rr">Roraima</option>
<option value="sc">Santa Catarina</option>
<option value="se">Sergipe</option>
<option value="sp">São Paulo</option>
<option value="to">Tocantins</option>
</select>
</div>
<div class="grid-6 spaceBox">
<label for="telefone">Telefone p/ locação 1</label>
<input type="tel" class="grid-12 formInput" id="telefone" placeholder="00 00000 0000" pattern="[000][0-9]{8,9}" required>
</div>
<div class="grid-6 spaceBox">
<label for="telefone">Telefone p/ locação 2</label>
<input type="tel" class="grid-12 formInput" id="telefone" placeholder="00 00000 0000" pattern="[000][0-9]{8,9}" required>
</div>
<div class="grid-6 spaceBox">
<label for="telefone">Quantidade de Quadras</label>
<select name="" class="grid-12 formInput" title="Selecione a quantidade de quadras..." tabindex="10" required>
<option selected label="Selecione a quantidade de quadras..."></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
</div>
<div class="grid-6 spaceBox">
<label for="telefone">Enviar Foto</label>
<input name="" class="btn btn-yellow upload" type="file">
</div>
<div class="grid-12 spaceBox">
<label id="mensagem">Faça uma descrição básica do local</label><br>
<textarea type="text" size="10" class="grid-12 formInput" id="mensagem" placeholder="Sua mensagem aqui ..." pattern="[A-Za-z]{3}" required></textarea>
</div>
<div class="grid-12 spaceBox">
<button type="submit" class="grid-12 btn btn-green"><i class="fa fa-send"></i> ENVIAR MENSAGEM</button>
</div>
</form>
</div>
<div class="grid-6"></div>
</div>
<div class="clear"></div>
<?php $this->ultimos_posts->exibe_posts(); ?> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ultimos_posts {
public function exibe_posts(){
$CI =& get_instance();
$CI->load->model('Model_blog');
$data['posts'] = $CI->Model_blog->lista(3);
$CI->load->view('template/ultimas_blog', $data);
}
}<file_sep><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Untitled Document</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<!-- Owl Carousel Assets -->
<link href="css/owl.carousel.css" rel="stylesheet">
<link href="css/owl.theme.css" rel="stylesheet">
<script src="js/modernizr.custom.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/responsivemobilemenu.js"></script>
</head>
<body>
<div id="main">
<div id="header">
<div id="nav">
<nav class="rmm">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="como-funciona.html">Como Funciona</a></li>
<li><a href="cadastre-local.html">Cadastre seu Local</a></li>
<li><a href="blog.html">Blog</a></li>
</ul>
</nav>
</div>
<div class="center-align">
<div id="logo">
<h1><a href="index.html"><img src="images/logo-final-branco.png" alt="<NAME>"></a></h1>
</div>
</div>
<div id="topo-chamada">
<div class="chamada-home"><h1>Encontrar o local e agendar seu futebol nunca foi tão fácil!</h1></div>
<div id="top-search">
<div class="filtro">
<div class="campo-1">
<input name="" type="text" placeholder="Encontre o local ideal por CIDADE ou NOME" required>
</div>
<div class="campo-2">
Horário
<select name="">
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
</select>
Até
<select name="">
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
<option>00:00</option>
</select>
</div>
<div class="campo-3">
<button class="button btgreen">ENCONTRAR</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="center-column" class="center-align">
<p class="images-blog-site-right"><img src="images/fotos.jpg"></p>
<h2>COMO FUNCIONA</h2>
<p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
<p>Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Interagi no mé, cursus quis, vehicula ac nisi. Aenean vel dui dui. Nullam leo erat, aliquet quis tempus a, posuere ut mi. Ut scelerisque neque et turpis posuere pulvinar pellentesque nibh ullamcorper. Pharetra in mattis molestie, volutpat elementum justo. Aenean ut ante turpis. Pellentesque laoreet mé vel lectus scelerisque interdum cursus velit auctor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ac mauris lectus, non scelerisque augue. Aenean justo massa.</p>
<h3> - PASSO 1</h3>
<p>Casamentiss faiz malandris se pirulitá, Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer Ispecialista im mé intende tudis nuam golada, vinho, uiski, carirí, rum da jamaikis, só num pode ser mijis. Adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
<h3> - PASSO 2</h3>
<p>Cevadis im ampola pa arma uma pindureta. Nam varius eleifend orci, sed viverra nisl condimentum ut. Donec eget justis enim. Atirei o pau no gatis. Viva Forevis aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Copo furadis é disculpa de babadis, arcu quam euismod magna, bibendum egestas augue arcu ut est. Delegadis gente finis. In sit amet mattis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis. Pellentesque viverra accumsan ipsum elementum gravidis.</p>
<h3> - PASSO 3</h3>
<p>Forevis aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Copo furadis é disculpa de babadis, arcu quam euismod magna, bibendum egestas augue arcu ut est. Etiam ultricies tincidunt ligula, sed accumsan sapien mollis et. Delegadis gente finis. In sit amet mattis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis. Pellentesque viverra accumsan ipsum elementum gravida. Quisque vitae metus id massa tincidunt iaculis sed sed purus. Vestibulum viverra lobortis faucibus. Vestibulum et turpis.</p>
</div>
<div id="blog">
<div class="center-align">
<h2>ÚLTIMAS DO BLOG</h2>
<div class="ultimas-blog left">
<h3><a href="">Líderes de mercado, Adidas e Nike inovam e lançam chuteiras 'cano alto' para a Copa</a></h3>
<p><a href="">As duas principais marcas de artigos esportivos ao redor do mundo lançaram...</a></p>
<p><a href="" class="button-small btgreen2">Leia na Íntegra</a></p>
</div>
<div class="ultimas-blog center">
<h3><a href="">Líderes de mercado, Adidas e Nike inovam e lançam chuteiras 'cano alto' para a Copa</a></h3>
<p><a href="">As duas principais marcas de artigos esportivos ao redor do mundo lançaram...</a></p>
<p><a href="" class="button-small btgreen2">Leia na Íntegra</a></p>
</div>
<div class="ultimas-blog right">
<h3><a href="">Líderes de mercado, Adidas e Nike inovam e lançam chuteiras 'cano alto' para a Copa</a></h3>
<p><a href="">As duas principais marcas de artigos esportivos ao redor do mundo lançaram...</a></p>
<p><a href="" class="button-small btgreen2">Leia na Íntegra</a></p>
</div>
</div>
</div>
<div id="publicidade">
<div class="center-align">
<h2>PUBLICIDADE</h2>
<div class="publicidade left"><a href=""><img src="images/banner.jpg" alt="Banner"></a></div>
<div class="publicidade center"><a href=""><img src="images/banner.jpg" alt="Banner"></a></div>
<div class="publicidade right"><a href=""><img src="images/banner.jpg" alt="Banner"></a></div>
</div>
</div>
<div id="footer">
<div class="center-align">
<div class="box-facebook left">
<strong>CADASTRE JÁ SUA QUADRA, GINÁSIO OU CAMPO NO JOGUE LÁ E VEJA SEU NEGÓCIO FAZER UMA BELA DUPLA COM O SUCESSO!</strong>
</div>
<div class="box-joguela right">
<img src="images/logo-final-branco.png" alt="<NAME>"><br>
<strong>Jogue Lá</strong><br>
É uma plataforma web pra quem deseja encontrar o local ideal para a prática do futebol de forma rápida e sem complicações. Chega de correr de site em site a procura de contato ou horário disponível. Faça sua busca e agite sua galera!
</div>
<div class="box-footer left">
<EMAIL>
</div>
<div class="box-footer center">
www.joguela.com | facebook.com/joguela
</div>
<div class="box-footer right">
Fone: 019 00000-0000
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Model_unidades');
}
public function index() {
$data['main_content'] = "home";
$data['ouro'] = $this->Model_unidades->ouro();
$data['destaques'] = $this->Model_unidades->lista(array('destaque' => 1, 'ouro' => 0), array(), 12);
$data['quadras'] = $this->Model_unidades->lista(array('destaque' => 0, 'ouro' => 0), array(), 24);
$this->load->view('template/default', $data);
}
}
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed');
class contato extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Model_contato');
}
public function index() {
$data['main_content'] = "contato";
$this->load->view('template/default', $data);
}
public function enviar(){
$dados = $this->input->post();
$this->Model_contato->gravar($dados);
redirect('contato');
}
}
<file_sep><?php
class Model_blog extends CI_Model {
function __construct() {
parent::__construct();
}
function inserir($dados = array()) {
$data = array(
'titulo' => $dados['titulo'],
'subtitulo' => $dados['subtitulo'],
'fonte' => $dados['fonte'],
'texto' => $dados['texto'],
'video' => $dados['video'],
'imagem' => $dados['imagem']
);
$this->db->insert('blog', $data);
}
function remover($blogID = 0) {
$this->db->delete('blog', array('blogID' => $blogID));
}
function alterar($dados = array(), $blogID = 0) {
$data = array(
'titulo' => $dados['titulo'],
'subtitulo' => $dados['subtitulo'],
'fonte' => $dados['fonte'],
'texto' => $dados['texto'],
'video' => $dados['video'],
'imagem' => $dados['imagem']
);
$this->db->where('blogID', $blogID);
$this->db->update('blog', $data);
}
function lista($limite = 3) {
$this->db->from('blog');
$this->db->limit($limite);
$query = $this->db->get();
return $query->result_array();
}
function item($url = '') {
$this->db->from('blog');
$this->db->where('url', $url);
$query = $this->db->get();
return $query->row_array();
}
}
<file_sep><?php
class Model_logs extends CI_Model {
function __construct() {
parent::__construct();
}
function inserir($chave) {
$data = array(
'chave' => $chave
);
$this->db->insert('log_buscas', $data);
}
}
<file_sep><div class="destaque grid-fluid clear">
<div class="grid-12 spaceBox">
<figure class="images-blog-site-center"><img src="<?php print base_url(); ?>uploads/blog/<?php print $post['imagem']; ?>"></figure>
<h2><?php print $post['titulo']; ?></h2>
<h3><?php print $post['subtitulo']; ?></h3>
<p><?php print $post['texto']; ?></p>
<h3>FONTE: <?php print $post['fonte']; ?></h3>
<div class="fb-comments" data-href="<?php print base_url(); ?>blog/post/<?php print $this->utils->url_amigavel($post['titulo']); ?>/<?php print $post['blogID']; ?>" data-numposts="5" data-colorscheme="light"></div>
</div>
</div>
<?php $this->ultimos_posts->exibe_posts(); ?>
<file_sep><?php
class Model_contato extends CI_Model {
function gravar($dados) {
$validos = array(
'nome' => '',
'email' => '',
'telefone' => '',
'assunto' => '',
'mensagem' => ''
);
$dadosInserir = array_intersect_key($dados, $validos);
$this->db->insert('contato', $dadosInserir);
return TRUE;
}
function listar() {
$this->db->from('contato');
$this->db->order_by('contatoID', 'DESC');
$query = $this->db->get();
return $query->result_array();
}
}
<file_sep><div class="destaque grid-fluid clear">
<div class="grid-12 spaceBox">
<h2><?php print $quadra['unidade']; ?></h2>
<p><?php print $quadra['endereco']; ?> - <?php print (isset($quadra['bairro']) ? $quadra['bairro'] . ' - ' : '' ); ?> <?php print $quadra['nome']; ?></p>
<p><?php print $quadra['telefone']; ?><?php print (isset($quadra['telefone2']) ? ' - ' . $quadra['telefone2'] : '' ); ?></p>
<hr>
<?php if(isset($quadra['estacionamento']) && $quadra['estacionamento'] == 1) : ?>
<div class="icon estacionamento" title="Estacionamento"></div>
<?php endif; ?>
<?php if(isset($quadra['lanchonete']) && $quadra['lanchonete'] == 1) : ?>
<div class="icon lanchonete" title="Lanchonete"></div>
<?php endif; ?>
<?php if(isset($quadra['vestiarios']) && $quadra['vestiarios'] == 1) : ?>
<div class="icon vestiario" title="Vestiários"></div>
<?php endif; ?>
<div class="icon icon-none"></div>
<?php if(isset($quadra['quadras'])) : ?>
<?php for ($i=1; $i<= $quadra['quadras']; $i++ ) : ?>
<div class="icon quadras" title="Número de Quadras"></div>
<?php endfor; ?>
<div class="icon icon-none"></div>
<?php endif; ?>
<?php if(isset($quadra['churrasqueira']) && $quadra['churrasqueira'] == 1) : ?>
<div class="icon churrasqueira" title="Churrasqueira"></div>
<?php endif; ?>
<?php if(isset($quadra['escolinha']) && $quadra['escolinha'] == 1) : ?>
<div class="icon escolinha" title="Escolinha de Futebol"></div>
<?php endif; ?>
<?php if(isset($quadra['tv']) && $quadra['tv'] == 1) : ?>
<div class="icon tv" title="TV à Cabo"></div>
<?php endif; ?>
<?php if(isset($quadra['wifi']) && $quadra['wifi'] == 1) : ?>
<div class="icon wifi" title="Wifi"></div>
<?php endif; ?>
<div class="icon icon-none"></div>
<br />
<hr>
<p><?php print (isset($quadra['descricao']) ? $quadra['descricao'] : ''); ?></p>
<?php if(isset($quadra['classificacao'])) : ?>
<?php for ($i=1; $i<= $quadra['classificacao']; $i++ ) : ?>
<div class="icon rating"></div>
<?php endfor; ?>
<?php endif; ?>
</div>
</div>
<div class="clear"></div>
<?php $this->ultimos_posts->exibe_posts(); ?> <file_sep><div id="publicidade">
<div class="center-align">
<h2>PUBLICIDADE</h2>
<div class="publicidade left"><a target="_blank" href="https://delavada.wordpress.com/"><img src="<?php print base_url(); ?>uploads/publicidade/delavada.jpg" alt="De Lavada"></a></div>
<div class="publicidade center"><a href="<?php print base_url(); ?>cadastre-seu-local"><img src="<?php print base_url(); ?>uploads/publicidade/joguela.jpg" alt="J<NAME> - Aluguel de Quadras Society"></a></div>
<div class="publicidade right"><a target="_blank" href="https://socio-palmeiras.futebolcard.com/"><img src="<?php print base_url(); ?>uploads/publicidade/avante.jpg" alt="Banner"></a></div>
</div>
</div><file_sep>/* var msnry = new Masonry( '#container', {
itemSelector: '.item'
});
*/
$(window).load(function(){
var $container = $('#container');
// initialize
$container.masonry({
itemSelector: '.item'
});
});
var container = document.querySelector('#container');
$(document).ready(function(){
/*==============================
Flippet Small Sliding Menu
===============================*/
function fliSmallMenu(){
var $block = $('.menu[data-type="small-menu-slide"]'),
$menu = $block.find('ul'),
$icon = $block.find('.trigger-menu'),
$bars = $icon.find('span');
$icon.on('click',function(e){
e.preventDefault();
if($menu.hasClass('active')){
$menu.removeClass('active');
$bars.removeClass('close');
}
else{
$menu.addClass('active');
$bars.addClass('close');
}
});
}
//call the menu function
fliSmallMenu();
});
<file_sep><div class="grid-fluid clear">
<div class="grid-6 spaceBox">
<h2>PREENCHA O FORMULÁRIO E ENVIE SUA MENSAGEM.</h2>
<form method="POST" action="<?php print base_url(); ?>contato/enviar">
<div class="grid-12">
<label for="name">Nome</label><br>
<input type="text" name="nome" class="grid-12 formInput" id="name" placeholder="Insira sue nome" required>
</div>
<div class="grid-6">
<label for="email">Email</label><br>
<input type="email" name="email" class="grid-12 formInput" id="email" placeholder="<EMAIL>" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required>
</div>
<div class="grid-6">
<label for="telefone">Telefone</label>
<input type="tel" name="telefone" class="grid-12 formInput" id="telefone" placeholder="00 00000 0000" required>
</div>
<div class="grid-12">
<label id="assunto">Assunto</label><br>
<input type="text" name="assunto" class="grid-12 formInput" id="assunto" placeholder="Insira o assunto da mensagem" required>
</div>
<div class="grid-12">
<label id="mensagem">Mensagem</label><br>
<textarea type="text" name="mensagem" size="10" class="grid-12 formInput" id="mensagem" placeholder="Sua mensagem aqui ..." required></textarea>
</div>
<div class="grid-12">
<button type="submit" class="grid-12 btn btn-green"><i class="fa fa-send"></i> ENVIAR MENSAGEM</button>
</div>
</form>
</div>
<div class="grid-6"></div>
</div>
<div class="clear"></div>
<?php $this->ultimos_posts->exibe_posts(); ?> <file_sep><div id="footer" class="grid-12">
<div class="grid-fluid center">
<div class="grid-4 spaceBox"><address><EMAIL></address></div>
<div class="grid-4 spaceBox">Fone: (19) 9 9515-9037 | www.joguela.com</div>
<div class="grid-4 spaceBox"><NAME> | Copyright © 2015 - Todos os direitos reservados</div>
</div>
</div>
</div>
<!-- SCRIPTS -->
<script type="text/javascript" src="<?php print base_url(); ?>assets/js/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="<?php print base_url(); ?>assets/js/index.js"></script>
<script type="text/javascript" src="<?php print base_url(); ?>assets/js/masonry.pkgd.js"></script>
<script type="text/javascript" src="<?php print base_url(); ?>assets/js/chart.js"></script>
<script>
var doughnutData = [{value: 90, color: "#91cb7f"}, {value: 10, color: "#d1eec8"}];
var doughnut2Data = [{value: 80, color: "#91cb7f"}, {value: 20, color: "#d1eec8"}];
var doughnut3Data = [{value: 85, color: "#91cb7f"}, {value: 15, color: "#d1eec8"}]
var doughnut4Data = [{value: 70, color: "#91cb7f"}, {value: 30, color: "#d1eec8"}]
new Chart(document.getElementById("doughnut").getContext("2d")).Doughnut(doughnutData);
new Chart(document.getElementById("doughnut2").getContext("2d")).Doughnut(doughnut2Data);
new Chart(document.getElementById("doughnut3").getContext("2d")).Doughnut(doughnut3Data);
new Chart(document.getElementById("doughnut4").getContext("2d")).Doughnut(doughnut4Data);
</script>
</body>
</html><file_sep><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title><NAME> - Encontrar o local e agendar seu futebol nunca foi tão fácil!</title>
<meta NAME="DESCRIPTION" CONTENT="Quer encontrar quadras society de forma rápida e sem complicação? Chega de correr de site em site a procura de contato ou horário disponível.">
<meta NAME="ABSTRACT" CONTENT="Encontrar o local e agendar seu futebol nunca foi tão fácil!">
<meta NAME="KEYWORDS" CONTENT="Quadras Society, Aluguel de Quadra Society, Quadras Online, Guia de Quadras, Futebol Society, Futebol de 7, Locação de Quadras, Quadras Society em Campinas, Campos Society, Alugar Quadra Society, Aluguel de Campo Society, Campo Sintético">
<meta name="robots" content="index, follow">
<meta NAME="RATING" CONTENT="general">
<meta NAME="DISTRIBUTION" CONTENT="global">
<meta NAME="LANGUAGE" CONTENT="PT">
<link href="<?php print base_url(); ?>assets/css/style.css" rel="stylesheet" type="text/css"/>
<!-- MENU RESPONSIVO -->
<link href="<?php print base_url(); ?>assets/css/menu.css" rel="stylesheet" type="text/css"/>
<link href="<?php print base_url(); ?>assets/css/responsive-nav.css" rel="stylesheet" type="text/css"/>
<!-- ÍCONES -->
<link href="<?php print base_url(); ?>assets/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<!-- ANIMAÇÕES -->
<link href="<?php print base_url(); ?>assets/css/animate.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,700' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Permanent+Marker' rel='stylesheet' type='text/css'>
<link href="<?php print base_url(); ?>assets/images/favicon.jpg" rel="shortcut icon" type="image/x-icon" />
<style>canvas{}</style>
<!-- SCRIPTS -->
</head>
<body>
<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-63478402-1', 'auto');
ga('send', 'pageview');
</script>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.3&appId=527340640618148";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id="main">
<div class="header">
<input class="menu" type="checkbox" name="btn" id="controler">
<label for="controler" class="transition"><i class="fa fa-bars"></i></label>
<nav class="nav transition">
<a href="<?php print base_url(); ?>home" class="transition">Home</a>
<a href="<?php print base_url(); ?>blog" class="transition">Blog</a>
<a href="<?php print base_url(); ?>como-funciona" class="transition">Como Funciona</a>
<a href="<?php print base_url(); ?>cadastre-sua-quadra" class="transition">Cadastre sua Quadra</a>
<a href="<?php print base_url(); ?>contato" class="transition">Contato</a>
</nav>
<div class="topo grid-12 grayscale">
<div class="grid-4">
<div class="grid-12">
<figure class="effect-animation">
<img src="<?php print base_url(); ?>assets/images/imagem-800-800.jpg">
<figcaption>
<h2>CATEGORIA</h2>
<p>Mussum ipsum cacilds, vidis litro abertis</p>
</figcaption>
</figure>
</div>
</div>
<div class="grid-4">
<div class="grid-12">
<img src="<?php print base_url(); ?>assets/images/imagem-800-400.jpg">
</div>
<div class="grid-12">
<figure class="effect-animation">
<img src="<?php print base_url(); ?>assets/images/imagem-800-400.jpg">
<figcaption>
<h2>CATEGORIA</h2>
<p>Mussum ipsum cacilds, vidis litro abertis</p>
</figcaption>
</figure>
</div>
</div>
<div class="grid-4">
<figure class="effect-animation">
<img src="<?php print base_url(); ?>assets/images/imagem-800-800.jpg">
<figcaption>
<h2>CATEGORIA</h2>
<p>Mussum ipsum cacilds, vidis litro abertis</p>
</figcaption>
</figure>
</div>
</div>
<div id="filtro" class="grid-12 filtro center">
<h1>Encontrar o local e agendar seu futebol nunca foi tão fácil!</h1>
<form method="POST" action="<?php print base_url(); ?>quadras/busca">
<label for="search"></label>
<input type="search" name="chave" class="formInput search" id="search" placeholder="Busque por Nome, Bairro ou Cidade" required>
<button type="submit" class="btn btn-white-2"><i class="fa fa-search"></i> BUSCAR</button><br>
<p><a href="<?php print base_url(); ?>contato">Não encontrou o local que procurava? Entre em contato com o Jogue Lá!</a></p>
</form>
</div>
</div><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class utils {
function url_amigavel($variavel) {
$procurar = array('à', 'ã', 'â', 'é', 'ê', 'í', 'ó', 'ô', 'õ', 'ú', 'ü', 'ç',);
$substituir = array('a', 'a', 'a', 'e', 'e', 'i', 'o', 'o', 'o', 'u', 'u', 'c',);
$variavel = strtolower($variavel);
$variavel = str_replace($procurar, $substituir, $variavel);
$variavel = htmlentities($variavel);
$variavel = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml);/", "$1", $variavel);
$variavel = preg_replace("/([^a-z0-9]+)/", "-", html_entity_decode($variavel));
return trim($variavel, "-");
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class quadras extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Model_unidades');
$this->load->model('Model_logs');
}
public function lista($cidade = '', $url = '') {
$data['main_content'] = "quadra";
$data['quadra'] = $this->Model_unidades->item($url);
$this->load->view('template/default', $data);
}
public function busca() {
$data['main_content'] = "quadras";
$chave = $this->input->post('chave');
$this->Model_logs->inserir($chave);
$itens_encontrados = $this->Model_unidades->busca($chave);
$data['destaques'] = array();
$data['quadras'] = array();
foreach ($itens_encontrados as $item) {
if ($item['destaque'] == 1) {
$data['destaques'][] = $item;
} else {
$data['quadras'][] = $item;
}
}
$this->load->view('template/default', $data);
}
}
<file_sep><div class="destaque grid-fluid clear">
<div class="grid-6 spaceBox">
<a href="<?php print base_url() . 'quadras-society/' . $this->utils->url_amigavel($ouro['nome']) . '/' . $ouro['url']; ?>"><h2><?php print $ouro['unidade']; ?></h2></a>
<hr>
<video width="100%" height="" controls>
<source src="<?php print base_url(); ?>assets/video/<?php print $ouro['video']; ?>" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
</video>
</div>
<div class="grid-6 spaceBox">
<h2>DETALHES</h2>
<p><?php print $ouro['endereco']; ?> - <?php print (isset($ouro['bairro']) ? $ouro['bairro'] . ' - ' : '' ); ?> <?php print $ouro['nome']; ?></p>
<p><?php print $ouro['telefone']; ?></p>
<hr>
<?php if(isset($ouro['estacionamento']) && $ouro['estacionamento'] == 1) : ?>
<div class="icon estacionamento" title="Estacionamento"></div>
<?php endif; ?>
<?php if(isset($ouro['lanchonete']) && $ouro['lanchonete'] == 1) : ?>
<div class="icon lanchonete" title="Lanchonete"></div>
<?php endif; ?>
<?php if(isset($ouro['vestiarios']) && $ouro['vestiarios'] == 1) : ?>
<div class="icon vestiario" title="Vestiários"></div>
<?php endif; ?>
<div class="icon icon-none"></div>
<?php if(isset($ouro['quadras'])) : ?>
<?php for ($i=1; $i<= $ouro['quadras']; $i++ ) : ?>
<div class="icon quadras" title="Número de Quadras"></div>
<?php endfor; ?>
<div class="icon icon-none"></div>
<?php endif; ?>
<?php if(isset($ouro['churrasqueira']) && $ouro['churrasqueira'] == 1) : ?>
<div class="icon churrasqueira" title="Churrasqueira"></div>
<?php endif; ?>
<?php if(isset($ouro['escolinha']) && $ouro['escolinha'] == 1) : ?>
<div class="icon escolinha" title="Escolinha de Futebol"></div>
<?php endif; ?>
<?php if(isset($ouro['tv']) && $ouro['tv'] == 1) : ?>
<div class="icon tv" title="TV à Cabo"></div>
<?php endif; ?>
<?php if(isset($ouro['wifi']) && $ouro['wifi'] == 1) : ?>
<div class="icon wifi" title="Wifi"></div>
<?php endif; ?>
<div class="icon icon-none"></div>
<br />
<hr>
<h2>AVALIAÇÃO JOGUE LÁ</h2>
<div class="grid-3 spaceBox center">
<canvas id="doughnut" height=70 width=70></canvas>
<p>Vestiários: 90%</p>
</div>
<div class="grid-3 spaceBox center">
<canvas id="doughnut2" height=70 width=70></canvas>
<p>Estacionamento: 80%</p>
</div>
<div class="grid-3 spaceBox center">
<canvas id="doughnut3" height=70 width=70></canvas>
<p>Iluminação: 85%</p>
</div>
<div class="grid-3 spaceBox center">
<canvas id="doughnut4" height=70 width=70></canvas>
<p>Lanchonete: 70%</p>
</div>
<hr>
INFORMAÇÕES
<p><?php print $ouro['descricao']; ?></p>
<?php if(isset($ouro['classificacao'])) : ?>
<?php for ($i=1; $i<= $ouro['classificacao']; $i++ ) : ?>
<div class="icon rating"></div>
<?php endfor; ?>
<?php endif; ?>
</div>
</div>
<div class="clear"></div>
<div id="container" class="grid-fluid grayscale">
<?php foreach ($destaques as $destaque) : ?>
<div class="item grid-3 spaceBox">
<?php if(isset($destaque['logo'])) : ?>
<a href="<?php print 'quadras-society/' . $this->utils->url_amigavel($destaque['nome']) . '/' . $destaque['url']; ?>"><img src="<?php print base_url(); ?>uploads/quadras/<?php print $destaque['logo']; ?>" alt="<?php print $destaque['unidade']; ?>"></a>
<?php else : ?>
<a href="<?php print 'quadras-society/' . $this->utils->url_amigavel($destaque['nome']) . '/' . $destaque['url']; ?>"><img src="<?php print base_url(); ?>assets/images/post.jpg" alt="<?php print $destaque['unidade']; ?>"></a>
<?php endif; ?>
<div class="post">
<a href="<?php print 'quadras-society/' . $this->utils->url_amigavel($destaque['nome']) . '/' . $destaque['url']; ?>" class="link"><h2><?php print $destaque['unidade']; ?></h2></a>
<hr>
<p><?php print $destaque['endereco']; ?></p>
<p><?php print (isset($destaque['bairro']) ? $destaque['bairro'] . ' - ' : '' ); ?> <?php print $destaque['nome']; ?></p>
<hr>
<p><?php print $destaque['telefone']; ?></p>
<?php if(isset($destaque['classificacao'])) : ?>
<?php for ($i=1; $i<= $destaque['classificacao']; $i++ ) : ?>
<i class="fa fa-star"></i>
<?php endfor; ?>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
<?php foreach ($quadras as $quadra) : ?>
<div class="item grid-3 spaceBox">
<div class="post">
<a href="<?php print base_url() . 'quadras-society/' . $this->utils->url_amigavel($quadra['nome']) . '/' . $quadra['url']; ?>" class="link"><h2><?php print $quadra['unidade']; ?></h2></a>
<p><?php print $quadra['endereco']; ?> <?php print (isset($quadra['bairro']) ? $quadra['bairro'] : '' ); ?></p>
<p><?php print $quadra['telefone']; ?></p>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="clear"></div>
<?php $this->ultimos_posts->exibe_posts(); ?> <file_sep><div class="clear"></div>
<div id="container" class="grid-fluid grayscale">
<?php foreach ($destaques as $destaque) : ?>
<div class="item grid-3 spaceBox">
<?php if(isset($destaque['logo'])) : ?>
<a href="<?php print base_url() . 'quadras-society/' . $this->utils->url_amigavel($destaque['nome']) . '/' . $destaque['url']; ?>"><img src="<?php print base_url(); ?>uploads/quadras/<?php print $destaque['logo']; ?>" alt="<?php print $destaque['unidade']; ?>"></a>
<?php else : ?>
<a href="<?php print base_url() . 'quadras-society/' . $this->utils->url_amigavel($destaque['nome']) . '/' . $destaque['url']; ?>"><img src="<?php print base_url(); ?>assets/images/post.jpg" alt="<?php print $destaque['unidade']; ?>"></a>
<?php endif; ?>
<div class="post">
<a href="<?php print base_url() . 'quadras-society/' . $this->utils->url_amigavel($destaque['nome']) . '/' . $destaque['url']; ?>" class="link"><h2><?php print $destaque['unidade']; ?></h2></a>
<hr>
<p><?php print $destaque['endereco']; ?></p>
<p><?php print (isset($destaque['bairro']) ? $destaque['bairro'] . ' - ' : '' ); ?> <?php print $destaque['nome']; ?></p>
<hr>
<p><?php print $destaque['telefone']; ?></p>
<?php if(isset($destaque['classificacao'])) : ?>
<?php for ($i=1; $i<= $destaque['classificacao']; $i++ ) : ?>
<i class="fa fa-star"></i>
<?php endfor; ?>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
<?php foreach ($quadras as $quadra) : ?>
<div class="item grid-3 spaceBox">
<div class="post">
<a href="<?php print base_url() . 'quadras-society/' . $this->utils->url_amigavel($quadra['nome']) . '/' . $quadra['url']; ?>" class="link"><h2><?php print $quadra['unidade']; ?></h2></a>
<p><?php print $quadra['endereco']; ?> <?php print (isset($quadra['bairro']) ? $quadra['bairro'] : '' ); ?></p>
<p><?php print $quadra['telefone']; ?></p>
</div>
</div>
<?php endforeach; ?>
</div>
<?php $this->ultimos_posts->exibe_posts(); ?>
<file_sep><?php $this->ultimos_posts->exibe_posts(); ?> <file_sep><?php
class Model_unidades extends CI_Model {
function __construct() {
parent::__construct();
}
function inserir($dados = array()) {
$data = array(
'unidade' => $dados['unidade'],
'endereco' => $dados['endereco'],
'cidadeID' => $dados['cidadeID'],
'bairro' => $dados['bairro'],
'telefone' => $dados['telefone'],
'telefone2' => $dados['telefone2'],
'lanchonete' => $dados['lanchonete'],
'estacionamento' => $dados['estacionamento'],
'vestiarios' => $dados['vestiarios'],
'quadras' => $dados['quadras'],
'churrasqueira' => $dados['churrasqueira'],
'escolinha' => $dados['escolinha'],
'tv' => $dados['tv'],
'academia' => $dados['academia'],
'wifi' => $dados['wifi'],
'logo' => $dados['logo'],
'classificacao' => $dados['classificacao'],
'destaque' => $dados['destaque']
);
$this->db->insert('unidades', $data);
}
function remover($unidadeID = 0) {
$this->db->delete('unidades', array('unidadeID' => $unidadeID));
}
function alterar($dados = array(), $unidadeID = 0) {
$data = array(
'unidade' => $dados['unidade'],
'endereco' => $dados['endereco'],
'cidadeID' => $dados['cidadeID'],
'bairro' => $dados['bairro'],
'telefone' => $dados['telefone'],
'telefone2' => $dados['telefone2'],
'lanchonete' => $dados['lanchonete'],
'estacionamento' => $dados['estacionamento'],
'vestiarios' => $dados['vestiarios'],
'quadras' => $dados['quadras'],
'churrasqueira' => $dados['churrasqueira'],
'escolinha' => $dados['escolinha'],
'tv' => $dados['tv'],
'academia' => $dados['academia'],
'wifi' => $dados['wifi'],
'logo' => $dados['logo'],
'classificacao' => $dados['classificacao'],
'destaque' => $dados['destaque']
);
$this->db->where('unidadeID', $unidadeID);
$this->db->update('unidades', $data);
}
function lista($filtros = array(), $ordem = array(), $limite = 0, $inicio = 0) {
$this->db->from('unidades');
$this->db->join('cidade','unidades.cidadeID = cidade.id');
if(isset($filtros)){
foreach ($filtros as $key => $value) {
$this->db->where($key, $value);
}
}
if(isset($ordem)){
foreach ($ordem as $key => $value) {
$this->db->order_by($key,$value);
}
}
if($limite > 0 || $inicio > 0)
$this->db->limit($limite, $inicio);
$query = $this->db->get();
return $query->result_array();
}
function busca($chave = '', $destaque = 0) {
$this->db->from('unidades');
$this->db->join('cidade','unidades.cidadeID = cidade.id');
if(isset($chave)){
$this->db->like('unidade', $chave);
$this->db->or_like('endereco', $chave);
$this->db->or_like('bairro', $chave);
$this->db->or_like('nome', $chave);
}
$query = $this->db->get();
return $query->result_array();
}
function ouro() {
$this->db->from('unidades');
$this->db->join('cidade','unidades.cidadeID = cidade.id');
$this->db->where('ouro', 1);
$query = $this->db->get();
return $query->row_array();
}
function item($url = '') {
$this->db->from('unidades');
$this->db->join('cidade','unidades.cidadeID = cidade.id');
$this->db->where('url', $url);
$query = $this->db->get();
return $query->row_array();
}
}
|
20d8794b7151037db68b489d7933c9e71ad528f1
|
[
"JavaScript",
"HTML",
"PHP"
] | 22
|
PHP
|
boleirao/joguela
|
18c336467a17efe5610db79a45acc4bbe72e1da4
|
a4e15fa01cfcaf0a774dc37d36b9620e4bf4b182
|
refs/heads/master
|
<file_sep>include ':app'
rootProject.name='NoSmoking'
<file_sep>package com.undrown.nosmoking
import kotlin.math.floor
class MoneySavedFormat(timeStart:Long, timeCur:Long) {
private val secDelta = (timeCur - timeStart)/1000 //секунд прошло
private val rubSavedPerDay:Double = 20.0 //рублей в сутки
private val secInDay = 3600*24 //секунд в сутках
private val rubSavedPerSec = rubSavedPerDay/secInDay //экономия в секунду
val rubSaved = rubSavedPerSec * secDelta
private val usdSaved = (rubSaved/16.5f)
private val rub = floor(rubSaved).toInt()
private val kop = floor((rubSaved - rub)*100).toInt()
private val usd = floor(usdSaved).toInt()
private val cent = ((usdSaved - usd)*100).toInt()
val vRub = "$rub руб., $kop к."
val vUSD = "$usd \$, $cent ¢"
}<file_sep>package com.undrown.nosmoking
import kotlin.math.abs
class TimestampFormat(timeStart:Long, timeCur:Long) {
private val timeDelta = timeCur - timeStart
private var years:Long = 0L
private var months:Long = 0L
private var days:Long = 0L
private var hours:Long = 0L
private var minutes:Long = 0L
private var seconds:Long = 0L
//service values
private val millisInSec = 1000L
private val millisInMinute = 60*millisInSec
private val millisInHour = 60*millisInMinute
private val millisInDay = 24*millisInHour
private val millisInMonth = 30*millisInDay
private val millisInYear = 365*millisInDay
init {
timeDelta
.getYears()
.getMonths()
.getDays()
.getHours()
.getMinutes()
.getSeconds()
}
fun toVerbose():String{
return "${vYear()}${vMonth()}${vDay()}${vHour()}${vMinute()}${vSecond()}"
}
private fun Long.getYears(): Long {
years = this/millisInYear
return this%millisInYear
}
private fun Long.getMonths(): Long {
months = this/millisInMonth
return this%millisInMonth
}
private fun Long.getDays(): Long {
days = this/millisInDay
return this%millisInDay
}
private fun Long.getHours(): Long {
hours = this/millisInHour
return this%millisInHour
}
private fun Long.getMinutes(): Long {
minutes = this/millisInMinute
return this%millisInMinute
}
private fun Long.getSeconds(): Long {
seconds = this/millisInSec
return this%millisInSec
}
//verbose functions
private fun vYear():String{
if(years == 0L) return ""
val v = when(abs(years/10) % 10){
1L -> "Лет"
else -> {
when(abs(years) % 10){
1L -> "Год"
2L, 3L, 4L -> "Года"
else -> {
"Лет"
}
}
}
}
return "$years $v, "
}
private fun vMonth():String{
if(months == 0L) return ""
val v = when(abs(months/10) % 10){
1L -> "Месяцев"
else -> {
when(abs(months) % 10){
1L -> "Месяц"
2L, 3L, 4L -> "Месяца"
else -> {
"Месяцев"
}
}
}
}
return "$months $v, "
}
private fun vDay():String{
if(days == 0L) return ""
val v = when(abs(days/10) % 10){
1L -> "Дней"
else -> {
when(abs(days) % 10){
1L -> "День"
2L, 3L, 4L -> "Дня"
else -> {
"Дней"
}
}
}
}
return "$days $v, "
}
private fun vHour():String{
if(hours == 0L) return ""
val v = when(abs(hours/10) % 10){
1L -> "Часов"
else -> {
when(abs(hours) % 10){
1L -> "Час"
2L, 3L, 4L -> "Часа"
else -> {
"Часов"
}
}
}
}
return "$hours $v, "
}
private fun vMinute():String{
if(minutes == 0L) return ""
val v = when(abs(minutes/10) % 10){
1L -> "Минут"
else -> {
when(abs(minutes) % 10){
1L -> "Минута"
2L, 3L, 4L -> "Минуты"
else -> {
"Минут"
}
}
}
}
return "$minutes $v, "
}
private fun vSecond():String{
if(seconds == 0L) return ""
val v = when(abs(seconds/10) % 10){
1L -> "Секунд"
else -> {
when(abs(seconds) % 10){
1L -> "Секунда"
2L, 3L, 4L -> "Секунды"
else -> {
"Секунд"
}
}
}
}
return "$seconds $v"
}
}<file_sep>package com.undrown.nosmoking
import org.junit.Test
import kotlin.math.abs
class MoneyVisualizerTest {
@Test
fun scale(){
val value = 12227.2344564
val c = MoneyVisualizer(value)
c.getSplit()
println("Normally:")
println(c.result)
c.getRandomSplit()
println("Randomly:")
println(c.resultRandom)
println("Accuracy: " + abs(value - c.getResultSum()))
assert(abs(value - c.getResultSum()) < 0.01)
}
@Test
fun drawMoneyTest(){
val value = 12227.2344564
val c = MoneyVisualizer(value)
c.getRandomSplit()
//c.drawMoney()
}
}<file_sep>package com.undrown.nosmoking
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.concurrent.fixedRateTimer
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var timeStart =
this.getPreferences(Context.MODE_PRIVATE)
.getLong("com.undrown.nosmoking.timestart", Date().time)
fixedRateTimer("timer", false, 0L, 1000L){
this@MainActivity.runOnUiThread {
val timeCur = Date().time
val moneySaved = MoneySavedFormat(timeStart, timeCur)
timePassed.text = TimestampFormat(timeStart, timeCur).toVerbose()
rubSaved.text = moneySaved.vRub
dollarsSaved.text = moneySaved.vUSD
}
}
resetButton.setOnClickListener {
val builder = AlertDialog.Builder(this@MainActivity)
with(builder){
setMessage("Желаете сбросить?")
setNegativeButton("Отмена"){_, _ ->
return@setNegativeButton
}
setPositiveButton("Ок"){_, _ ->
with(this@MainActivity.getPreferences(Context.MODE_PRIVATE).edit()){
putLong("com.undrown.nosmoking.timestart", Date().time)
apply()
}
timeStart = this@MainActivity
.getPreferences(Context.MODE_PRIVATE)
.getLong("com.undrown.nosmoking.timestart", Date().time)
}
create().show()
}
}
timePassed.setOnClickListener {
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, "Я не курю уже ${TimestampFormat(timeStart, Date().time).toVerbose()}")
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, "Share via...")
startActivity(shareIntent)
}
//TODO: show how to use saved money
//TODO: show variants
rubSaved.setOnClickListener {
val visualizer = MoneyVisualizer(MoneySavedFormat(timeStart, Date().time).rubSaved)
visualizer.getRandomSplit()
Toast.makeText(this@MainActivity, visualizer.toString(), Toast.LENGTH_SHORT).show()
moneyCanvas.setImageBitmap(visualizer.drawMoney(this))
}
}
}
<file_sep>package com.undrown.nosmoking
import android.content.Context
import android.graphics.*
import org.jetbrains.annotations.TestOnly
import kotlin.math.floor
import kotlin.random.Random
/*
* TODO: make heap of money
* */
class MoneyVisualizer(value:Double) {
private val amount = floor(value*100)/100
private val nominalsRub = mapOf(
"500ka" to 500.0,
"200ka" to 200.0,
"100ka" to 100.0,
"50ka" to 50.0,
"25ka" to 25.0,
"10ka" to 10.0,
"5ka" to 5.0,
"1ka" to 1.0,
"50c" to 0.5,
"25c" to 0.25,
"10c" to 0.10,
"5c" to 0.05,
"1c" to 0.01
)
private val images = mapOf(
"500ka" to listOf(
R.drawable.img_500,
R.drawable.img_500r,
R.drawable.img_new_500,
R.drawable.img_new_500r
),
"200ka" to listOf(
R.drawable.img_200,
R.drawable.img_200r,
R.drawable.img_new_200,
R.drawable.img_new_200r
),
"100ka" to listOf(
R.drawable.img_100,
R.drawable.img_100r,
R.drawable.img_new_100,
R.drawable.img_new_100r
),
"50ka" to listOf(
R.drawable.img_50,
R.drawable.img_50r,
R.drawable.img_new_50,
R.drawable.img_new_50r
),
"25ka" to listOf(
R.drawable.img_25,
R.drawable.img_25r,
R.drawable.img_new_25,
R.drawable.img_new_25r
),
"10ka" to listOf(
R.drawable.img_10,
R.drawable.img_10r,
R.drawable.img_new_10,
R.drawable.img_new_10r
),
"5ka" to listOf(
R.drawable.img_5,
R.drawable.img_5r,
R.drawable.img_new_5,
R.drawable.img_new_5r
),
"1ka" to listOf(
R.drawable.img_1,
R.drawable.img_1r,
R.drawable.img_new_1,
R.drawable.img_new_1r
),
"50c" to listOf(
R.drawable.img_05,
R.drawable.img_05r,
R.drawable.img_05,
R.drawable.img_05r
),
"25c" to listOf(
R.drawable.img_025,
R.drawable.img_025r,
R.drawable.img_025,
R.drawable.img_025r
),
"10c" to listOf(
R.drawable.img_01,
R.drawable.img_01r,
R.drawable.img_01,
R.drawable.img_01r
),
"5c" to listOf(
R.drawable.img_005,
R.drawable.img_005r,
R.drawable.img_005,
R.drawable.img_005r
),
"1c" to listOf(
R.drawable.img_001,
R.drawable.img_001r,
R.drawable.img_001,
R.drawable.img_001r
)
)
private val paint = Paint()
val result = mutableMapOf<String, Int>()
val resultRandom = mutableMapOf(
"500ka" to 0,
"200ka" to 0,
"100ka" to 0,
"50ka" to 0,
"25ka" to 0,
"10ka" to 0,
"5ka" to 0,
"1ka" to 0,
"50c" to 0,
"25c" to 0,
"10c" to 0,
"5c" to 0,
"1c" to 0
)
private fun getSplit(amountUnused:Double){
val actualNominals = nominalsRub.filter { entry -> entry.value <= amountUnused }
if (actualNominals.isEmpty()) return
val scale = actualNominals.entries.first()
result[scale.key] = floor(amountUnused/scale.value).toInt()
if(scale.value == 0.01)
return
getSplit(amountUnused - scale.value*floor(amountUnused/scale.value).toInt())
}
private fun getRandomSplit(amountUnused: Double){
val actualNominals = nominalsRub.filter { entry -> entry.value <= amountUnused }
if (actualNominals.isEmpty()) return
val scale = actualNominals.entries.elementAt(Random.nextInt(actualNominals.entries.size))
var scalesMax = floor(amountUnused/scale.value).toInt()
if (scalesMax > 25)
scalesMax = 25
val times = Random.nextInt(scalesMax)
resultRandom[scale.key] = (resultRandom[scale.key]?.plus(times) ?: times)
if(amountUnused <= 0.02) {
resultRandom["1c"] = resultRandom["1c"]!! + 2
return
}
getRandomSplit(amountUnused - scale.value*times)
}
fun getSplit(){
result.clear()
getSplit(amount)
}
fun getRandomSplit(){
resultRandom.clear()
getRandomSplit(amount)
}
override fun toString(): String {
return resultRandom.toString()
}
@TestOnly
fun getResultSum(): Double {
var result = 0.0
for (item in resultRandom){
val times = item.value
val scale = nominalsRub.getOrElse(item.key) { 0.0 }
result += scale * times
}
return result
}
fun drawMoney(context: Context):Bitmap{
val width = 250
val height = 250
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
val canvas = Canvas(bitmap)
while(resultRandom.filter { item -> item.value > 0 }.isNotEmpty()){
for (item in resultRandom.filter { item -> item.value > 0 }){
if (item.value > 0){
resultRandom[item.key] = item.value - 1
val img = images[item.key]
var bmp = BitmapFactory.decodeResource(context.resources, img!![Random.nextInt(4)])
if(bmp == null){
println("null")
bmp = BitmapFactory.decodeResource(context.resources, R.drawable.img_001)
}
drawBitmap(canvas, bmp)
}
}
}
return bitmap
}
private fun drawBitmap(canvas:Canvas, bitmap: Bitmap){
val degrees = Random.nextFloat()*360
var r = Random.nextFloat()*(canvas.width)/2
if (Random.nextInt(100) < 50)
r /= 2
val d = canvas.width/2f
val degrees1 = Random.nextFloat()*360
canvas.translate(d, d)
canvas.rotate(degrees)
canvas.rotate(degrees1, r, 0f)
canvas.drawBitmap(bitmap, r, 0f, paint)
canvas.rotate(-degrees1, r, 0f)
canvas.rotate(-degrees)
canvas.translate(-d, -d)
}
}
|
d877feef1b5c51cb10e79a07d301f07dbb1d974f
|
[
"Kotlin",
"Gradle"
] | 6
|
Gradle
|
Undrown/NoSmoking
|
e0435b0807c8899ba1b446869a35f359faf80164
|
999f160dc9fb680340c2d88bae5af57cd06f6222
|
refs/heads/master
|
<file_sep>package br.com.java8;
import java.util.ArrayList;
import java.util.List;
public class LambdaStringsNewCompare {
public static void main(String[] args) {
List<String> palavras = new ArrayList<String>();
palavras.add("testeq1");
palavras.add("teste2");
palavras.add("teste323");
palavras.add("teste4");
palavras.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(palavras);
}
}
<file_sep>package br.com.java8;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
public class LambdaStrings {
public static void main(String[] args) {
List<String> palavras = new ArrayList<String>();
palavras.add("testeq1");
palavras.add("teste2");
palavras.add("teste323");
palavras.add("teste4");
palavras.sort((p1, p2) -> Integer.compare(p1.length(), p2.length()));
//Melhorias
palavras.sort(Comparator.comparing(s -> s.length()));
System.out.println("Lambda");
System.out.println(palavras);
//Explicacao
Function<String, Integer> funcao = s -> s.length();
Comparator<String> comparador = Comparator.comparing(funcao);
palavras.sort(comparador);
System.out.println(palavras);
/**************************************/
//Method Reference
palavras.sort(Comparator.comparing(String::length));
System.out.println("Method Reference");
System.out.println(palavras);
//Explicacao
Function<String, Integer> funcao2 = String::length;
Comparator<String> comparador2 = Comparator.comparing(funcao2);
palavras.sort(comparador2);
palavras.forEach(p -> System.out.println(p));
Consumer<String> impressor = System.out::println;
palavras.forEach(impressor);
palavras.forEach(System.out::println);
}
}
|
fe0e10174fd0dd9f714740a2c2599b9894735447
|
[
"Java"
] | 2
|
Java
|
sronlemos/Java8
|
23bfe0da0677ff49ad3ab926d6a2753e9339c11d
|
7ad57bd31bfb91b4219bf6175639579aadf22bfa
|
refs/heads/master
|
<repo_name>tsinbal/WaterDetection<file_sep>/src/com/waterdet/dao/UserDao.java
package com.waterdet.dao;
import org.apache.ibatis.session.SqlSession;
import com.waterdet.pojo.*;
public class UserDao {
private User user;
public UserDao(String userID)
{
user=new User();
user.setUserid(userID);
String stat="com.waterdet.mappers.Usermapper.getuser";
SqlSession session = ConnectMysql.connect();
user=(User)session.selectOne(stat,user);
session.close();
}
public String getUserPassword() {
String password=null;
if(user!=null)
password=user.getPassward();
return password;
}
}
<file_sep>/src/com/waterdet/dao/SensorDao.java
package com.waterdet.dao;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
import com.waterdet.pojo.Sensor;
public class SensorDao {
private List<Object> sensorlist;
private Sensor sensor;
public SensorDao(int number,String type)
{
sensor=new Sensor();
sensor.setNumber(number);
sensor.setType(type);
String stat="com.waterdet.mappers.Sensormapper.getdata";
SqlSession session = ConnectMysql.connect();
sensorlist=(List<Object>)session.selectList(stat,sensor);
session.close();
}
public List<Object> getSensorlist()
{
return sensorlist;
}
}
|
b8f9d0ce5f2b4645b1dc751c7f5b35f337ced07e
|
[
"Java"
] | 2
|
Java
|
tsinbal/WaterDetection
|
c1e97aedd07c00a2c9451877c2aeb8bd2c3503ca
|
b33aecc87280d9deb2e12ef98d0080d8e322eb64
|
refs/heads/master
|
<repo_name>xiaoxin008/hermes<file_sep>/source/_posts/19_7_16_docker-build-springboot.md
---
layout: post
title: 使用Docker部署SpringBoot项目
date: 2019-07-15 10:07:04
categories: docker
tags: docker docker-compose springboot
toc: true
---
#### 项目中添加Dockerfile
----
```dockerfile
# 基础镜像
FROM openjdk:8-jdk-alpine
# 挂载临时目录
VOLUME /tmp
# 创建变量JAR_FILE
ARG JAR_FILE
# 把jar放入容器中
ADD ${JAR_FILE} test.jar
# 暴露端口
EXPOSE 8999
# 容器启动时执行命令
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/test.jar"]
```
在项目下添加此`Dockerfile`文件
#### 添加Maven插件
----
```xml
<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>1.4.0</version>
<!--构建jar包时 自动打包为image package时执行build deploy 执行 push-->
<executions>
<execution>
<id>default</id>
<goals>
<goal>build</goal>
<goal>push</goal>
</goals>
</execution>
</executions>
<configuration>
<repository>${docker.registry.name}/${project.artifactId}</repository>
<tag>${project.version}</tag>
<!--使用setting.xml进行dockerhub 远程认证-->
<useMavenSettingsForAuth>false</useMavenSettingsForAuth>
<buildArgs>
<JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
</configuration>
</plugin>
```
在SpringBoot项目中的pom.xml `<build>-><plugins>-><plugin>` 里添加此插件,再执行`package`命令即可把此项目打包为镜像放入本地Docker images中,执行`deploy`命令会把打包后的镜像上传到Docker Registry(远程仓库)。
变量说明:
* `${docker.registry.name}`:docker registry(远程仓库)名称-上传的远程仓库的url,需在`properties`标签中定义
* `${project.artifactId}`:项目名称-image名称
* `${project.version}`:项目版本-image的tag
* `${project.build.finalName}`:项目构建后名称-构建参数(Dockerfile使用)
#### 打包项目
----
使用指令 `mvn clean install -U -DskipTests`指令即可构建此项目镜像
#### 启动容器
----
使用指令`docker run --name test -d ${docker.registry.name}/${project.artifactId}:${project.version}`
#### 使用docker-compose构建多容器微服务
----
```dockerfile
# 使用的docker版本
version: '3'
services:
# zookeeper服务
zookeeper-service:
image: docker.io/zookeeper:latest
ports:
- "2181:2181"
# mysql服务
mysql-service:
image: docker.io/mysql:latest
volumes:
- /opt/docker_v/mysql/conf:/etc/mysql/conf.d
environment:
MYSQL_ROOT_PASSWORD: <PASSWORD>
ports:
- "3306:3306"
# 项目一
test1:
image: xiaoxin008/test1:1.0.5-RELEASE
# 挂载日志目录
volumes:
- /logs/admin
ports:
- "8888:8888"
# 错误后是否重启
restart: always
# 依赖的服务(决定启动容器的顺序)
depends_on:
- mysql-service
- zookeeper-service
# 项目二
test2:
image: xiaoxin008/test2:1.0.0
volumes:
- /logs
ports:
- "8999:8999"
restart: always
depends_on:
- zookeeper-service
```
在项目下添加`docker-compose`文件
#### 启动docker-compose多容器微服务
----
使用指令`docker-compose up -d `<file_sep>/source/_posts/19_7_31_redis-rate-limiter.md
---
layout: post
title: 使用Redis-Lua脚本实现访问限流
date: 2019-07-31 18:01:04
categories: redis
tags: redis rate-limiter
toc: true
---
#### Redis中使用Lua脚本
----
* `减少网络开销` - 在Lua脚本中可以把多个命令放在同一个脚本中运行
* `原子操作` - redis会将整个脚本作为一个整体执行,中间不会被其他命令插入,编写脚本的过程中无需担心会出现竞态条件
* `复用性` - 客户端发送的脚本会永远存储在redis中,这意味着其他客户端可以复用这一脚本来完成同样的逻辑
#### 令桶法限流
----
<img src="/css/img/redis-usage/bucket.png" style="width:100%;height:100%"/>
<center class="picture-desc">令桶法.gif</center>
<img src="/css/img/redis-usage/step.png" style="width:100%;height:100%"/>
<center class="picture-desc">具体流程.gif</center>
#### 项目代码
----
##### 项目结构
```
+ config
RedisConfig.java------------------------------------------------初始化Redis方法
+ constant
SysConstant.java------------------------------------------------常量类
+ controller
IndexController.java--------------------------------------------测试接口
+ domain
RateLimiterBucket.java------------------------------------------令桶实体
+ web
RateLimiterFilter.java------------------------------------------限流过滤器
Application.java----------------------------------------------------启动类
+ resources
+ templates
login.html--------------------------------------------------测试界面
application.yml-----------------------------------------------------项目配置文件
rate_limiter.lua----------------------------------------------------Redis脚本
```
##### 项目依赖
```xml
<properties>
<java.version>1.8</java.version>
<fastjson.version>1.2.47</fastjson.version>
<common.lang3.version>3.8.1</common.lang3.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${common.lang3.version}</version>
</dependency>
</dependencies>
```
##### 核心解读
* RedisConfig.java
```java
package com.xiaoxin008.redisusage.config;
/**
* Redis初始化
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@Configuration
public class RedisConfig{
/**
* redisTemplate相关配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用fastjson来序列化和反序列化reids的value值(默认使用jdk的序列化方式)
GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
template.setDefaultSerializer(genericFastJsonRedisSerializer);
template.setValueSerializer(genericFastJsonRedisSerializer);
template.setKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(genericFastJsonRedisSerializer);
template.setHashKeySerializer(new StringRedisSerializer());
//修改以上配置,使其生效
template.afterPropertiesSet();
return template;
}
/**
* 对hash类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 对string类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对list类型的数据操作(链表)
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对set类型的数据操作(无序集合)
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对zset类型的数据操作(有序集合)
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
```
* RateLimiterBucket.java
```java
package com.xiaoxin008.redisusage.domain;
/**
* 令桶
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@Data
public class RateLimiterBucket implements Serializable {
//容量
private Long capacity;
//速率
private Long rate;
}
```
* RateLimiterFilter.java
```java
package com.xiaoxin008.redisusage.web;
/**
* 限流过滤器
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@WebFilter(urlPatterns = "/index",filterName = "rateLimiterFilter")
public class RateLimiterFilter implements Filter {
@Autowired
private RedisTemplate<String,Object> redisTemplate;
private RedisScript<Boolean> redisScript;
private RateLimiterBucket limiterBucket;
@Override
public void init(FilterConfig config){
//初始化令桶
RateLimiterBucket bucket = new RateLimiterBucket();
bucket.setCapacity(20L);
bucket.setRate(100L);
limiterBucket = bucket;
//初始化脚本
DefaultRedisScript script = new DefaultRedisScript<>();
ClassPathResource resource=new ClassPathResource("rate_limiter.lua");
script.setScriptSource(new ResourceScriptSource(resource));
script.setResultType(Boolean.class);
redisScript = script;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
String requestURI = req.getServletPath();
//生成redis-key
List<String> keys = generateKeys(requestURI);
//执行lua脚本 传入key 令桶对象 返回是否受限结果
Boolean isAllow = redisTemplate.execute(redisScript, keys, limiterBucket);
if(isAllow){
//true 不受限 正常放行
chain.doFilter(request,response);
}else{
//false 受限 返回受限提示
res.getWriter().print("server is too busy!!!");
}
}
@Override
public void destroy() {
//清除所有限流
redisTemplate.delete(SysConstant.REDIS_GROUP.concat(":").concat(SysConstant.RATE_LIMITER_GROUP));
}
private List<String> generateKeys(String url){
List<String> keys = Arrays.asList(SysConstant.REDIS_GROUP, SysConstant.RATE_LIMITER_GROUP, url);
return Arrays.asList(StringUtils.join(keys, ":"));
}
}
```
* application.yml
```yaml
server:
port: 8080
servlet:
context-path: "/rate"
spring:
thymeleaf:
cache: false
redis:
# 地址
host: 127.0.0.1
# 端口
port: 6379
# 连接超时时间(毫秒)
timeout: 5000
# 采用jedis方式实现
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
```
* rate_limiter.lua
```lua
-- 取到传入的redis-key
local key = KEYS[1];
-- 取到传入的令桶速率(过期时间)
local rate = cjson.decode(ARGV[1]).rate;
-- 取到传入的令桶容量(redis-value)
local capacity = cjson.decode(ARGV[1]).capacity;
-- 去redis-server中取此key的值
local current = tonumber(redis.call("get",key));
-- 如果为null
if current == nil then
-- 存入数据 value = 令桶容量 - 1 过期时间为令桶速率
redis.call("setex",key,rate,capacity - 1);
else
-- 如果不为null 并且 value == 0
if current == 0 then
-- 返回false 限制其访问
return false
-- 如果不为null 并且 value != 0
else
-- 存入数据 value = value - 1 过期时间为令桶速率
redis.call("setex",key,rate,current - 1);
end
end
-- 返回true允许其访问
return true
```
#### 源码地址 & 借鉴资料
----
* 源码地址:[https://github.com/xiaoxin008/redis-usage](https://github.com/xiaoxin008/redis-usage)
* 在Redis中使用Lua脚本:[https://my.oschina.net/u/3847203/blog/3023066](https://my.oschina.net/u/3847203/blog/3023066)
<file_sep>/themes/theme-example/source/js/about.js
$(function () {
$(".button-3d").on("click",function () {
var type = $(this).attr("name");
var cardName = "."+type+"-card";
if($(this).hasClass("button-"+type+"-3d-active")){
$(this).removeClass("button-"+type+"-3d-active");
$(cardName).css("display","none");
}else{
$.each($(".button-3d"),function (i,item) {
$(item).removeClass("button-"+$(item).attr("name")+"-3d-active");
$("."+$(item).attr("name")+"-card").css("display","none");
})
$(this).addClass("button-"+type+"-3d-active");
$(cardName).css("display","block");
}
});
});<file_sep>/source/about/index.md
---
layout: about
title: about
date: 2019-06-17 12:26:33
tags:
---
<file_sep>/source/_posts/19_7_17_spring-security-oauth2-social.md
---
layout: post
title: SpringSecurity-OAuth2-SpringSocial构建统一认证登陆中心
date: 2019-07-25 10:42:04
categories: spring
tags: spring spring-social
toc: true
---
#### 流程简述
----
<img src="/css/img/security-oauth/springsecurity-oauth2-social.png" style="width:100%;height:100%"/>
<center class="picture-desc">简单流程图.gif</center>
#### 认证中心服务端代码
----
##### 项目结构
```
+ controller
AccountController.java------------------------------------------统一账户控制器
LoginController.java--------------------------------------------登录控制器
UserController.java---------------------------------------------用户控制器
+ core
+ security
AuthRedisTokenStore.java-------------------------------------Redis存储Token支持
AuthServerConfig.java ---------------------------------------初始化授权服务器
ResourceServerConfig.java------------------------------------初始化资源服务器
SecurityConfig.java------------------------------------------SpringSecurity初始化配置
+ social
CertificationSocialUserDetailsService.java-------------------绑定统一账户服务类
SignUpController.java----------------------------------------绑定统一账户控制器
SocialConfig.java--------------------------------------------SpringSocial初始化配置
+ dao
AccountMapper.java----------------------------------------------统一账户Mapper
+ domain
Account.java----------------------------------------------------统一账户实体
Role.java-------------------------------------------------------角色实体
+ service
+ impl
AccountServiceImpl.java------------------------------------统一账户服务实现
AccountService.java---------------------------------------------统一账户服务接口
+ util
MyPasswordEncoder.java------------------------------------------加密工具类
Application.java----------------------------------------------------启动类
+ resources
+ mapper
AccountMapper.xml-------------------------------------------统一账户Mapper
+ static
+ templates
login.html--------------------------------------------------登录操作界面
register.html-----------------------------------------------绑定操作界面
application.yml-----------------------------------------------------项目配置文件
logback-spring.xml--------------------------------------------------日志配置文件
```
##### 项目依赖
```xml
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
<docker.registry.name>xiaoxin008</docker.registry.name>
<spring-social.version>1.1.6.RELEASE</spring-social.version>
<spring-social-crypto.version>5.0.0.M2</spring-social-crypto.version>
<spring-social.github.version>1.0.0.M4</spring-social.github.version>
<mybatis.version>2.0.1</mybatis.version>
<httpclient.version>4.5.3</httpclient.version>
<fastjson.version>1.2.58</fastjson.version>
</properties>
<dependencies>
<!--springboot监控节点-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--springcloud-eureka依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--oauth2依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<!--springsocial 基础包-->
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-config</artifactId>
<version>${spring-social.version}</version>
</dependency>
<!--springsocial 提供社交连接框架和OAuth 客户端支持 -->
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-core</artifactId>
<version>${spring-social.version}</version>
</dependency>
<!--springsocial 提供社交安全支持 -->
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-security</artifactId>
<version>${spring-social.version}</version>
</dependency>
<!--springsocial 管理web应用程序的连接 -->
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-web</artifactId>
<version>${spring-social.version}</version>
</dependency>
<!-- springsocial 对spring-security提供支持-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>${spring-social-crypto.version}</version>
</dependency>
<!-- springsocial 对github提供支持-->
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-github</artifactId>
<version>${spring-social.github.version}</version>
</dependency>
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<!--json工具-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--配置文件属性注入支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
```
##### 项目核心类及核心配置解读
* application.yml
```yaml
# 服务器端口号
server:
port: 9090
# eureka注册中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8070/eureka
spring:
# 应用名称
application:
name: certification-server
# 关闭thymeleaf缓存
thymeleaf:
cache: false
# mysql
datasource:
name: local
url: jdbc:mysql://localhost:3306/certification?
useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
username: root
password: <PASSWORD>
# redis
redis:
host: 127.0.0.1
port: 6379
# mybatis配置
mybatis:
mapperLocations: classpath:/mapper/*.xml
type-aliases-package: com.xiaoxin.certification.dao.*Mapper
# 日志相关
logging:
config: classpath:logback-spring.xml
path: ../certification-server/logs/
# Github OAuth 服务器
github:
clientId: 55faa83726f98252c50e
secret: <KEY>
auth-url: /auth/github
# 应用url
application:
url: http://localhost:9090/
```
* AuthServerConfig.java
```java
package com.xiaoxin.certification.core.security;
/**
* 授权服务器配置类
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@Configuration
@EnableAuthorizationServer //启用授权服务器
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new AuthRedisTokenStore(redisConnectionFactory);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//使用redis来存储验证返回的token
endpoints.tokenStore(tokenStore());
//请求token的request method 可以为 GET或者POST(方便测试,可以去除)
endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//从数据库加载client信息
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
//允许表单认证
oauthServer.allowFormAuthenticationForClients();
}
}
```
* ResourceServerConfig.java
```java
package com.xiaoxin.certification.core.security;
/**
* 资源服务器配置类
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@Order(6) //加载顺序必须在SecurityConfig.java之后
@Configuration
@EnableResourceServer //启用资源服务器
@EnableGlobalMethodSecurity(prePostEnabled = true) //使用表达式时间方法级别的安全性
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().exceptionHandling()
//处理错误信息
.authenticationEntryPoint((request, response, authException)
-> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
.authorizeRequests()
//所有通过的url全部需要权限过滤
.anyRequest().authenticated()
.and()
//基于http基本验证
.httpBasic();
}
}
```
* SecurityConfig.java
```java
package com.xiaoxin.certification.core.security;
/**
* SpringSecurity基础配置
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@EnableWebSecurity //启用SpringSecurity
@Configuration
@Order(2) //执行顺序一定要在 ResourceServerConfig.java 前
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
HttpSecurity security = http.requestMatchers()
.antMatchers("/account/**","/login","/auth/**","/signup","/connect/**","/register","/oauth/**") //拦截的url
.and()
.authorizeRequests()
.antMatchers("/account/**").hasRole("ADMIN") //添加权限
.antMatchers("/auth/**","/signup","/connect/**","/register","/oauth/**").permitAll() //放行的url
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and().csrf().disable();
security.apply(new SpringSocialConfigurer());
}
}
```
* SocialConfig.java
```java
package com.xiaoxin.certification.core.social;
/**
* SpringSocial初始化类
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@EnableSocial //启用SpringSocial
@Configuration
public class SocialConfig implements SocialConfigurer {
@Autowired
private DataSource dataSource;
@Autowired
private Environment environment;
/**
* 创建链接工厂
* @param configurer
* @param environment
*/
@Override
public void addConnectionFactories(ConnectionFactoryConfigurer configurer, Environment environment) {
//创建GitHubConnectionFactory(专门用来创建GitHubConnection对象的)
configurer.addConnectionFactory(new GitHubConnectionFactory(environment.getProperty("github.clientId"), environment.getProperty("github.secret")));
}
/**
* 创建用户保留和恢复连接设置
* @param connectionFactoryLocator
* @return UsersConnectionRepository
*/
@Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
//从GitHub上获取的用户对象存入数据库中
return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
}
@Override
public UserIdSource getUserIdSource() {
//基于SecurityContextHolder的UserIdSource实现类(为与SpringSecurity集成)
return new AuthenticationNameUserIdSource();
}
/**
* 创建ConnectController Bean
* @param connectionFactoryLocator
* @param connectionRepository
* @return
*/
@Bean
public ConnectController connectController(
ConnectionFactoryLocator connectionFactoryLocator,
ConnectionRepository connectionRepository) {
ConnectController connectController = new ConnectController(connectionFactoryLocator, connectionRepository);
//设置应用url
connectController.setApplicationUrl(environment.getProperty("application.url"));
return connectController;
}
/**
* 注册使用工具
* @param connectionFactoryLocator
* @param connectionRepository
* @return
*/
@Bean
public ProviderSignInUtils providerSignInUtils(ConnectionFactoryLocator connectionFactoryLocator,
UsersConnectionRepository connectionRepository){
//使用这个bean的doPostSignUp来关联本地统一账户和远程github账号
return new ProviderSignInUtils(connectionFactoryLocator,connectionRepository);
}
}
```
* SignUpController.java
```java
package com.xiaoxin.certification.core.social;
/**
* 绑定页面
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@Controller
public class SignUpController {
@Autowired
private ProviderSignInUtils providerSignInUtils;
@Autowired
private Environment environment;
@Autowired
private AccountService accountService;
@RequestMapping(value="/signup", method= RequestMethod.GET)
public String signup(WebRequest request) {
//当GitHub OAuth返回账号相关信息时,会使用UserIdSource的getUserId()去查询服务器是否为其
//分配好了统一账户的userId,如果获得到的userId为NULL会跳至此接口让用户绑定统一账户,如果
//不为NULL则直接进入所请求页面(在权限范围内)
return "register";
}
@RequestMapping(value="/signup", method= RequestMethod.POST)
public String signupForm(String phone,String password, WebRequest request) {
//绑定页面提交的统一账户信息,如果存在此统一账户直接使用providerSignInUtils.doPostSignUp绑定GitHub账号和统一账户
//如果不存在此统一账户,则创建之后再进行绑定
Account account = accountService.getAccountByUsername(phone);
if(account == null){
Account a = new Account(phone,password);
accountService.insertAccount(a);
}
providerSignInUtils.doPostSignUp(phone,request);
//最后重定向到请求授权url 重新刷新上面的过程
return "redirect:".concat(environment.getProperty("github.auth-url"));
}
}
```
* CertificationSocialUserDetailsService.java
```java
package com.xiaoxin.certification.core.social;
/**
* 获取统一账户
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@Service
public class CertificationSocialUserDetailsService implements SocialUserDetailsService {
@Autowired
private AccountService accountService;
//SpringSocial获取所绑定的统一账户方法
@Override
public SocialUserDetails loadUserByUserId(String username) throws UsernameNotFoundException {
Account account = accountService.getAccountByUsername(username);
List<Role> roles = account.getRoles();
List<String> roleNames = roles.stream().map(Role::getExpression).collect(Collectors.toList());
SocialUser socialUser = new SocialUser(account.getUsername(), account.getPassword(), AuthorityUtils.createAuthorityList(roleNames.toArray(new String[roleNames.size()])));
return socialUser;
}
}
```
* UserController.java
```java
package com.xiaoxin.certification.controller;
/**
* 用户控制器
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@Controller
public class UserController {
/**
* 向客户端返回用户信息接口
* @param principal
* @return
*/
@RequestMapping("/user")
@ResponseBody
public Principal user(Principal principal) {
OAuth2Authentication authentication = (OAuth2Authentication) principal;
Authentication userAuthentication = authentication.getUserAuthentication();
//因为SpringSecurity会把用户信息装成UsernamePasswordAuthenticationToken.class返回,而
//SpringSocial会把用户信息封装为SocialAuthenticationToken.class,所以需要转换一下
if(userAuthentication instanceof SocialAuthenticationToken){
principal = new UsernamePasswordAuthenticationToken(
userAuthentication.getPrincipal(),userAuthentication.getCredentials(),userAuthentication.getAuthorities());
}
return principal;
}
}
```
#### 认证中心客户端代码
----
##### 项目结构
```
+ config
ResourceServerConfig.java---------------------------------------初始化资源服务器
+ controller
IndexController.java--------------------------------------------首页控制器
+ security
SecurityConfig.java---------------------------------------------SpringSecurity初始化配置
Application.java----------------------------------------------------启动类
+ resources
+ static
+ templates
index.html--------------------------------------------------首页操作界面
securedPage.html--------------------------------------------受保护界面
application.yml-----------------------------------------------------项目配置文件
logback-spring.xml--------------------------------------------------日志配置文件
```
##### 项目依赖
```xml
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
<docker.registry.name>xiaoxin008</docker.registry.name>
<thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
</properties>
<dependencies>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--eureka-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--oauth2-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<!--springsecurity-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<!--支持thymeleaf使用springsecurity相关标签 并且 只支持2.10以下版本的springboot-->
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>${thymeleaf-extras-springsecurity4.version}</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
```
##### 项目核心类及核心配置解读
* application.yml
```yaml
# 服务器
server:
port: 8882
servlet:
# 一定要有上下文,因为启用单点登录时,SpringSecurity会对"/"有特殊处理
context-path: /client
session:
cookie:
name: SESSION1
# spring-security
security:
auth-server: http://localhost:9090
oauth2:
# oAuth认证中心配置
client:
clientId: certification
clientSecret: 123456
accessTokenUri: ${security.auth-server}/oauth/token
userAuthorizationUri: ${security.auth-server}/oauth/authorize
scope: read
resource:
userInfoUri: ${security.auth-server}/user
# spring
spring:
application:
name: certification-client-1
thymeleaf:
cache: false
# eureka
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8070/eureka
# 日志
logging:
config: classpath:logback-spring.xml
path: ../logs/certification-client-1
```
* ResourceServerConfig.java
```java
package com.xiaoxin008.client.config;
/**
* 资源服务器配置类
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@Order(6) //加载顺序必须在SecurityConfig.java之后
@Configuration
@EnableResourceServer //启用资源服务器
@EnableGlobalMethodSecurity(prePostEnabled = true) //使用表达式时间方法级别的安全性
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().exceptionHandling()
//异常处理
.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
.authorizeRequests()
// .antMatchers(HttpMethod.GET,"/read").access("#oauth2.hasScope('read')")
// .antMatchers(HttpMethod.GET,"/write").access("#oauth2.hasScope('write')")
//所有资源必须经过权限过滤
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
```
* SecurityConfig.java
```java
package com.xiaoxin008.client.security;
/**
* 安全初始化配置
*
* @author xiaoxin008(313595055 @ qq.com)
* @since 1.0.0
*/
@Order(2) //执行顺序一定要在 ResourceServerConfig.java 前
@EnableOAuth2Sso //启用单点登录
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
//拦截所有url
.antMatchers("/**")
.and()
.authorizeRequests()
//放行登陆url
.antMatchers("/login**","/").permitAll()
//其余url进行权限过滤
.anyRequest().authenticated()
.and()
//禁用csrf
.csrf().disable().cors();
}
}
```
* securedPage.html(使用thymeleaf对SpringSecurity标签支持)
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Spring Security SSO</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="col-sm-12">
<h1>Secured Page</h1>
<!--Welcome, <p>登录者:<span th:text="${#httpServletRequest.remoteUser}"></span></p>-->
<div sec:authorize="isAuthenticated()">
<p>已有用户登录</p>
<p>登录者:<span sec:authentication="name"></span></p>
<p>角色:<span sec:authentication="authorities"></span></p>
<p>是否是管理员:<span sec:authorize="hasRole('ROLE_ADMIN')">是</span><span sec:authorize="!hasRole('ROLE_ADMIN')">否</span></p>
</div>
<div sec:authorize="isAnonymous()">
<p>未有用户登录</p>
</div>
</div>
</div>
</body>
</html>
```
#### 结果演示
----
* 正常登陆演示
<img src="/css/img/security-oauth/common.gif" style="width:100%;height:100%"/>
<center class="picture-desc">正常登陆.gif</center>
* GitHub登陆演示
<img src="/css/img/security-oauth/github.gif" style="width:100%;height:100%"/>
<center class="picture-desc">GitHub登陆.gif</center>
* 单点登录演示
<img src="/css/img/security-oauth/sso.gif" style="width:100%;height:100%"/>
<center class="picture-desc">单点登陆.gif</center>
#### 优化方向
----
* 从数据库中动态加载权限数据
* 资源服务器相关配置优化
* 错误页面
* 微信,微博等登陆实现
* 实现 `scope` 权限控制
* 取消绑定和退出登录功能实现
* 登录加入验证码
* `Remember Me` 功能实现
* 加入短信登录方式和短信登录绑定
* 实现前后端分离
#### 源码地址 & 借鉴资料
----
* 源码地址:[https://github.com/xiaoxin008/certification](https://github.com/xiaoxin008/certification)
* OAuth2设计理念:[http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html](http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html)
* SpringSecurity基于OAuth2单点登录:[https://www.cnblogs.com/xifengxiaoma/p/10043173.html](https://www.cnblogs.com/xifengxiaoma/p/10043173.html)
* SpringSocial文档:[https://docs.spring.io/spring-social/docs](https://docs.spring.io/spring-social/docs/current-SNAPSHOT/reference/htmlsingle/#section_how-to-get)
* SpringSocial-GitHub简易登录:[https://www.cnblogs.com/sky-chen/p/10530678.html](https://www.cnblogs.com/sky-chen/p/10530678.html)
<file_sep>/source/categories/index.md
---
layout: categories
title: categories
date: 2019-07-17 22:06:24
type: "categories"
---
<file_sep>/README.md
# hermes
#### [博客地址:https://dreamy-turing-2fc2f2.netlify.com/](https://dreamy-turing-2fc2f2.netlify.com/)
<file_sep>/source/_posts/19_9_17_docker_remote_debug.md
---
layout: post
title: 使用IDEA远程调试Springboot项目(Docker环境)
date: 2019-09-17 18:01:04
categories: docker
tags: docker springboot
toc: true
---
#### 在IDEA中创建远程连接
----
<img src="/css/img/docker-debug/connection.png" style="width:100%;height:100%"/>
<center class="picture-desc">在IDEA中创建远程连接.png</center>
#### Dockerfile构建镜像
----
```dockerfile
# 基础镜像
FROM openjdk:8-jdk-alpine
# 挂载临时目录
VOLUME /tmp
# 创建变量JAR_FILE
ARG JAR_FILE
# 把jar放入容器中
ADD ${JAR_FILE} certification-server.jar
# 暴露端口,这里的端口要与配置项中的address一致
EXPOSE 9090
# 容器启动时执行命令,这里的配置与远程连接配置中的参数一致
ENTRYPOINT ["java","-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=9090","-jar","/certification-server.jar"]
```
#### 远程调试
----
##### 开始调试
<div class="picture-font">1. 先启动容器</div>
<img src="/css/img/docker-debug/start-container.png" style="width:100%;height:100%"/>
<center class="picture-desc">启动容器.png</center>
<div class="picture-font">2. 在启动容器的同时再启动remote-debug(一定是在容器启动之后,启动完成之前)</div>
<img src="/css/img/docker-debug/remote-debug.png" style="width:100%;height:100%"/>
<center class="picture-desc">启动远程调试.png</center>
##### 调试演示
<div class="picture-font">1. 访问接口</div>
<img src="/css/img/docker-debug/interface.png" style="width:100%;height:100%"/>
<center class="picture-desc">访问接口.png</center>
<div class="picture-font">2. 看其是否进入断点</div>
<img src="/css/img/docker-debug/break-point.png" style="width:100%;height:100%"/>
<center class="picture-desc">进入断点.png</center><file_sep>/source/_posts/19_7_15_soul-usage.md
---
layout: post
title: Soul使用文档
date: 2019-07-04 13:47:04
tags: soul gateway
categories: gateway
toc: true
---
#### HTTP调用
--------------------
##### soul-admin配置
<div class="picture-font">1. 打开soul-admin控制台,登陆之后,选择【系统管理-插件管理】界面,确保divide插件开启</div>
<img src="/css/img/soul/plugin.png" style="width:100%;height:100%"/>
<center class="picture-desc">插件管理.png</center>
<div class="picture-font">2. 打开divide插件,添加选择器</div>
<center><img src="/css/img/soul/divide-selector.png" style="width:50%;height:50%;"/></center>
<center class="picture-desc">创建divide插件选择器.png</center>
<div class="picture-font">3. 选中添加后的选择器,添加规则列表</div>
<center><img src="/css/img/soul/divide-rule.png" style="width:50%;height:50%;"/></center>
<center class="picture-desc">创建规则列表.png</center>
##### postman发送HTTP请求
<div class="picture-font">1. 添加header参数</div>
<img src="/css/img/soul/divide-add-header.png" style="width:100%;height:100%"/>
<center class="picture-desc">添加header.png</center>
<div class="picture-font">2. 添加body参数(接口参数)</div>
<img src="/css/img/soul/divide-add-body.png" style="width:100%;height:100%"/>
<center class="picture-desc">添加body.png</center>
<div class="picture-font">3. 执行结果</div>
<img src="/css/img/soul/divide-result.png" style="width:100%;height:100%"/>
<center class="picture-desc">执行结果.png</center>
#### DUBBO调用
--------------------
##### soul-admin配置
<div class="picture-font">1. 先检查是否已开启dubbo插件,与上述类似不再赘述。打开dubbo插件,添加选择器</div>
<center><img src="/css/img/soul/dubbo-selector.png" style="width:50%;height:50%;"/></center>
<center class="picture-desc">创建dubbo插件选择器.png</center>
<div class="picture-font">2. 选中添加后的选择器,添加规则列表</div>
<center><img src="/css/img/soul/dubbo-rule.png" style="width:50%;height:50%;"/></center>
<center class="picture-desc">创建规则列表.png</center>
##### postman发送HTTP请求调用DUBBO接口
<div class="picture-font">1. 添加header参数</div>
<img src="/css/img/soul/dubbo-add-header.png" style="width:100%;height:100%"/>
<center class="picture-desc">添加header.png</center>
<div class="picture-font">2. 添加body参数(DUBBO接口相关参数)</div>
<img src="/css/img/soul/dubbo-add-body.png" style="width:100%;height:100%"/>
<center class="picture-desc">添加body.png</center>
<div class="picture-font">3. 执行结果</div>
<img src="/css/img/soul/dubbo-result.png" style="width:100%;height:100%"/>
<center class="picture-desc">执行结果.png</center>
<div class="note"><span style="color:red">*</span>DUBBO接口相关参数,请参照官方文档:<a href="https://dromara.org/website/zh-cn/docs/soul/dubbo.html">soul-dubbo插件参数传递</a></div>
#### 权限过滤
--------------------
##### soul-admin配置
<div class="picture-font">1. 先检查是否已开启sign插件(默认关闭),与上述类似不再赘述。打开sign插件,添加选择器</div>
<center><img src="/css/img/soul/sign-selector.png" style="width:50%;height:50%;"/></center>
<center class="picture-desc">创建sign插件选择器.png</center>
<div class="picture-font">2. 选中添加后的选择器,添加规则列表</div>
<center><img src="/css/img/soul/sign-rule.png" style="width:50%;height:50%;"/></center>
<center class="picture-desc">创建规则列表.png</center>
<div class="picture-font">3. 添加appKey与appSecret,进入【系统管理-认证管理】菜单,添加数据</div>
<center><img src="/css/img/soul/sign-appKey.png" style="width:50%;height:50%;"/></center>
<center class="picture-desc">添加appKey.png</center>
<div class="note"><span style="color:red">*</span>根据官方加密方式获取sign值,具体见:<a href="https://dromara.org/website/zh-cn/docs/soul/sign.html">soul-sign插件使用规则</a></div>
##### postman发送HTTP请求调用DUBBO接口验证权限
<div class="picture-font">未加入权限验证参数</div>
<img src="/css/img/soul/sign-auth-fail.png" style="width:100%;height:100%"/>
<center class="picture-desc">验证拦截.png</center>
<div class="picture-font">加入权限验证参数</div>
<img src="/css/img/soul/sign-auth-success.png" style="width:100%;height:100%"/>
<center class="picture-desc">验证通过.png</center>
<div class="note"><span style="color:red">*</span>参数来源具体见:<a href="https://dromara.org/website/zh-cn/docs/soul/sign.html">soul-sign插件使用规则</a></div>
#### 参考文档
--------------------
* [Soul网关项目GitHub地址](https://github.com/Dromara/soul)
* [Soul网关官方参考文档](https://dromara.org/website/zh-cn/docs/soul/soul.html)
|
c57d5e7dd25a388a0d60245ff4879f86cf14e04a
|
[
"Markdown",
"JavaScript"
] | 9
|
Markdown
|
xiaoxin008/hermes
|
b319698d5511caf368ae3c8bc2ac82b6d84d67c8
|
7a303c64107327152a68b021cbac084d04aacdda
|
refs/heads/master
|
<repo_name>shaxqq/switches<file_sep>/menu.js
window.onload = function (){
function menusHow() {
console.log();
document.querySelector('.checkbox-button-menu').style.top = '5vh';
}
}<file_sep>/ftth_pon.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Коммутаторы</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine">
<script src="scroll.js"></script>
</head>
<body>
<header class="nav">
<div class="nav__logo">
<a href="index.html" class="nav__text" > Swit</a>
<a href="index.html"class="nav__text--right">ches</a>
</div>
<ul class="nav__list">
<!-- <li class="nav__item">
<a href="zte.html" class="nav__link">ZTE</a></li>
<li class="nav__item">
<a href="dlink.html" class="nav__link">D-link</a></li> -->
<li class="nav__item">
<a href="radio.html" class="nav__link">Радиоканал</a></li>
<li class="nav__item">
<a href="fttb.html" class="nav__link">FTTB</a></li>
<li class="nav__item">
<a href="ftth_mediaconverter.html" class="nav__link">FTTH-Медиаконвертер</a></li>
<li class="nav__item">
<a href="ftth_pon.html" class="nav__link">FTTH-PON</a></li>
</ul>
<li class="nav__item-check">
<label for="checkbox-button-menu">☰</label>
<input id="checkbox-button-menu" type="checkbox" hidden />
<ul class="button-menu">
<!-- <li class="button-menu__item">
<a href="#" class="button-menu__link">ZTE</a>
</li>
<li class="button-menu__item">
<a href="#" class="button-menu__link">D-link</a>
</li> -->
<li class="button-menu__item">
<a href="radio.html" class="button-menu__link">Радиоканал</a>
</li>
<li class="button-menu__item">
<a href="fttb.html" class="button-menu__link">FTTB</a>
</li>
<li class="button-menu__item">
<a href="ftth_mediaconverter.html" class="button-menu__link">FTTH-Медиаконвертер</a>
</li>
<li class="button-menu__item">
<a href="ftth_pon.html" class="button-menu__link">FTTH-PON</a>
</li>
</ul>
</li>
</header>
<!-- <section class="header__switches">
<h1 class="header__title">FTTH-PON</h1>
<p class="header__content">directory on switches</p>
</section> -->
<section class="scroll__button">
<div class="scroll__item" id="top">
<p class="scroll__text"></p>
</div>
</section>
<section class="main">
<div class="main__description">
<div class="main__content">
<!-- <h1 class="main__title">BDCOM</h1> -->
<p class="main__text--content"><b>PON</b> – (Passive Optical Network) что переводится, как пассивная оптическая сеть. Это, по сути, технология абонентского множественного доступа посредством одного волокна с применением временного мультиплексирования (TDM) и разделения частотного трактов приёма/передачи (WDM). <br>
<b>Основная идея архитектуры PON</b> — использование всего одного приёмопередающего модуля в OLT (англ. optical line terminal) для передачи информации множеству абонентских устройств ONT (optical network terminal в терминологии ITU-T), также называемых ONU (optical network unit) в терминологии IEEE и приёма информации от них.
</p> <br>
<p class="main__text--content"><b>Схема подключения</b></p>
<img class="main__img" src="images/bdcom/7.png" width="783px"><br>
<p class="main__text--content"><b>OLT</b> (Optical line termination) – свитч L2, оснащённый Uplink портами (чтобы подключаться к оборудованию L3 "шлюз") и Downlink портами (для создания сети PON). </p> <br>
<img class="main__img" src="images/bdcom/8.png" width="900px"><br>
<p class="main__text--content"><b>Модуль SFP OLT</b> – является специальным трансивером для сетей PON. Важное отличие от стандартных модулей SFP - большая мощность и кодирование канала.</p> <br>
<img class="main__img" src="images/bdcom/11.png" width="425px"><br>
<p class="main__text--content"><b>Сплиттер</b> (Разветвитель) – это устройство, которое работает в разветвительном режиме в направлении "провайдер - клиент" и в смесительном режиме в обратном направлении.</p> <br>
<img class="main__img" src="images/bdcom/10.png" width="625px"><br>
<p class="main__text--content"><b>ONU</b> (Optical Network Unit) – свитч "VLAN" компактного размера. Стандартно ONU оснащён 1-им оптическим 1Г портом (Uplink) и одним 1Г, либо 4-мя 100МБит медными портами (Downlink). Есть модели ONU c 8-ью, 16-ью и 24-мя портами</p> <br>
<img class="main__img" src="images/bdcom/9.png" width="425px"><br><br>
<p class="main__text--content"> <br>
- <b>SFP OLT</b> модули поддерживают работу на дистанцию - 120 км (тип сети "точка-точка"), но поскольку, традиционно сеть PON имеет древовидную структуру (точка–много-точек), то максимальная дистанция работы PON, из-за разветвления на сплиттерах волокна, будет составлять около 20 км.<br>
- Если абонентами <b>PON</b> дерева (64-мя абонентами) будет одновременно скачиваться из Интернета большой объём информации, то на каждого абонента придётся канал в 16 Мбит/с. А если ещё учесть, что не все абоненты Интернетом пользуются одновременно, а те, что пользуются, не потребляют ресурс канала по максимуму, то на абонента даже может приходиться до 50-ти Мбит/с, иногда даже выше.<br>
- Если на одной/нескольких <b>ONU</b> - сигнальный уровень будет очень слабым (< -26 дБм), то появляется большая вероятность возникновения ошибок в пакетной передаче с таких ONU. В приведённом случае OLT растрачивает кванты времени на то, чтобы дать ONU возможность отправить ещё раз пакет. Эти повторные запросы понижают эффективность пропускной способности сети.<br>
- Чтобы определить затухания в линии можно использовать специальные рефлектометры для <b>PON</b> (они существенно дороже обычных), либо оптическими тестерами. Когда сеть уже выстроена, то самым простым решением для проверки уровней сигналов - будет использование специальных команд командного интерфейса OLT-а.<br>
- Каждая операция по обмену информацией между ONU происходит через OLT.<br><br>
<b>GPON (Gigabit Passive Optical Networks)</b> базируется на стандарте ITU-T G.984 <br>
Преимуществами технологии <b>GPON</b> являются:<br>
- полностью пассивная оптическая сеть;<br>
- меньше затраты на электроэнергию;<br>
- оборудование занимает меньше места;<br>
- удобство обслуживания и простота подключения новых абонентов;<br>
- возможность подключения по одному оптическому волокну до 64 абонентов.<br><br>
<b>GEPON (Gigabit Ethernet Passive Optical Networks)</b> стандарт IEEE 802.3ah.<br>
Преимуществами технологии <b>GEPON</b> являются:<br>
- позволяет оптимально использовать волоконно-оптический ресурс кабеля;<br>
- благодаря стандартным механизмам 802.3 ah происходит снижение стоимости
оборудования;<br>
- возможность подключения по одному оптическому волокну до 16 абонентов;<br>
- простота установки и обслуживания;<br>
- передача потокового видео (IGMP Snooping).<br>
Основным преимуществом GEPON является низкая цена по сравнению с
GPON.<br><br>
<b>GPON</b> более удобной решение для сетей большой емкости и протяженности.
Но более сложное и дорогостоящее оборудование окупается только при высокой
степени загрузки.<br>
В <b>GEPON</b>, в отличие от GPON, нет специфических функций поддержки
TDM, синхронизации и защитных переключений, что делает эту технологию самой
экономичной.
</p>
</div>
</div>
</section>
<section class="footer">
<ul class="footer__list">
<li class="footer__item">
<p class="footer__title">Навигация</p>
<a href="radio.html" class="footer__link">Радиоканал</a>
<a href="fttb.html" class="footer__link">FTTB</a>
<a href="ftth_mediaconverter.html" class="footer__link">FTTH-Медиаконвертер</a>
<a href="ftth_pon.html" class="footer__link">FTTH-PON</a>
<!-- <a href="raisecom.html" class="footer__link">Raisecom</a> -->
</li>
</ul>
<!-- <ul class="footer__list">
<li class="footer__item">
<p class="footer__title">Навигация</p>
<a href="bdcom.html" class="footer__link">BDCOM</a>
<a href="edgecore.html" class="footer__link">EdgeCore</a>
<a href="quidway.html" class="footer__link">Quidway</a>
<a href="l3zte.html" class="footer__link">L3-ZTE</a>
<a href="l3cisco.html" class="footer__link">L3-Cisco</a>
</li>
</ul> -->
<div class="footer__social">
<ul class="footer__social--link">
<li class="footer__social--item">
<a href="" class="footer__social--item footer__social--facebook"></a>
</li>
<li class="footer__social--item">
<a href="" class="footer__social--item footer__social--twitter"></a>
</li>
<li class="footer__social--item">
<a href="" class="footer__social--item footer__social--dribbble"></a>
</li>
<li class="footer__social--item">
<a href="" class="footer__social--item footer__social--share"></a>
</li>
</ul>
<p class="footer__copy">Copyright © 2018 shaxqq</p>
</div>
</section>
</body>
</html>
<file_sep>/README.md
# switches
(switchsite)
[https://shaxqq.github.io/switches/]
|
cc609681e511b33ef9df99f335605ad02bb491a4
|
[
"JavaScript",
"HTML",
"Markdown"
] | 3
|
JavaScript
|
shaxqq/switches
|
62306f028e34104d04d9b6f63e8b58d0e96e9968
|
ad46c116fb71c78ca883bea432b4a9000e0dbbc6
|
refs/heads/master
|
<file_sep>=README
C++ Beginner
<file_sep>#include <iostream>
#include <cstring>
using namespace std;
class meo {
public:
double trongluong;
string mausac;
meo();
meo(double tl, string ms) {
trongluong = tl;
mausac = ms;
};
//Ham bat chuot
void batchuot(double tlChuot) {
trongluong = trongluong + tlChuot;
}
};
class chuot {
public:
string loai;
double trongluong;
string mausac;
chuot();
chuot(string loai, double tl, string ms) {
loai = loai;
trongluong = tl;
mausac = ms;
};
};
void main() {
meo meo1(2, "Mau den");
meo meo2(1.5, "Mau den");
meo meo3(3, "Mau xanh");
chuot chuot1("Chuot xa", 0.3, "Den thui");
chuot chuot2("Chuot cong", 0.5, "Den thui");
chuot chuot3("Chuot cong cha ba", 0.8, "Den thui");
meo1.batchuot(chuot1.trongluong);
cout << "Trong luong chuot la: " << meo1.trongluong;
system("pause");
}
|
b786246cea3fdfe112195f8ef3d016f13d6ed000
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
tanngoc93/demo_c_plus_plus
|
46c01677f56243515bd76d056a97513b28e7f7b5
|
baccc943a2804e5e6653dbfe972743419b68ae28
|
refs/heads/master
|
<repo_name>hpRamirez/rdmax<file_sep>/modulos/Modulo.java
package modulos;
import factory.ModuleFactory;
import java.util.List;
public abstract class Modulo
{
protected List<Modelo> listaModelos;
protected List<Vista> listaVistas;
protected Controlador c;
protected ModuleFactory mf;
public Modulo()
{
}
public Modulo(ModuleFactory mf)
{
this.mf = mf;
this.listaModelos = this.mf.crearModelos();
this.listaVistas = this.mf.crearVistas(this.listaModelos);
this.c = this.mf.crearControlador(this.listaModelos, this.listaVistas);
}
public List<Vista> getListaVistas() {
return this.listaVistas;
}
}<file_sep>/examens/controlador/Modificar.java
package examens.controlador;
import interfaces.Comandos;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintStream;
import java.util.List;
import javax.swing.JTextField;
import modulos.Modelo;
import modulos.Vista;
class Modificar
implements ActionListener
{
private List<Modelo> modelos;
private Vista vista;
private Comandos mfc;
public Modificar(List<Modelo> modelos, Vista vista)
{
this.modelos = modelos;
this.vista = vista;
this.vista.agregarAceptarListener(this);
}
public void actionPerformed(ActionEvent e)
{
System.out.println("Modificando historia...");
if (this.vista != null)
this.mfc.ejecutar(new Object[] { getValores() });
else System.out.println("La vista no fue cargada.");
}
public String[] getValores()
{
String[] lista = new String[1];
lista[0] = this.vista.getCampoFecha().getText();
return lista;
}
}<file_sep>/factory/ModuloDentistasFactory.java
package factory;
import dentistas.controlador.DentistaControlador;
import dentistas.modelo.Dentista;
import dentistas.vista.EliminarDentista;
import dentistas.vista.IngresarDentista;
import java.util.ArrayList;
import java.util.List;
import modulos.Controlador;
import modulos.Modelo;
import modulos.Vista;
public class ModuloDentistasFactory
implements ModuleFactory
{
public List<Modelo> crearModelos()
{
List listaModelos = new ArrayList();
Modelo modelo = new Dentista();
listaModelos.add(modelo);
return listaModelos;
}
public List<Vista> crearVistas(List<Modelo> listaModelos)
{
Vista idv = new IngresarDentista((Modelo)listaModelos.get(0));
Vista edv = new EliminarDentista((Modelo)listaModelos.get(0));
Vista mdv = new IngresarDentista((Modelo)listaModelos.get(0));
List listaVistas = new ArrayList();
listaVistas.add(idv);
listaVistas.add(edv);
listaVistas.add(mdv);
return listaVistas;
}
public Controlador crearControlador(List<Modelo> listaModelos, List<Vista> listaVistas)
{
return new DentistaControlador((Modelo)listaModelos.get(0), listaVistas);
}
}<file_sep>/vista/Ingresar.java
package vista;
import interfaces.Observable;
import interfaces.Observador;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import org.javalite.activejdbc.Base;
public class Ingresar extends JFrame
implements Observable
{
private List<Observador> listaObservadores;
private JButton aceptar;
private JPasswordField campoContrasena;
private JComboBox comboBoxDepartamento;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
public Ingresar()
{
initComponents();
this.listaObservadores = new ArrayList();
this.aceptar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae) {
char[] pwd = Ingresar.this.getCampoContrasena().getPassword();
if (ae.getActionCommand().equals("ok")) {
String dpto = (String)Ingresar.this.getComboBoxDepartamento().getSelectedItem();
String pass = String.valueOf(pwd);
try {
Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/rdmax", dpto.toLowerCase(), pass);
Ingresar.this.dispose();
Ingresar.this.campoContrasena.setText("");
Ingresar.this.comboBoxDepartamento.setSelectedIndex(0);
} catch (Exception ex) {
System.err.println("No se pudo conectar a la base de datos, razon: \n" + ex.getMessage());
JOptionPane.showMessageDialog(null, "No se pudo realizarla conexion a la base de datos. \nPor favorcontacte al administrador del sistema.");
System.exit(-1);
}
}
Ingresar.this.notificar();
}
});
}
private void initComponents()
{
this.jLabel1 = new JLabel();
this.jLabel2 = new JLabel();
this.jLabel3 = new JLabel();
this.aceptar = new JButton();
this.comboBoxDepartamento = new JComboBox();
this.campoContrasena = new JPasswordField();
setDefaultCloseOperation(2);
this.jLabel1.setFont(new Font("Tahoma", 0, 14));
this.jLabel1.setText("Departamento:");
this.jLabel2.setFont(new Font("Tahoma", 0, 14));
this.jLabel2.setText("Contraseña:");
this.jLabel3.setFont(new Font("Tahoma", 0, 18));
this.jLabel3.setForeground(new Color(0, 51, 204));
this.jLabel3.setText("RD-Max");
this.aceptar.setActionCommand("ok");
this.aceptar.setText("Aceptar");
this.comboBoxDepartamento.setModel(new DefaultComboBoxModel(new String[] { "Seleccione departamento:", "Laboratorio", "Radiologia", "Recepcion", "Documentacion", "Fotografia", "Principal" }));
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(this.jLabel1).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.comboBoxDepartamento, -2, 192, -2)).addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(this.jLabel2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.campoContrasena, -2, 192, -2)))).addGroup(layout.createSequentialGroup().addGap(119, 119, 119).addComponent(this.aceptar))).addContainerGap()).addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGap(0, 0, 32767).addComponent(this.jLabel3).addGap(121, 121, 121)));
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap(-1, 32767).addComponent(this.jLabel3).addGap(18, 18, 18).addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel1).addComponent(this.comboBoxDepartamento, -2, -1, -2)).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel2).addComponent(this.campoContrasena, -2, -1, -2)).addGap(23, 23, 23).addComponent(this.aceptar).addContainerGap()));
pack();
}
public static void main(String[] args)
{
try
{
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Ingresar.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(Ingresar.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Ingresar.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(Ingresar.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable()
{
public void run() {
new Ingresar().setVisible(true);
}
});
}
public JPasswordField getCampoContrasena()
{
return this.campoContrasena;
}
public JComboBox getComboBoxDepartamento() {
return this.comboBoxDepartamento;
}
public void agregarObservador(Observador o)
{
this.listaObservadores.add(o);
}
public void removerObservador(Observador o)
{
throw new UnsupportedOperationException("Not supported yet.");
}
public List getListaObservadores()
{
return this.listaObservadores;
}
public void notificar()
{
Iterator it = this.listaObservadores.iterator();
while (it.hasNext())
((Observador)it.next()).update(this);
}
}<file_sep>/facturas/comandos/ModificarFacturaComando.java
package facturas.comandos;
import facturas.modelo.Factura;
import interfaces.Comandos;
import java.io.PrintStream;
import modulos.Modelo;
public class ModificarFacturaComando
implements Comandos
{
private Modelo modelo;
public ModificarFacturaComando(Modelo modelo)
{
this.modelo = modelo;
}
public void ejecutar(Object[] obj)
{
String[] lista = (String[])obj[0];
if (this.modelo.existe(lista[0])) {
Factura.update("nro = ?, fecha = ?, lugar = ?, condiciones_pago = ?, datos_adicionales = ?, convenio = ?, entrega_a = ?", "nro = ?", new Object[] { lista[0], lista[1], lista[2], lista[3], lista[4], lista[5], lista[6], lista[0] });
}
else
{
System.out.println("no existe una historia con ese codigo.");
}
}
}<file_sep>/modulos/Modelo.java
package modulos;
import java.util.Vector;
import javax.swing.JTable;
public abstract interface Modelo
{
public abstract boolean existe(Object paramObject);
public abstract boolean ingresar(Object paramObject);
public abstract void ingresarData(int paramInt, Vector paramVector);
public abstract void eliminar(Object paramObject);
public abstract void modificar(Object paramObject);
public abstract void modificar(Object paramObject, JTable paramJTable);
}<file_sep>/factory/ModuloFacturaFactory.java
package factory;
import facturas.controlador.FacturaControlador;
import facturas.modelo.Contenido;
import facturas.modelo.Factura;
import facturas.vista.EliminarFactura;
import facturas.vista.IngresarFactura;
import facturas.vista.ModificarFactura;
import java.util.ArrayList;
import java.util.List;
import modulos.Controlador;
import modulos.Modelo;
import modulos.Vista;
public class ModuloFacturaFactory
implements ModuleFactory
{
public List<Modelo> crearModelos()
{
List listaModelos = new ArrayList();
Modelo f = new Factura();
Modelo c = new Contenido();
listaModelos.add(f);
listaModelos.add(c);
return listaModelos;
}
public List<Vista> crearVistas(List<Modelo> listaModelos)
{
Vista idv = new IngresarFactura((Modelo)listaModelos.get(0));
Vista edv = new EliminarFactura((Modelo)listaModelos.get(0));
Vista mdv = new ModificarFactura((Modelo)listaModelos.get(0));
List listaVistas = new ArrayList();
listaVistas.add(idv);
listaVistas.add(edv);
listaVistas.add(mdv);
return listaVistas;
}
public Controlador crearControlador(List<Modelo> listaModelos, List<Vista> listaVistas)
{
return new FacturaControlador(listaModelos, listaVistas);
}
}<file_sep>/vista/AppView.java
package vista;
import dentistas.vista.EliminarDentista;
import dentistas.vista.IngresarDentista;
import examens.vista.Examenes;
import examens.vista.ModificarExamen;
import facturas.vista.EliminarFactura;
import facturas.vista.IngresarFactura;
import facturas.vista.ModificarFactura;
import facturas.vista.paneles.PanelFactura;
import interfaces.Observable;
import interfaces.Observador;
import interfaces.VistaAdapter;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import misc.Respaldo;
import modulos.Modulo;
import pacientes.vista.EliminarPaciente;
import pacientes.vista.IngresarPaciente;
import pacientes.vista.paneles.PanelControlExamenes;
import personal.vista.EliminarPersonal;
import personal.vista.IngresarPersonal;
public class AppView extends JFrame
implements Observador
{
private EliminarDentista ed;
private IngresarDentista id;
private IngresarDentista md;
private IngresarPaciente ip;
private EliminarPaciente ep;
private IngresarPaciente mp;
private EliminarFactura ef;
private IngresarFactura inf;
private ModificarFactura mf;
private IngresarPersonal iper;
private EliminarPersonal eper;
private VistaAdapter ie;
private ModificarExamen me;
private Ingresar ing;
private List<Modulo> modulos;
private JMenu dentistasMenu;
private JMenuItem eliminarDentistasMenu;
private JMenuItem eliminarFacturasMenu;
private JMenuItem eliminarPacientesMenu;
private JMenuItem eliminarPersonalMenu;
private JMenu examensMenu;
private JMenu facturasMenu;
private JMenuItem ingresarDentistasMenu;
private JMenuItem ingresarExamensMenu;
private JMenuItem ingresarFacturasMenu;
private JMenuItem ingresarPacientesMenu;
private JMenuItem ingresarPersonalMenu;
private JButton jButton1;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JMenu jMenu1;
private JMenuBar jMenuBar1;
private JMenuItem jMenuItem1;
private JMenuItem modificarPacientesMenu;
private JMenu pacientesMenu;
private JMenu personalMenu;
private JMenu respaldoMenu;
public AppView()
{
initComponents();
}
public AppView(Ingresar ing, Modulo[] modulos) {
this.modulos = Arrays.asList(modulos);
this.ing = ing;
this.ing.agregarObservador(this);
List vistasDentistas = ((Modulo)this.modulos.get(0)).getListaVistas();
this.id = ((IngresarDentista)vistasDentistas.get(0));
this.ed = ((EliminarDentista)vistasDentistas.get(1));
this.md = ((IngresarDentista)vistasDentistas.get(2));
List vistasExamens = ((Modulo)this.modulos.get(2)).getListaVistas();
this.ie = ((Examenes)vistasExamens.get(0));
this.me = ((ModificarExamen)vistasExamens.get(1));
List vistasPacientes = ((Modulo)this.modulos.get(1)).getListaVistas();
this.ip = ((IngresarPaciente)vistasPacientes.get(0));
this.ep = ((EliminarPaciente)vistasPacientes.get(1));
this.mp = ((IngresarPaciente)vistasPacientes.get(2));
List vistasFacturas = ((Modulo)this.modulos.get(3)).getListaVistas();
this.inf = ((IngresarFactura)vistasFacturas.get(0));
this.ef = ((EliminarFactura)vistasFacturas.get(1));
this.mf = ((ModificarFactura)vistasFacturas.get(2));
List vistasPersonal = ((Modulo)this.modulos.get(4)).getListaVistas();
this.iper = ((IngresarPersonal)vistasPersonal.get(0));
this.eper = ((EliminarPersonal)vistasPersonal.get(1));
this.ip.getPanelControlExamenes().setObservable((Observable)this.ie);
this.inf.getPanelFactura().setObservable((Observable)this.ie);
initComponents();
setMenusEnabled(false);
}
private void initComponents()
{
this.jMenu1 = new JMenu();
this.jButton1 = new JButton();
this.jLabel1 = new JLabel();
this.jLabel2 = new JLabel();
this.jLabel3 = new JLabel();
this.jMenuBar1 = new JMenuBar();
this.examensMenu = new JMenu();
this.ingresarExamensMenu = new JMenuItem();
this.pacientesMenu = new JMenu();
this.ingresarPacientesMenu = new JMenuItem();
this.eliminarPacientesMenu = new JMenuItem();
this.modificarPacientesMenu = new JMenuItem();
this.dentistasMenu = new JMenu();
this.ingresarDentistasMenu = new JMenuItem();
this.eliminarDentistasMenu = new JMenuItem();
this.facturasMenu = new JMenu();
this.ingresarFacturasMenu = new JMenuItem();
this.eliminarFacturasMenu = new JMenuItem();
this.personalMenu = new JMenu();
this.ingresarPersonalMenu = new JMenuItem();
this.eliminarPersonalMenu = new JMenuItem();
this.respaldoMenu = new JMenu();
this.jMenuItem1 = new JMenuItem();
this.jMenu1.setText("jMenu1");
setDefaultCloseOperation(3);
setTitle("Principal");
this.jButton1.setText("Ingresar al Sistema");
this.jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.ingresarAlSistema(evt);
}
});
this.jLabel1.setFont(new Font("Tahoma", 0, 36));
this.jLabel1.setForeground(new Color(0, 0, 204));
this.jLabel1.setText("RD-MAX");
this.jLabel2.setText("Departamento de");
this.jLabel3.setText("jLabel3");
this.examensMenu.setText("Examenes");
this.ingresarExamensMenu.setText("Ingresar");
this.ingresarExamensMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.ingresarExamen(evt);
}
});
this.examensMenu.add(this.ingresarExamensMenu);
this.jMenuBar1.add(this.examensMenu);
this.pacientesMenu.setText("Pacientes");
this.ingresarPacientesMenu.setText("Ingresar");
this.ingresarPacientesMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.ingresarPaciente(evt);
}
});
this.pacientesMenu.add(this.ingresarPacientesMenu);
this.eliminarPacientesMenu.setText("Eliminar");
this.eliminarPacientesMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.eliminarPaciente(evt);
}
});
this.pacientesMenu.add(this.eliminarPacientesMenu);
this.modificarPacientesMenu.setText("Modificar/Consultar");
this.modificarPacientesMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.modificarPaciente(evt);
}
});
this.pacientesMenu.add(this.modificarPacientesMenu);
this.jMenuBar1.add(this.pacientesMenu);
this.dentistasMenu.setText("Dentistas");
this.ingresarDentistasMenu.setText("Ingresar/Modificar");
this.ingresarDentistasMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.ingresarDentista(evt);
}
});
this.dentistasMenu.add(this.ingresarDentistasMenu);
this.eliminarDentistasMenu.setText("Eliminar");
this.eliminarDentistasMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.eliminarDentista(evt);
}
});
this.dentistasMenu.add(this.eliminarDentistasMenu);
this.jMenuBar1.add(this.dentistasMenu);
this.facturasMenu.setText("Facturas");
this.ingresarFacturasMenu.setText("Ingresar");
this.ingresarFacturasMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.ingresarFactura(evt);
}
});
this.facturasMenu.add(this.ingresarFacturasMenu);
this.eliminarFacturasMenu.setText("Eliminar");
this.eliminarFacturasMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.eliminarFactura(evt);
}
});
this.facturasMenu.add(this.eliminarFacturasMenu);
this.jMenuBar1.add(this.facturasMenu);
this.personalMenu.setText("Personal");
this.ingresarPersonalMenu.setText("Ingresar");
this.ingresarPersonalMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.ingresarPersonal(evt);
}
});
this.personalMenu.add(this.ingresarPersonalMenu);
this.eliminarPersonalMenu.setText("Eliminar");
this.eliminarPersonalMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.eliminarPersonal(evt);
}
});
this.personalMenu.add(this.eliminarPersonalMenu);
this.jMenuBar1.add(this.personalMenu);
this.respaldoMenu.setText("Extras");
this.jMenuItem1.setText("Repaldar Base de Datos");
this.jMenuItem1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppView.this.jMenuItem1ActionPerformed(evt);
}
});
this.respaldoMenu.add(this.jMenuItem1);
this.jMenuBar1.add(this.respaldoMenu);
setJMenuBar(this.jMenuBar1);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGap(0, 247, 32767).addComponent(this.jButton1, -2, 144, -2)).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(96, 96, 96).addComponent(this.jLabel1)).addGroup(layout.createSequentialGroup().addGap(99, 99, 99).addComponent(this.jLabel2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jLabel3, -2, 68, -2))).addGap(0, 110, 32767))).addContainerGap()));
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(88, 88, 88).addComponent(this.jLabel1).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel2).addComponent(this.jLabel3)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 74, 32767).addComponent(this.jButton1).addContainerGap()));
pack();
}
private void ingresarDentista(ActionEvent evt) {
this.id.setVisible(true);
}
private void eliminarDentista(ActionEvent evt) {
this.ed.setVisible(true);
}
private void ingresarPaciente(ActionEvent evt) {
this.ip.setVisible(true);
}
private void eliminarPaciente(ActionEvent evt) {
this.ep.setVisible(true);
}
private void modificarPaciente(ActionEvent evt) {
this.mp.setVisible(true);
}
private void ingresarFactura(ActionEvent evt) {
this.inf.setVisible(true);
}
private void eliminarFactura(ActionEvent evt) {
this.ef.setVisible(true);
}
private void ingresarExamen(ActionEvent evt) {
this.ie.setVisible(true);
}
private void ingresarAlSistema(ActionEvent evt) {
this.ing.setVisible(true);
}
private void ingresarPersonal(ActionEvent evt) {
this.iper.setVisible(true);
}
private void eliminarPersonal(ActionEvent evt) {
this.eper.setVisible(true);
}
private void jMenuItem1ActionPerformed(ActionEvent evt) {
try {
new Respaldo().guardar();
JOptionPane.showMessageDialog(null, "Base de datos Respaldada.");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "La base de datos no pudo ser respaldada.");
}
}
public static void main(String[] args)
{
try
{
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
catch (ClassNotFoundException ex) {
Logger.getLogger(AppView.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(AppView.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(AppView.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(AppView.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new AppView().setVisible(true);
}
});
}
public JMenuItem getEliminarDentistasMenu()
{
return this.eliminarDentistasMenu;
}
public JMenuItem getEliminarFacturasMenu() {
return this.eliminarFacturasMenu;
}
public JMenuItem getEliminarPacientesMenu() {
return this.eliminarPacientesMenu;
}
public JMenuItem getIngresarDentistasMenu() {
return this.ingresarDentistasMenu;
}
public JMenuItem getIngresarExamensMenu() {
return this.ingresarExamensMenu;
}
public JMenuItem getIngresarFacturasMenu() {
return this.ingresarFacturasMenu;
}
public JMenuItem getIngresarPacientesMenu() {
return this.ingresarPacientesMenu;
}
public JMenuItem getModificarPacientesMenu() {
return this.modificarPacientesMenu;
}
public void update(Observable obs)
{
setMenusEnabled(true);
}
private void setMenusEnabled(boolean b) {
this.dentistasMenu.setEnabled(b);
this.pacientesMenu.setEnabled(b);
this.examensMenu.setEnabled(b);
this.respaldoMenu.setEnabled(b);
this.facturasMenu.setEnabled(b);
this.personalMenu.setEnabled(b);
}
}<file_sep>/pacientes/comandos/ModificarPacienteComando.java
package pacientes.comandos;
import interfaces.Comandos;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import modulos.Modelo;
import pacientes.modelo.Paciente;
public class ModificarPacienteComando
implements Comandos
{
private Modelo modelo;
public ModificarPacienteComando(Modelo modelo)
{
this.modelo = modelo;
}
public void ejecutar(Object[] obj)
{
Map l = (Map)obj[0];
String ci = (String)l.get("cedula");
if (this.modelo.existe(ci)) {
List attrs = Paciente.attributes();
Iterator it = attrs.iterator();
while (it.hasNext()) {
String s = (String)it.next();
Paciente.update(s + " = ?", "cedula = ?", new Object[] { l.get(s), ci });
}
} else {
System.out.println("no existe un dentista con esa cedula.");
}
}
}<file_sep>/pacientes/controlador/Modificar.java
package pacientes.controlador;
import examens.modelo.Examen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.sql.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.text.JTextComponent;
import modulos.Modelo;
import modulos.Vista;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;
import pacientes.modelo.Identificacion;
import pacientes.modelo.Intervencion;
import pacientes.modelo.Paciente;
import pacientes.vista.paneles.PanelInformacionGeneral;
import pacientes.vista.paneles.PanelIntervenciones;
import reflection.ListaAtributos;
class Modificar extends FocusAdapter
implements ActionListener
{
private List<Modelo> modelos;
private Vista vista;
public Modificar(List<Modelo> modelos, Vista vista)
{
this.modelos = modelos;
this.vista = vista;
this.vista.agregarAceptarListener(this);
this.vista.agregarAceptarListener(this);
this.vista.agregarCedulaFocusListener(this);
}
private Map<String, String> extraerData(Object p)
{
ListaAtributos la = new ListaAtributos(p);
return la.diccionarioBDVista();
}
public void actionPerformed(ActionEvent e)
{
System.out.println("Modificando paciente: ");
if (this.vista != null) {
String cedula = this.vista.getPanelInformacionGeneral().getCampoCedula().getText();
actualizarPaciente(this.vista.getPanelInformacionGeneral(), cedula, new Modelo[0]);
actualizarIdentificacion(this.vista.getPanelIdentificacion(), cedula);
actualizarIntervenciones(this.vista.getPanelIntervenciones(), cedula); } else {
System.out.println("La vista no fue cargada.");
}
}
public void focusLost(FocusEvent e) {
llenarInformacionGeneral();
llenarIdentificacion();
llenarControlExamenes();
llenarIntervenciones();
}
private void actualizarPaciente(JPanel panel, String cedula, Modelo[] modelos) {
System.out.println("metodo actualizar:");
ListaAtributos la = new ListaAtributos(panel);
la.listarAtributos();
Map lista = la.getDiccionarioBD();
Model p = Paciente.findFirst("cedula = ?", new Object[] { cedula });
Long pacientes_id = p.getLongId();
lista.put("id", String.valueOf(pacientes_id));
actualizarData(null, lista, new Modelo[] { (Modelo)p });
}
private void actualizarIdentificacion(JPanel panel, String cedula) {
System.out.println("metodo actualizar:");
ListaAtributos la = new ListaAtributos(panel);
la.listarAtributos();
Map lista = la.getDiccionarioBD();
Model p = Paciente.findFirst("cedula = ?", new Object[] { cedula });
Long pacientes_id = p.getLongId();
Model ident = Identificacion.findFirst("pacientes_id = ?", new Object[] { pacientes_id });
lista.put("pacientes_id", String.valueOf(pacientes_id));
System.out.println("id del paciente para identificacion: " + (String)lista.get("pacientes_id"));
actualizarData(null, lista, new Modelo[] { (Modelo)ident });
}
private void llenar(Object src, Model modelo, Map<String, String> lista, int i) {
Iterator it = lista.entrySet().iterator();
if (modelo == null) {
JOptionPane.showMessageDialog(null, "no existe paciente alguno con esa cedula.");
}
else {
Class clase = src.getClass();
while (it.hasNext())
try {
String nombreCampo = (String)((Map.Entry)it.next()).getKey();
String claseCampo = null;
System.out.println("campo: " + nombreCampo);
if (((!nombreCampo.equals("aceptar") ? 1 : 0) & (!nombreCampo.equals("opcional") ? 1 : 0) & (!nombreCampo.equals("panel_foto") ? 1 : 0) & (!nombreCampo.equals("obs") ? 1 : 0) & (!nombreCampo.equals("abrir_carpeta_paciente") ? 1 : 0) & (!nombreCampo.contains("tabla_") ? 1 : 0) & (!nombreCampo.contains("diagnostico") ? 1 : 0)) != 0)
{
Object valor = modelo.get(nombreCampo);
Field campo = clase.getDeclaredField((String)lista.get(nombreCampo));
campo.setAccessible(true);
claseCampo = campo.get(src).getClass().toString();
System.out.println(nombreCampo + " " + (String)lista.get(nombreCampo) + " " + valor + " " + valor.getClass() + " " + claseCampo);
if ((valor instanceof Date & claseCampo.contains("JText")))
((JTextComponent)campo.get(src)).setText(desconvertir((Date)valor));
else if ((valor instanceof String & claseCampo.contains("JText")))
((JTextComponent)campo.get(src)).setText((String)valor);
else if ((valor instanceof Boolean & (claseCampo.contains("JRadioButton") | claseCampo.contains("CheckBox"))))
{
((JToggleButton)campo.get(src)).getModel().setSelected(((Boolean)valor).booleanValue());
}
campo.setAccessible(false);
} else if (nombreCampo.contains("tabla_")) {
Field campo = clase.getDeclaredField((String)lista.get(nombreCampo));
campo.setAccessible(true);
claseCampo = campo.get(src).getClass().toString();
if (claseCampo.contains("JTable")) {
if ((modelo instanceof Examen)) {
String examen = (String)modelo.get("examen");
String observacion = (String)modelo.get("observacion");
((JTable)campo.get(src)).setValueAt(examen, i, 0);
((JTable)campo.get(src)).setValueAt(observacion, i, 1);
}if ((modelo instanceof Intervencion)) {
String fecha = (String)modelo.get("fecha");
String tp = (String)modelo.get("tp");
String tr = (String)modelo.get("tr");
((JTable)campo.get(src)).setValueAt(fecha, i, 0);
((JTable)campo.get(src)).setValueAt(tr, i, 1);
((JTable)campo.get(src)).setValueAt(tp, i, 2);
}
}
}
} catch (NoSuchFieldException ex) {
Logger.getLogger(Modificar.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(Modificar.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException iae) {
Logger.getLogger(Modificar.class.getName()).log(Level.SEVERE, null, iae);
} catch (IllegalAccessException ex) {
Logger.getLogger(Modificar.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void llenar(Object src, LazyList data, Map<String, String> lista)
{
Iterator it = data.iterator();
int fila = 0;
while (it.hasNext()) {
llenar(src, (Model)it.next(), lista, fila);
fila++;
}
}
private void llenarInformacionGeneral() {
Object src = this.vista.getPanelInformacionGeneral();
String cedula = this.vista.getPanelInformacionGeneral().getCampoCedula().getText();
Map lista = extraerData((JPanel)src);
Model p = Paciente.findFirst("cedula = ?", new Object[] { cedula });
Object fecha = p.get("fecha_nacimiento");
System.out.println("fecha de nacimiento en cuestion: " + (String)lista.get("fecha_nacimiento"));
llenar(src, p, lista, -1);
}
private void llenarIdentificacion() {
try {
Object src = this.vista.getPanelIdentificacion();
String cedula = this.vista.getPanelInformacionGeneral().getCampoCedula().getText();
Map lista = extraerData((JPanel)src);
Model paciente = Paciente.findFirst("cedula = ?", new Object[] { cedula });
Long id = paciente.getLongId();
Model ident = Identificacion.findById(id);
llenar(src, ident, lista, -1); } catch (Exception ex) {
System.out.println("Hubo problemas en el proceso de llenado.");
}
}
private void llenarControlExamenes() { Object src = this.vista.getPanelControlExamenes();
String cedula = this.vista.getPanelInformacionGeneral().getCampoCedula().getText();
Map lista = extraerData((JPanel)src);
Model paciente = Paciente.findFirst("cedula = ?", new Object[] { cedula });
Long pacientes_id = paciente.getLongId();
System.out.println("id del paciente: " + pacientes_id);
LazyList examens = Examen.find("pacientes_id = ?", new Object[] { pacientes_id });
llenar(src, examens, lista); }
private void llenarIntervenciones()
{
Object src = this.vista.getPanelIntervenciones();
String cedula = this.vista.getPanelInformacionGeneral().getCampoCedula().getText();
Map lista = extraerData((JPanel)src);
Model paciente = Paciente.findFirst("cedula = ?", new Object[] { cedula });
Long pacientes_id = paciente.getLongId();
System.out.println("id del paciente: " + pacientes_id);
LazyList examens = Intervencion.find("pacientes_id = ?", new Object[] { pacientes_id });
llenar(src, examens, lista);
}
private void actualizarData(JTable tabla, Map<String, String> lista, Modelo[] lista2) {
for (Modelo m : lista2) {
System.out.println("clase actualizarData(a, b): " + m.getClass());
try {
if ((m instanceof Intervencion))
m.modificar(lista, tabla);
else {
m.modificar(lista);
}
}
catch (Exception ex)
{
System.out.println("ocurrio un error en el ingreso a la base de datos");
ex.printStackTrace();
}
}
}
private String actualizarData(JPanel panel, Modelo[] lista) {
ListaAtributos la = new ListaAtributos(panel);
la.listarAtributos();
Map dict = la.getDiccionarioBD();
for (Modelo m : lista) {
System.out.println("clase actualizarData(a, b): " + m.getClass());
try {
if ((m instanceof Paciente)) {
m.modificar(dict);
}
}
catch (Exception ex)
{
System.out.println("ocurrio un error en el ingreso a la base de datos");
ex.printStackTrace();
}
}
return (String)dict.get("cedula");
}
private String actualizarData(int pacientes_id, JPanel panel, Modelo[] lista) {
ListaAtributos la = new ListaAtributos(panel);
la.listarAtributos();
Map dict = la.getDiccionarioBD();
dict.put("pacientes_id", String.valueOf(pacientes_id));
for (Modelo m : lista)
try {
if ((m instanceof Examen)) {
System.out.println("Ingresando data a la tabla de examenes...");
((Examen)m).ingresarData(pacientes_id, la.getDataFromTabla());
} else {
m.ingresar(dict);
}la.clear();
} catch (Exception ex) {
System.out.println("ocurrio un error en el ingreso a la base de datos");
ex.printStackTrace();
}
return (String)dict.get("cedula");
}
private String desconvertir(Date valor) {
String s = valor.toString();
String[] l = s.split("-");
return l[2] + "/" + l[1] + "/" + l[0];
}
private void actualizarIntervenciones(JPanel panelIntervenciones, String cedula) {
System.out.println("metodo actualizar:");
ListaAtributos la = new ListaAtributos(panelIntervenciones);
la.listarAtributos();
JTable table = ((PanelIntervenciones)panelIntervenciones).getTabla();
Map lista = la.getDiccionarioBD();
Model p = Paciente.findFirst("cedula = ?", new Object[] { cedula });
Long pacientes_id = p.getLongId();
Model interv = Intervencion.findFirst("pacientes_id = ?", new Object[] { pacientes_id });
lista.put("pacientes_id", String.valueOf(pacientes_id));
System.out.println("id del paciente para intervencion: " + (String)lista.get("pacientes_id"));
actualizarData(table, lista, new Modelo[] { (Modelo)interv });
}
}<file_sep>/interfaces/BaseDatos.java
package interfaces;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public abstract class BaseDatos
implements Observable
{
public static String url = "jdbc:mysql://localhost/rdmax";
private static final String pass = "<PASSWORD>";
private static final String usr = "root";
public abstract boolean conectar(String paramString);
public abstract void cerrar();
public abstract Connection getCon();
public abstract ResultSet ejecutar(String paramString);
public abstract String[] getCargos();
public abstract String[] getDepartamentos();
public abstract int getID(String paramString);
public abstract void mostrarErrores(SQLException paramSQLException);
public Properties crearProps()
{
Properties params = new Properties();
params.setProperty("user", "root");
params.setProperty("password", "<PASSWORD>");
params.setProperty("autoReconnect", "true");
params.setProperty("maxReconnects", "3");
return params;
}
}<file_sep>/misc/Recuperacion.java
package misc;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class Recuperacion
{
private Process p;
private ProcessBuilder pb;
public Recuperacion()
{
this.pb = new ProcessBuilder(new String[] { "mysql", "-uroot", "-prdmax", "rdmax", "< rdmax.sql" });
}
public void restaurar() {
try {
File db = new File("rdmax.sql");
if (db.exists()) {
this.p = this.pb.start();
InputStream is = this.p.getInputStream();
InputStream err = this.p.getErrorStream();
new RecuperacionStream(is).start();
new RecuperacionStream(err).start();
int retVal = this.p.waitFor();
System.out.println("Exit code: " + retVal);
is.close();
err.close();
this.p.destroy();
} else {
JOptionPane.showMessageDialog(null, "La base de datos no ha sido respaldada todavia.");
}
} catch (InterruptedException ex) {
Logger.getLogger(Respaldo.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Respaldo.class.getName()).log(Level.SEVERE, null, ex);
}
}
class RecuperacionStream extends Thread
{
private InputStream is;
private FileWriter fw;
RecuperacionStream(InputStream is)
{
this.is = is;
}
public void run()
{
try {
InputStreamReader isr = new InputStreamReader(this.is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(line);
} catch (IOException ex) {
Logger.getLogger(Recuperacion.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}<file_sep>/factory/ModuloPersonalFactory.java
package factory;
import java.util.ArrayList;
import java.util.List;
import modulos.Controlador;
import modulos.Modelo;
import modulos.Vista;
import personal.controlador.PersonalControlador;
import personal.modelo.Personal;
import personal.vista.EliminarPersonal;
import personal.vista.IngresarPersonal;
public class ModuloPersonalFactory
implements ModuleFactory
{
public List<Modelo> crearModelos()
{
List listaModelos = new ArrayList();
listaModelos.add(new Personal());
return listaModelos;
}
public List<Vista> crearVistas(List<Modelo> listaModelos)
{
Vista idv = new IngresarPersonal((Modelo)listaModelos.get(0));
Vista edv = new EliminarPersonal((Modelo)listaModelos.get(0));
Vista mdv = new IngresarPersonal((Modelo)listaModelos.get(0));
List listaVistas = new ArrayList();
listaVistas.add(idv);
listaVistas.add(edv);
listaVistas.add(mdv);
return listaVistas;
}
public Controlador crearControlador(List<Modelo> listaModelos, List<Vista> listaVistas)
{
return new PersonalControlador(listaModelos, listaVistas);
}
}<file_sep>/modulos/Controlador.java
package modulos;
import java.util.List;
public abstract interface Controlador
{
public abstract List<Vista> getVistas();
}<file_sep>/examens/controlador/Ingresar.java
package examens.controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintStream;
import java.util.List;
import modulos.Modelo;
import modulos.Vista;
import reflection.ListaAtributos;
class Ingresar
implements ActionListener
{
private List<Modelo> modelos;
private Vista vista;
public Ingresar(List<Modelo> modelos, Vista vista)
{
this.modelos = modelos;
this.vista = vista;
}
public void actionPerformed(ActionEvent e)
{
if (this.vista != null) {
System.out.println("actionPerformed de la clase ExamenControlador");
}
else
System.out.println("La vista no fue cargada.");
}
private void agregarData(Object panel, Modelo[] lista) {
ListaAtributos la = new ListaAtributos(panel);
la.listarAtributos();
for (Modelo m : lista)
m.ingresar(la.getDiccionarioBD());
}
}<file_sep>/modulos/ModuloPersonal.java
package modulos;
import factory.ModuleFactory;
public class ModuloPersonal extends Modulo
{
public ModuloPersonal(ModuleFactory mf)
{
super(mf);
}
}<file_sep>/pacientes/vista/EliminarPaciente.java
package pacientes.vista;
import interfaces.VistaAdapter;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import modulos.Modelo;
public class EliminarPaciente extends VistaAdapter
{
private Modelo p;
private JButton aceptar;
private JTextField campoCedula;
private JLabel cedulaLabel;
public EliminarPaciente()
{
initComponents();
}
public EliminarPaciente(Modelo p) {
this.p = p;
setTitle("Eliminar paciente de la base de datos");
initComponents();
}
public void agregarAceptarListener(ActionListener al)
{
this.aceptar.addActionListener(al);
}
private void initComponents()
{
this.cedulaLabel = new JLabel();
this.campoCedula = new JTextField();
this.aceptar = new JButton();
setDefaultCloseOperation(2);
this.cedulaLabel.setText("C.I.:");
this.campoCedula.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
EliminarPaciente.this.campoCedulaActionPerformed(evt);
}
});
this.aceptar.setText("Aceptar");
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(this.cedulaLabel).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.campoCedula, -2, 168, -2)).addGroup(layout.createSequentialGroup().addGap(71, 71, 71).addComponent(this.aceptar))).addContainerGap(-1, 32767)));
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.campoCedula, -2, -1, -2).addComponent(this.cedulaLabel)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 11, 32767).addComponent(this.aceptar).addContainerGap()));
pack();
}
private void campoCedulaActionPerformed(ActionEvent evt)
{
}
public static void main(String[] args)
{
try
{
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
catch (ClassNotFoundException ex) {
Logger.getLogger(EliminarPaciente.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(EliminarPaciente.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(EliminarPaciente.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(EliminarPaciente.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable()
{
public void run() {
new EliminarPaciente().setVisible(true);
}
});
}
public JButton getAceptar()
{
return this.aceptar;
}
public JTextField getCampoCedula()
{
return this.campoCedula;
}
}<file_sep>/misc/ResultSetTableModelActiveJDBC.java
package misc;
import javax.swing.table.AbstractTableModel;
import org.javalite.activejdbc.Model;
public class ResultSetTableModelActiveJDBC extends AbstractTableModel
{
private Model modelo;
public ResultSetTableModelActiveJDBC(Model modelo)
{
this.modelo = modelo;
}
public String getColumnName(int columnIndex)
{
return null;
}
public int getRowCount() {
throw new UnsupportedOperationException("Not supported yet.");
}
public int getColumnCount()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public Object getValueAt(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
public static void main(String[] h)
{
}
}<file_sep>/activejdbc_models.properties
dentistas.modelo.Dentista
examens.modelo.Examen
facturas.modelo.Contenido
facturas.modelo.Factura
modelo.Atiende
modelo.Cdentista
modelo.Paga
pacientes.modelo.Acomp
pacientes.modelo.Asenc
pacientes.modelo.Exclnc
pacientes.modelo.Identificacion
pacientes.modelo.Intervencion
pacientes.modelo.Paciente
personal.modelo.Personal
<file_sep>/examens/controlador/ExamenControlador.java
package examens.controlador;
import java.util.List;
import modulos.Controlador;
import modulos.Modelo;
import modulos.Vista;
public class ExamenControlador
implements Controlador
{
List<Modelo> modelos;
Ingresar ingresar;
Eliminar eliminar;
Modificar modificar;
List<Vista> vistas;
public ExamenControlador(List<Modelo> modelos, List<Vista> vistas)
{
this.modelos = modelos;
this.vistas = vistas;
this.ingresar = new Ingresar(modelos, (Vista)vistas.get(0));
this.modificar = new Modificar(modelos, (Vista)vistas.get(1));
}
public List<Vista> getVistas()
{
return this.vistas;
}
}<file_sep>/interfaces/SelectoresPanel.java
package interfaces;
import java.util.ArrayList;
import javax.swing.JCheckBox;
public abstract interface SelectoresPanel
{
public abstract ArrayList<JCheckBox> getListaElementos();
}<file_sep>/dentistas/comandos/IngresarDentistaComando.java
package dentistas.comandos;
import interfaces.Comandos;
import java.io.PrintStream;
import modulos.Modelo;
public class IngresarDentistaComando
implements Comandos
{
private Modelo modelo;
public IngresarDentistaComando(Modelo modelo)
{
this.modelo = modelo;
}
public void ejecutar(Object[] obj)
{
System.out.println(obj[0].getClass());
String[] lista = (String[])obj[0];
if (!this.modelo.existe(lista[2])) {
System.out.println("Guardando registro:");
this.modelo.ingresar(lista); } else {
System.out.println("ya existe un dentista con esa cedula.");
}
}
}<file_sep>/interfaces/Observador.java
package interfaces;
public abstract interface Observador
{
public abstract void update(Observable paramObservable);
}<file_sep>/personal/controlador/PersonalControlador.java
package personal.controlador;
import java.util.List;
import modulos.Controlador;
import modulos.Modelo;
import modulos.Vista;
public class PersonalControlador
implements Controlador
{
List<Modelo> modelos;
Vista idv;
Vista edv;
Vista mdv;
Ingresar ingresar;
Eliminar eliminar;
List<Vista> vistas;
public PersonalControlador(List<Modelo> modelos, List<Vista> vistas)
{
this.modelos = modelos;
this.vistas = vistas;
this.ingresar = new Ingresar((Modelo)this.modelos.get(0), (Vista)this.vistas.get(0));
this.eliminar = new Eliminar((Modelo)this.modelos.get(0), (Vista)this.vistas.get(1));
}
public List<Vista> getVistas()
{
return this.vistas;
}
}<file_sep>/pacientes/vista/IngresarPaciente.java
package pacientes.vista;
import interfaces.VistaAdapter;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.FocusListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import modulos.Modelo;
import pacientes.vista.paneles.PanelControlExamenes;
import pacientes.vista.paneles.PanelExamenClinico;
import pacientes.vista.paneles.PanelIdentificacion;
import pacientes.vista.paneles.PanelInformacionGeneral;
import pacientes.vista.paneles.PanelIntervenciones;
public class IngresarPaciente extends VistaAdapter
{
private Modelo modelo;
private JScrollPane jScrollPane1;
private JTabbedPane jTabbedPane1;
private PanelControlExamenes panelControlExamenes1;
private PanelExamenClinico panelExamenClinico21;
private PanelIdentificacion panelIdentificacion;
private PanelInformacionGeneral panelInformacionGeneral1;
private PanelIntervenciones panelIntervenciones;
public IngresarPaciente()
{
initComponents();
}
public IngresarPaciente(Modelo modelo) {
this.modelo = modelo;
initComponents();
}
public void agregarAceptarListener(ActionListener al)
{
this.panelInformacionGeneral1.getAceptar().addActionListener(al);
}
public void agregarCedulaFocusListener(FocusListener fl)
{
this.panelInformacionGeneral1.getCampoCedula().addFocusListener(fl);
}
private void initComponents()
{
this.jTabbedPane1 = new JTabbedPane();
this.panelInformacionGeneral1 = new PanelInformacionGeneral();
this.panelIdentificacion = new PanelIdentificacion();
this.jScrollPane1 = new JScrollPane();
this.panelExamenClinico21 = new PanelExamenClinico();
this.panelControlExamenes1 = new PanelControlExamenes();
this.panelIntervenciones = new PanelIntervenciones();
setDefaultCloseOperation(2);
this.jTabbedPane1.addTab("Información General", this.panelInformacionGeneral1);
this.jTabbedPane1.addTab("Identificación", this.panelIdentificacion);
this.jScrollPane1.setViewportView(this.panelExamenClinico21);
this.jTabbedPane1.addTab("Examen Clínico", this.jScrollPane1);
this.jTabbedPane1.addTab("Control de Exámenes", this.panelControlExamenes1);
this.jTabbedPane1.addTab("Intervenciones", this.panelIntervenciones);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.jTabbedPane1, GroupLayout.Alignment.TRAILING, -1, 980, 32767));
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.jTabbedPane1, -2, 625, -2));
pack();
}
public static void main(String[] args)
{
try
{
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
catch (ClassNotFoundException ex) {
Logger.getLogger(IngresarPaciente.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(IngresarPaciente.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(IngresarPaciente.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(IngresarPaciente.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new IngresarPaciente().setVisible(true);
}
});
}
public PanelInformacionGeneral getPanelInformacionGeneral()
{
return this.panelInformacionGeneral1;
}
public PanelIdentificacion getPanelIdentificacion()
{
return this.panelIdentificacion;
}
public PanelExamenClinico getPanelExamenClinico()
{
return this.panelExamenClinico21;
}
public PanelIntervenciones getPanelIntervenciones()
{
return this.panelIntervenciones;
}
public PanelControlExamenes getPanelControlExamenes()
{
return this.panelControlExamenes1;
}
}<file_sep>/README.md
Sistema para administrar inventario y consultas de una
clinica maxilofacial.<file_sep>/dentistas/comandos/ModificarDentistaComando.java
package dentistas.comandos;
import interfaces.Comandos;
import java.io.PrintStream;
import modulos.Modelo;
public class ModificarDentistaComando
implements Comandos
{
private Modelo modelo;
public ModificarDentistaComando(Modelo modelo)
{
this.modelo = modelo;
}
public void ejecutar(Object[] obj)
{
String[] lista = (String[])obj[0];
if (!this.modelo.existe(lista[2]))
{
System.out.println("no existe un dentista con esa cedula.");
}
}
}<file_sep>/interfaces/VistaAdapter.java
package interfaces;
import dentistas.vista.paneles.PanelDentista;
import java.awt.event.ActionListener;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import modulos.Vista;
import pacientes.vista.paneles.PanelInformacionGeneral;
import personal.vista.paneles.PanelPersonal;
public class VistaAdapter extends JFrame
implements Vista
{
public void agregarAceptarListener(ActionListener al)
{
}
public JTextField getCampoNombre()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoApellido()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoCedula()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoCelular()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoDireccionEmail()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoDireccion()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoCodigo()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoCodigoViejo()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoCodigoNuevo()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoFechaNacimiento()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoSexo()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoTelefonoLocal()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoTelefonoMovil()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoTelefonoFijo()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextArea getAreaDireccionCompleta()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoPrimerNombre()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoSegundoNombre()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoPrimerApellido()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoSegundoApellido()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoFecha()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public PanelInformacionGeneral getPanelInformacionGeneral()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JPanel getPanelIdentificacion()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JPanel getPanelExamenClinico()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JPanel getPanelIntervenciones()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JPanel getPanelAnalisis()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoCondicionesPago()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoNroFactura()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JRadioButton getDomiciolioRadioBtn()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JRadioButton getPacienteRadioBtn()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTable getTablaFacturas()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoTelefono()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoLugar()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoDatosAdicionales()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoConvenio()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JTextField getCampoEntrega()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JPanel getPanelFactura()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JPanel getAnalisisSencillo()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public JPanel getAnalisisComplejo()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public void agregarCedulaFocusListener(FocusListener fl)
{
}
public JPanel getPanelControlExamenes() {
throw new UnsupportedOperationException("Not supported yet.");
}
public PanelDentista getPanelDentista()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public PanelPersonal getPanelPersonal()
{
throw new UnsupportedOperationException("Not supported yet.");
}
}<file_sep>/TODO.txt
*) Retomar, para recordar.
*) Analizar la posibilidad de mejorar la implementacion
del sistema, i.e., pasarlo a webapp.
|
996114f2a97c288f03509d13d3463cde1d0e7ba4
|
[
"Markdown",
"Java",
"Text",
"INI"
] | 29
|
Java
|
hpRamirez/rdmax
|
0abd97ff38bc3f3a67ed81f860db246c4ff1b1d0
|
f88db12db1e7098adf04eed2557ff0fb0d51c679
|
refs/heads/master
|
<repo_name>k82cn/volcano<file_sep>/pkg/scheduler/api/shared_device_pool.go
/*
Copyright 2023 The Volcano Authors.
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 api
import (
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"volcano.sh/volcano/pkg/scheduler/api/devices/nvidia/gpushare"
"volcano.sh/volcano/pkg/scheduler/api/devices/nvidia/vgpu"
)
const (
GPUSharingDevice = "GpuShare"
)
type Devices interface {
//following two functions used in node_info
//AddResource is to add the corresponding device resource of this 'pod' into current scheduler cache
AddResource(pod *v1.Pod)
//SubResoure is to substract the corresponding device resource of this 'pod' from current scheduler cache
SubResource(pod *v1.Pod)
//following four functions used in predicate
//HasDeviceRequest checks if the 'pod' request this device
HasDeviceRequest(pod *v1.Pod) bool
//FiltreNode checks if the 'pod' fit in current node
FilterNode(pod *v1.Pod) (bool, error)
//Allocate action in predicate
Allocate(kubeClient kubernetes.Interface, pod *v1.Pod) error
//Release action in predicate
Release(kubeClient kubernetes.Interface, pod *v1.Pod) error
//IgnredDevices notify vc-scheduler to ignore devices in return list
GetIgnoredDevices() []string
//used for debug and monitor
GetStatus() string
}
// make sure GPUDevices implements Devices interface
var _ Devices = new(gpushare.GPUDevices)
var IgnoredDevicesList []string
var RegisteredDevices = []string{
GPUSharingDevice, vgpu.DeviceName,
}
|
fd58c9658913200bb4536f5a9ae13c6f279575ec
|
[
"Go"
] | 1
|
Go
|
k82cn/volcano
|
9427174e0eefc18d321d34ba844fe3f80ff491a5
|
8e2ecb773e4e2eaac372890ec8a3213d3b12a8f8
|
refs/heads/main
|
<file_sep>import { AppRouteRecordRaw } from '#/vue-route'
import { RouteRecordRaw } from 'vue-router'
// 本地路由配置
const constantRoutes: AppRouteRecordRaw[] = [
{
path: '/login',
name: 'Login',
hidden: true,
component: () => import('@/views/login/Login.page.vue'),
meta: { title: '用户登录' },
},
{
path: '',
component: () => import('@/layout/MainLayout.vue'),
redirect: '/home',
meta: { title: '首页', isLayout: true, breadcrumb: false },
children: [
//配置在这个children下的路由将会展示在左边menu的第一层 平铺 没有嵌套
{
path: 'home',
name: 'Home',
component: () => import('@/views/dashboard/DashBoard.page.vue'),
meta: { title: '控制台', icon: 'DashboardOutlined' },
},
// {
// path: 'icons',
// name: 'SvgIcon',
// component: () => import('@/views/icons/SvgIcons.page.vue'),
// meta: { title: 'SvgIcon', icon: 'svg-all' },
// },
],
},
{
path: '/:pathMatch(.*)',
name: 'Page404',
hidden: true,
component: () => import('@/views/error-page/404.page.vue'),
meta: {
title: 'page404',
noCache: true,
},
},
]
export default constantRoutes as RouteRecordRaw[]
|
dfe51ac63e045c7166126847e6e58434ff7abd76
|
[
"TypeScript"
] | 1
|
TypeScript
|
dairsaber/template-vue3
|
21619911479dd028a7aab0e30042e0ab300d6491
|
e022f4379be86e42925392ac09c7b49ff388b763
|
refs/heads/master
|
<file_sep>package com.customer.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Customer {
private String name;
@Id
private String email;
private String password;
private String contactNumber;
private String income;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getIncome() {
return income;
}
public void setIncome(String income) {
this.income = income;
}
}
<file_sep>package com.customer.controllers;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.customer.dao.impl.CustomerDaoImpl;
import com.customer.pojo.Customer;
import com.customer.validation.CustomerValidation;
@Controller
public class CustomerController {
@RequestMapping(value="/register")
public String registerCustomer(Model model,Customer cust) {
System.out.println("entered into register");
CustomerValidation validation=new CustomerValidation();
boolean result =validation.isTextEmpty(cust.getName());
if(result) {
System.out.println(1);
model.addAttribute("message", "Name should not be empty");
model.addAttribute("customer", cust);
return "register";
}
result =validation.isTextEmpty(cust.getEmail());
if(result) {
System.out.println(2);
model.addAttribute("message", "email id should not be empty");
model.addAttribute("customer", cust);
return "register";
}
result =validation.isTextEmpty(cust.getPassword());
if(result) {
System.out.println(3);
model.addAttribute("message", "Password field should not be empty");
model.addAttribute("customer", cust);
return "register";
}
result =validation.isTextEmpty(cust.getContactNumber());
if(result) {
System.out.println(4);
model.addAttribute("message", "contact number should not be empty");
model.addAttribute("customer", cust);
return "register";
}
/*result =validation.isTextEmpty(cust.getIncome());
if(result) {
model.addAttribute("message", "Income field cannot not be empty");
model.addAttribute("customer", cust);
return "register";
}*/
try {
System.out.println(5);
CustomerDaoImpl custDao=new CustomerDaoImpl();
custDao.customerRegistration(cust);
}catch(ConstraintViolationException cve){
model.addAttribute("message", "Already registered");
return "register";
}catch(Exception e) {
model.addAttribute("message", "Please try after sometime something went right");
return "register";
}
System.out.println("CustomerController::registerCustomer()method!!");
return "login";
}
}
<file_sep>package com.customer.dao.impl;
import org.hibernate.Session;
import com.customer.pojo.Customer;
import com.customer.pojo.DBUtil;
public class CustomerDaoImpl {
public void customerRegistration(Customer c) {
System.out.println(6);
Session ss = DBUtil.getsf().openSession();
ss.save(c);
ss.beginTransaction().commit();
ss.close();
}
}
|
56cf8958b1dabdb7ad3ac26bb7b7ca7f8b6fc528
|
[
"Java"
] | 3
|
Java
|
kshivarama/Banking
|
821609090bbdc8467cc770035209434301ebbdad
|
853325054683953b616bdcc7751a2ed7374e8634
|
refs/heads/master
|
<file_sep>## <NAME> Notitajada
Proyecto final para el curso de Web Development Full Stack
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class RegistersController extends Controller
{
public function registrado(Request $request){
$this->validate($request, [
'email' => 'required',
'age' => 'required',
'password' => '<PASSWORD>',
'object' => 'required',
'friend' => 'required',
'name' => 'required'
]);
$user = new User;
$user->email = $request->input('email');
$user->age = $request->input('age');
$user->password = <PASSWORD>($request->input('password'));
$user->object = $request->input('object');
$user->friend = $request->input('friend');
$user->name = $request->input('name');
$user->save();
return redirect('register')->with('response', 'Registro Exitoso');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class pageController extends Controller
{
public function __construct(){
$this->middleware(
'authorization',
['only'=>['noticia']]
);
}
public function inicio()
{
return view('home');
}
public function register()
{
return view('register');
}
public function login()
{
return view('login');
}
public function noticia()
{
return view('noticia');
}
public function noticia2()
{
return view('noticia2');
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'pageController@inicio')->name('inicio');
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
Route::post('/registrado', 'RegistersController@registrado');
Route::get('noticia', 'pageController@noticia')->name('noticia');
Route::get('noticia2', 'pageController@noticia2')->name('noticia2');
Route::get('/home', 'HomeController@index')->name('home');
Route::post('login', 'Auth\LoginController@login');
Route::get('logout', 'Auth\LoginController@logout')->name('logout');
Route::get ('createuser', function(){
App\User::create([
'name' => 'brazo',
'email' => '<EMAIL>',
'password' => <PASSWORD>('<PASSWORD>'),
'age' => '46',
'object' => 'zapato',
'friend' => 'fran'
]);
});
|
779268483fb89bf3f796af34053554568a0efc80
|
[
"Markdown",
"PHP"
] | 4
|
Markdown
|
oninsomnus/Notitajada
|
2cc2cdb9ff97a88c875fd1e70ee4e2c8d10deb20
|
4db0c246204fd48c854f2566ba332c8b7ca5ae02
|
refs/heads/master
|
<file_sep><?php
session_start();
require('dbconnect.php');
if(isset($_SESSION['id']) && $_SESSION['time'] + 3600 > time()){
$_SESSION['time'] = time();
// ようこそ◎◎さん
$sql = sprintf('SELECT * FROM `members` WHERE id="%d"',
mysqli_real_escape_string($db,$_SESSION['id'])
);
$record = mysqli_query($db,$sql) or die(mysql_error($db));
$member = mysqli_fetch_assoc($record);
}else{
// ログインしていない
header('Location; login.php');
exit();
}
// 各変数の初期値設定
$name = '';
$username = '';
$comment = '';
// 名前、アカウント名、画像、コメントが入力された場合
if(!empty($_POST)){
$name = $_POST['name'];
$username = $_POST['username'];
$comment = $_POST['comment'];
// 名前未入力チェック
if($_POST['name'] == ''){
$error['name'] = 'blank';
}
// アカウント名未入力チェック
if($_POST['username'] == ''){
$error['username'] = 'blank';
}
// 画像ファイルの拡張子チェック
$filename = $_FILES['picture']['name'];
if(!empty($filename)){
$ext = substr($filename, -3);
if($ext != 'jpg' && $ext != 'gif' && $ext != 'png'){
$error['picture'] = 'type';
}
}
// 画像をアップロードする
if(empty($error)){
$picture = date('YmdHis') . $_FILES['picture']['name'];
move_uploaded_file($_FILES['picture']['tmp_name'], 'twitter_picture/' . $picture);
var_dump($_FILES);
// セッションに値を保存
$_SESSION['join'] = $_POST;
$_SESSION['join']['picture'] = $picture;
header('Location: check2.php');
exit();
}
}
?>
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/favicon.ico">
<title>おもしろtwitterアカウント</title>
<!-- Bootstrap core CSS -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="assets/css/starter-template.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</nav>
<div class="container">
<div class="starter-template">
<legend>ようこそ<?php echo $member['name']; ?>さん!</legend>
<h1>おもしろtwitterアカウント</h1>
<table class="table table-striped table-condensed">
<form action="" method="post" enctype="multipart/form-data">
<div class="lead">追加したい時
<tr>
<td><div>ツイッター名</div></td>
<td><div> <input type="text" name="name" value="<?php echo $name; ?>">
<?php if(isset($error['name']) && $error['name'] == 'blank'): ?>
<p class="error">※ツイッター名を入力してください</p>
<?php endif; ?>
</div></td>
</tr>
<tr>
<td><div>アカウント</div></td>
<td><div><input type="text" name="username" value="<?php echo $username; ?>">
<?php if(isset($error['username']) && $error['username'] == 'blank'): ?>
<p class="error">※アカウントIDを入力してください</p>
<?php endif; ?>
</div></td>
</tr>
<tr>
<td><div>画像</div></td>
<td><div><p><input type="file" name="picture">
<?php if(isset($error['picture']) && $error['picture'] == 'type'): ?><br>
<p style="color:red;">✴︎ プロフィール画像は「jpg」「gif」「png」の画像を指定してください</p>
<?php endif; ?>
<?php if(!empty($error)): ?><br>
<p style="color:red;">✴︎ 画像を再設定してください</p>
<?php endif; ?>
</p>
</div></td>
</tr>
<tr>
<td><div>コメント</div></td>
<td><div><textarea name="comment" ><?php echo $comment; ?></textarea></div></td>
</tr>
<div>
<td><div><input type="submit" value="登録する"></div></td>
</div>
</form>
</div>
</table>
<form action="view.php" method="post">
<h3>検索したい時</h3>
<input type="text" name="search">
<input type="submit" value="検索" class="btn btn-success btn-xs">
</form>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="assets/js/jquery.min.js"><\/script>')</script>
<script src="assets/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
<file_sep><?php
session_start();
require('dbconnect.php');
// 検索処理
if(!empty($_POST)){
$sql = sprintf('SELECT *
FROM `accounts`
WHERE `name` LIKE "%%%s%%"
OR `username` LIKE "%%%s%%"
OR `comment` LIKE "%%%s%%"',
mysqli_real_escape_string($db,$_POST['search']),
mysqli_real_escape_string($db,$_POST['search']),
mysqli_real_escape_string($db,$_POST['search'])
);
// var_dump($sql);
$account = mysqli_query($db,$sql) or die(mysqli_error($db));
}
?>
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>アカウント一覧</title>
<!-- Bootstrap core CSS -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="sticky-footer.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Begin page content -->
<div class="container">
<div class="page-header">
<h1>アカウント一覧</h1>
</div>
<?php while($accounts = mysqli_fetch_assoc($account)): ?>
<div>画像:
<img src="twitter_picture/<?php echo $accounts['picture'] ?>" width="100" height="100">
</div>
<p>名前 : <span class="name"><?php echo $accounts['name']; ?> </span></p>
<p>
アカウント : <br>
<?php echo $accounts['username']; ?>
</p>
<p>
コメント : <br>
<?php echo $accounts['comment']; ?>
</p>
<?php endwhile ?>
</div>
<footer class="footer">
<div class="container">
<p class="text-muted">Place sticky footer content here.</p>
</div>
</footer>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
<file_sep><?php
session_start();
require('../dbconnect.php');
// 各入力値の初期値を設定
$name = '';
$email = '';
$password = '';
// フォームからデータが送信された場合
if(!empty($_POST)){
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// エラー項目の確認
// ニックネーム未入力チェック
if($_POST['name'] == ''){
$error['name'] = 'blank';
}
// メールアドレス未入力チェック
if($_POST['email'] == ''){
$error['email'] = 'blank';
}
// パスワード未入力チェック
if($_POST['password'] == ''){
$error['password'] = 'blank';
}
// パスワードが4文字以下の場合
if(strlen($_POST['password']) < 4){
$error['password'] ='length';
}
// 重複アカウントのチェック
if(empty($error)){
$sql = sprintf('SELECT COUNT(*) As cnt
FROM `members`
WHERE `email`="%s"',mysqli_real_escape_string($db,$_POST['email']));
$record = mysqli_query($db,$sql) or die(mysqli_error($db));
$table = mysqli_fetch_assoc($record);
if($table['cnt'] > 0){
$error['email'] = 'duplicate';
}
}
// エラーがなかった場合の処理
if(empty($error)){
$_SESSION['join'] = $_POST;
header('Location: check.php');
exit();
}
}
// 書き直し処理
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'rewrite'){
$_POST = $_SESSION['join'];
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$error['rewrite'] = true;
}
?>
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../favicon.ico">
<title>会員登録</title>
<!-- Bootstrap core CSS -->
<link href="../assets/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="jumbotron.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="../assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<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="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="<PASSWORD>" class="form-control">
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
</div><!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1>会員登録</h1>
<p>次のフォームに必要事項をご記入ください</p>
<form action="index.php" method="post" enctype="multipart/form-data">
<dl>
<dt>ニックネーム<span class="required">(必須)</span></dt>
<dd><input type="text" name="name" size="35" maxlength="255" value="<?php echo htmlspecialchars($name); ?>">
<?php if(isset($error['name']) && $error['name'] == 'blank'): ?>
<p class="error">ニックネームを入力してください</p>
<?php endif; ?>
</dd>
<dt>メールアドレス<span class="required">(必須)</span></dt>
<dd><input type="text" name="email" size="35" maxlength="255" value="<?php echo htmlspecialchars($email); ?>">
<?php if(isset($error['email']) && $error['email'] == 'blank'): ?>
<p class="error">メールアドレスを入力してください</p>
<?php endif; ?>
</dd>
<dt>パスワード<span class="required">(必須)</span></dt>
<dd><input type="<PASSWORD>" name="password" size="10" maxlength="20" value="<?php echo $password; ?>">
<?php if(isset($error['password']) && $error['password'] == 'blank'): ?>
<p class="error">パスワードを入力してください</p>
<?php endif; ?>
<?php if(isset($error['password']) && $error['password'] == 'length'): ?>
<p class = "error">パスワードは4文字以上で入力してください</p>
<?php endif; ?>
</dd>
</dl>
<div><input type="submit" value="入力内容を確認する"></div>
</form>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="../assets/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
<file_sep><?php
session_start();
require('dbconnect.php');
// もし登録ボタンが押されたら
if(!empty($_POST)){
//登録処理
$sql = sprintf('INSERT INTO `accounts`
SET `name`="%s",
`username`="%s",
`picture`="%s",
`comment`="%s",
`member_id`="%s",
`created`=NOW()',
mysqli_real_escape_string($db,$_SESSION['join']['name']),
mysqli_real_escape_string($db,$_SESSION['join']['username']),
mysqli_real_escape_string($db,$_SESSION['join']['picture']),
mysqli_real_escape_string($db,$_SESSION['join']['comment']),
mysqli_real_escape_string($db,$_SESSION['id'])
);
mysqli_query($db,$sql) or die(mysqli_error($db));
unset($_SESSION['join']);
header('Location: thanks2.php');
exit();
}
?>
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>アカウント登録確認</title>
<!-- Bootstrap core CSS -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="sticky-footer-navbar.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
</div>
</nav>
<!-- Begin page content -->
<div class="container">
<div class="page-header">
<h1>アカウント登録確認</h1>
</div>
<div>
<form method="post" action="">
<input type="hidden" name="action" value="submit">
<table class="table table-striped table-condensed">
<tbody>
<!-- 登録内容を表示 -->
<tr>
<td><div class="text-center">名前</div></td>
<td><div class="text-center"><?php echo $_SESSION['join']['name']; ?></div></td>
</tr>
<tr>
<td><div class="text-center">アカウント</div></td>
<td><div class="text-center"><?php echo $_SESSION['join']['username']; ?></div></td>
</tr>
<tr>
<td><div class="text-center">パスワード</div></td>
<td><div class="text-center">●●●●●●●●</div></td>
</tr>
<tr>
<td><div class="text-center">アカウント画像</div></td>
<td><div class="text-center"><img src="twitter_picture/<?php echo $_SESSION['join']['picture']; ?>" width="100" width="100" height="100"></div></td>
</tr>
<tr>
<td><div class="text-center">コメント</div></td>
<td><div class="text-center"><?php echo $_SESSION['join']['comment'] ?></div></td>
</tr>
</tbody>
</table>
<input type="submit" class="btn btn-default" value="アカウント登録">
</form>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="text-muted">Place sticky footer content here.</p>
</div>
</footer>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="assets/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
|
c8d0a2f63e15310a6cbc0c094016cc7f4f9437b3
|
[
"PHP"
] | 4
|
PHP
|
macky666/twitter_search
|
b2aa48f911cef730785b0cae5411e7cdc9ef00ae
|
dc833808eaf1c519fd061ef49ab12126729f52a0
|
refs/heads/master
|
<file_sep>require_relative 'fizz_buzz'
<file_sep>require 'rspec-given'
require_relative 'spec_helper'
describe "Fizz Buzz Mapper" do
Given(:mapper) { Mapper.new }
context "mapper yields" do
it "1 yields 1" do
result = mapper.map(2)
expect(result).to eq(2)
end
it "2 yields 2" do
result = mapper.map(2)
expect(result).to eq(2)
end
it "multiples of three yield fizz" do
result = mapper.map(9)
expect(result).to eq("fizz")
end
it "multiples of five yield buzz" do
result = mapper.map(50)
expect(result).to eq("buzz")
end
it "multiples of five and three yield fizzbuzz" do
result = mapper.map(15)
expect(result).to eq("fizzbuzz")
end
end
end
<file_sep>task :default => :spec
task :spec do
sh "bundle exec rspec fizz_buzz_spec.rb"
end
<file_sep>class Mapper
def map(number)
if divisible_by_three_and_five? number
"fizzbuzz"
elsif divisible_by_three? number
"fizz"
elsif divisible_by_five? number
"buzz"
else
number
end
end
def divisible_by_three_and_five?(number)
number % 3 == 0 && number % 5 == 0
end
def divisible_by_three?(number)
number % 3 == 0
end
def divisible_by_five?(number)
number % 5 == 0
end
end
|
e56bac7f0a0fcca7e03848fdabf219490a72c7b0
|
[
"Ruby"
] | 4
|
Ruby
|
jskulski/kata-fizz_buzz-ruby
|
4cc2bf811a725246deb94b9f382222bfe0a18b3c
|
5a2f12fb9908a5a66923495407ca58b9c54789af
|
refs/heads/master
|
<file_sep>## Caching part #1: Cache-Control header ##
This repo contains the full code of my [blog entry](https://code.darkroku12.ovh/5-caching-part-1/).
## Install instructions:
1) Run `npm install`. (This is a NodeJS app).
2) Create a file named `.env` in the root folder.
The `.env` file content:
```c++
PORT=4010 # Desired port to run the NodeJS app.
```
## Running instructions:
Just open the console and run: `node index.js`.
If you want to use NGINX/OpenResty, be sure to use the provided `nginx.conf` at the root folder.
## Notes:
`Environment: PORT` --> The desired port to run the NodeJS server. Take into account that if you use the NGINX web server you'll need to change `nginx.conf` to match the new port.
## Setup info:
- Windows 10 (20H2)
- Node version: v16.5.0
- NGINX/OpenResty: openresty/1.19.3.2
## Author:
#### <NAME> | DarkRoku12 | <EMAIL><file_sep>import "./exceptionHandler.js";
import Env from "./environment.js";
import Express from "express";
import Moment from "moment";
import Path from "path";
const app = Express();
app.get( "/" , function( req , res )
{
res.sendFile( "index.html" , { root : Path.resolve() });
});
// Middleware to log requests that start with 'counter'.
app.all( "/counter*" , function( req , res , next )
{
const path = `${req.baseUrl}${req.path}`;
console.log( req.method , path , Moment().format( "HH:mm:ss" ) );
next();
});
let counter = 0;
// Without cache.
app.get( "/counter" , function( req , res )
{
res.json({ from : "counter" , counter : ++counter });
});
// With Cache-control.
app.get( "/counter-cache-control" , function( req , res )
{
const seconds = 10;
res.set( "Cache-control" , `private, max-age=${seconds}` );
res.json({ from : "counter-cache-control" , counter : ++counter });
});
// Create the server.
app.listen( Env.PORT , () =>
{
console.log( `Server running at: http://localhost:${Env.PORT}` );
});
|
8ae67ff6f2bf3f353fd8c121b8ef45ca7628e1f6
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
DarkRoku12/5--cache-control-header
|
f94d4fd2e0a6b7e95381f50be13733d310a776a6
|
1a6733fa17bfa1e1d82001cc92f56d85ad97356c
|
refs/heads/master
|
<file_sep>const express = require("express");
const path = require("path");
const app = express();
const port = 3000;
const bodyParser = require("body-parser");
const dotenv = require("dotenv").config();
const mongoose = require("mongoose");
const router = express.Router();
const indexRouter = require("./routes/index");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var mongoDB = `mongodb+srv://${process.env.DB_HOST}:${
process.env.DB_PASSWORD
}@<EMAIL>/${process.env.DB_NAME}?retryWrites=true`;
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error"));
app.engine("html", require("ejs").renderFile);
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "views")));
app.use("/public", express.static("public"));
app.use("/", indexRouter);
app.listen(port, () => console.log(`App running on port ${port}`));
<file_sep>const express = require("express");
const router = express.Router();
const facebook_controller = require("../controllers/facebookController");
const youtube_controller = require("../controllers/youtubeController");
router.all("/", (req, res) => {
res.redirect("/facebook");
});
router.get("/facebook", facebook_controller.search_facebook_get);
router.post("/facebook", facebook_controller.search_facebook_post);
router.get("/youtube", youtube_controller.search_youtube_get);
router.post("/youtube", youtube_controller.search_youtube_post);
module.exports = router;
<file_sep>ACCESS_TOKEN=GRAPH_API_ACCESS_TOKEN
DB_HOST=YOUR_DB_HOST_NAME
DB_PASSWORD=<PASSWORD>
DB_NAME=YOUR_DB_NAME
YOUTUBE_API_KEY=YOUTUBE_DATA_API_V3_KEY<file_sep>const YoutubeSearch = require("../models/youtube");
const request = require("request");
exports.search_youtube_get = function(req, res) {
res.render("youtube");
};
exports.search_youtube_post = function(req, res) {
YoutubeSearch.findOne({ name: req.body.youtube }, function(err, docs) {
if (err) {
return error;
}
if (docs) {
var obj = JSON.parse(docs.search);
res.render("youtube", { body: obj.items });
} else {
request(
`https://www.googleapis.com/youtube/v3/search?&part=snippet&q=${
req.body.youtube
}&type=channel&maxResults=50&key=${process.env.YOUTUBE_API_KEY}`,
function(error, response, body) {
if (error) {
console.log(error);
}
var youtube = new YoutubeSearch({
name: req.body.youtube,
search: body
});
youtube.save(function(error, result) {
if (error) {
return error;
}
});
var obj = JSON.parse(body);
res.render("youtube", { body: obj.items });
}
);
}
});
};
|
36213509f4f5ce09767a14348c95cd97e2730e79
|
[
"JavaScript",
"Shell"
] | 4
|
JavaScript
|
Tihomir10/mediatoolkit
|
801502b43b2e71c2d49d12762d731dc13fdbd4d0
|
51c5494b589622587a65a36a64efa5b0417c323e
|
refs/heads/master
|
<repo_name>DNgoc479/project_staff<file_sep>/main.cpp
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <Staff.h>
#include <map>
#include <Helpper.h>
#include <InfoAttendance.h>
#include <TimekeepingHistory.h>
#include <InfoAttendance.h>
using namespace std;
void menu(){
cout<< ""<< endl;
cout <<"===========================================" <<endl;
cout <<"= 1-Nhap nhan vien =" << endl;
cout <<"= 2-Tim Thong tin nhan vien =" << endl;
cout <<"= 3-In tat ca cac nhan vien =" << endl;
cout <<"= 4-Tao file luu nhan vien =" << endl;
cout <<"= 5-Nhap thong tin diem danh nhan vien =" << endl;
cout <<"= 6-Lich su diem danh nhan vien =" << endl;
cout <<"===========================================" <<endl;
cout << "Chon chuc nang (1-6):" << endl;
cout << "Moi ban nhap lai lua chon: ";
}
void run(){
Staff *staff;
int choice;
string urlFile = "C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\fileStaff.csv";
staff = new Staff();
map<string,Staff> list = staff->addMapStaff(urlFile);
do {
menu();
cin >> choice;
switch (choice) {
case 1:
{
staff->inputStaff();
break;
}
case 2:
{
cout << "\n------= SEARCH STAFF =------" <<endl;
staff->SearchStaff();
break;
}
case 3:
{
cout << "------= LIST STAFF =------ " <<endl;
staff->outStaffFile();
break;
}case 4:
{
for(map<string,Staff>::iterator it = list.begin()++;it != list.end();it++){
// tao file nhan vien diem danh
std::ofstream o( "C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\ListDSNV\\"+it->first+".csv");
}
cout << "File creation successful !!! " <<endl;
break;
}
case 5:
{
cout << "------= NHAP THONG TIN DIEM DANH =------ " <<endl;
InfoAttendance::read(list);
break;
}
case 6:
{
cout << "------= lICH SU LAM VIEC CUA NHAN VIEN =------ " <<endl;
string month;
cout << "Nhap Thang ban muon diem danh: ";
cin >> month;
while (TimekeepingHistory::inputNumber(month) == 0 ) {
cout << "Nhap Thang ban muon diem danh again: ";
cin >> month;
}
string idStaff;
cout << "Enter id staff: ";
cin >>idStaff;
while(Helpper::checkId(list,idStaff) == 1){
cout << "Enter id staff again: ";
cin >>idStaff;
}
map<string,TimekeepingHistory> listT = TimekeepingHistory::readFileStaff(idStaff,list,month);
// cout <<"check = " <<listT.empty();
// int check = listT.empty();
// if(check == 0){
// break;
// }
for(map<string,TimekeepingHistory>::iterator it = listT.begin();it != listT.end();it++){
cout <<"So ngay di lam := " <<it->second.getNumberDaysDL()<< endl;
cout <<"So ngay ngay nghi := " <<it->second.getNumberDaysN()<< endl;
cout <<"So ngay di lam nua ngay:= " <<it->second.getNumberDaysDLNN()<< endl;
cout <<"so ngay nghi phep := " <<it->second.getNumberDaysNP()<< endl;
}
string urlFileHistory = "C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\HistoryDD\\";
std::ofstream o( urlFile+idStaff+".csv");
o.close();
TimekeepingHistory::inputFileAttendance(urlFileHistory,idStaff,listT);
break;
}
}
}while (choice != 0);
cout << "THE END !" << endl;
}
int main()
{
run(); //<mo run>
return 0;
}
<file_sep>/InfoAttendance.cpp
#include <stdio.h>
#include <string>
#include <iostream>
#include <map>
#include <fstream>
#include <Staff.h>
#include <Helpper.h>
#include "InfoAttendance.h"
using namespace std;
void InfoAttendance::read(map<string, Staff> list){
cin.ignore();
string url = "C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\ListDSNV\\";
string idStaff;
cout <<"Enter the employee id you want to time: ";
getline(cin,idStaff);
while(Staff::checkId(idStaff,list) == 1){
cout << "Enter the employee id you want to time! again: "<< endl;
getline(cin,idStaff);
}
ifstream ifs(url+idStaff+".csv", ios::in);
cout<< "Enter the date you want to timekeeping: ";
string date;
getline(cin,date);
// while (Helpper::checkDateStaff(date) == 1) {
// cout<< "Enter the date you want to timekeeping(dd/mm/yyyy): ";
// getline(cin,date);
// }
cout<< "Enter status of employee to work (DL-DLNN-N-NP): ";
string status;
// cin >> status;
getline(cin,status);
while(Helpper::checkStatus(status) ==0){
cout<<"Dinh dang sai , xin nhap lai ";
//cin >> status;
getline(cin,status);
}
fflush(stdin);
//vector<string> listdate = Helpper::split(date,'/');
// ghi vào
fstream output(url+idStaff+".csv", ios::app);
output <<":" <<date <<","<<status;
// đóng đọc file
output.close();
ifs.close();
}
<file_sep>/helpper.h
#ifndef HELPPER_H
#define HELPPER_H
#include <vector>
#include <sstream>
#include <string>
#include <map>
#include <Staff.h>
using namespace std;
class Helpper
{
public:
static int numberLine(); // lấy ra số dòng trong file csv
static vector<string> split (const string &s, char delim) ; // tách theo chuỗi theo dấu
// static int isSubstring(string s1, string s2);
static int checkId(map<string,Staff>list, string id); // kiem tra id trung ko
static int checkDateOfBirth(string dateOfBirth); // kiem tra ngay hop le ko
static int checkStatus(string status);
static int checkDateStaff(string date);
};
#endif // HELPPER_H
<file_sep>/Staff.h
#ifndef STAFF_H
#define STAFF_H
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class Staff{
private:
string _id;
string _name;
string _birthday;
string _address;
string _wDepartment; // bo phan cong tac
public:
const string &getId() const {return this->_id;};
const string &getName() const {return this->_name;};
const string &getBirthday() const {return this->_birthday;};
const string &getAddress() const {return this->_address;};
const string &getWDepartment() const{return this->_wDepartment;};
public:
Staff(string id, string name,string birthday,string address,string wdepartment);
Staff(){};
~Staff(){};
static map<string,Staff>addMapStaff(string urlfile);
virtual void inputFile(string url,Staff staff);
virtual void inputStaff();
static int checkId(string id,map<string,Staff> list);
virtual void printStaff(Staff staff);
virtual void outStaffFile();
virtual void SearchStaff();
static vector<string> cutStringDate(string s,string delimiter);
};
#endif // STAFF_H
<file_sep>/FileIoUtils.h
#ifndef FileIoUtils_hpp
#define FileIoUtils_hpp
#include <stdio.h>
#include <map>
#include <string>
using namespace std;
class Staff;
class InfoAttendance;
class FileIoUtils {
public:
static string _resourceFile;
public:
static void addEmployee(Staff *staff);
static void addListEmployees(map<string,Staff> & employees);
static void loadAllEmployee(map<string,Staff> & employees);
static map<string,Staff> & readEmployeeFromCsv(string & path);
static bool checkExist(string & path);
static void addCheckPoint(const InfoAttendance & infoAttendance); // Write to a file, indentify by employee_id
static map<string,InfoAttendance> loadCheckPoint(const string & idStaff); // Get checkpoit of a employee by employee_id
static void rewriteCheckPoint(string & idStaff, map<string,InfoAttendance> checkPoints);
static const string genCheckpointFileName(const string & idStaff); // Specify checkpoint file by employeeId
};
#endif /* FileIoUtils_hpp */
<file_sep>/Staff.cpp
#include "Staff.h"
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <map>
#include<cstring>
#include <algorithm>
#include <Helpper.h>
#include <iomanip>
#include <stdlib.h>
using namespace std;
string urlFile = "C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\fileStaff.csv";
Staff::Staff(string id, string name,string birthday,string address,string wdepartment):
_id(id),
_name(name),
_birthday(birthday),
_address(address),
_wDepartment(wdepartment)
{
}
void Staff::inputFile(string url,Staff staff){
//cout <<"co sddvsv";
fstream output(url, ios::app);;
string id = staff.getId();
string name = staff.getName();
string birthday = staff.getBirthday();
string address = staff.getAddress();
string wDepartment = staff.getWDepartment();
output <<id <<",";
output <<name <<",";
output <<birthday <<",";
output <<address <<",";
output <<wDepartment <<endl;
output.close();
}
map<string,Staff> Staff::addMapStaff(string urlfile){
map<string,Staff> mapStaff;
ifstream output;
output.open(urlfile,ios::in);
if(!output.is_open()){
cout << "ERROR: File Open" << '\n';
}
while (output.good()) {
string lineId,lineName,lineBirthday,linAddress,lineDepartment,line;
getline(output,lineId,',');
getline(output,lineName,',');
getline(output,lineBirthday,',');
getline(output,linAddress,',');
getline(output,lineDepartment,'\n');
Staff staff = Staff(lineId,lineName,lineBirthday,linAddress,lineDepartment);
// cout << lineId<<endl;
mapStaff.insert(pair<string,Staff>(lineId,staff));
//staff.~Staff();
}
output.close();
fflush(stdin);
return mapStaff;
}
map<string,Staff> list = Staff::addMapStaff(urlFile);
int Staff::checkId(string id,map<string,Staff> list){
for(map<string,Staff>::iterator it = list.begin();it != list.end();it++){
if(it->first == id){
return 0;
}
}
return 1;
}
//
//
void Staff::inputStaff(){
// string urlFile = "C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\fileStaff.csv";
cout <<"" <<endl;
cin.ignore();
cout << "Enter id staff : ";
getline(cin,_id);
while (true) {
if(checkId(_id,list) == 0){
cout << "ID contained in the file.Enter id staff : ";
getline(cin,_id);
}else{
break;
}
}
cout << "Enter Name: ";
getline(cin,_name);
cout << "Enter birthday: ";
getline(cin,_birthday);
cout << "Enter address: ";
getline(cin,_address);
while ( _address == ""){
cout << "Address not empty.Please enter again ! " <<endl;
cout << "Enter address: ";
getline(cin,_address);
}
cout << "Enter department: ";
getline(cin,_wDepartment);
while ( _wDepartment == ""){
cout << "Department not empty.Please enter again ! "<< endl;
cout << "Enter Department: ";
getline(cin,_wDepartment);
}
Staff staff = Staff(_id,_name,_birthday,_address,_wDepartment);
inputFile(urlFile,staff);
fflush(stdin);
}
void formPrint(){
cout <<setw(10)<<"ID"<< setw(30) << "NAME" << setw(20)
<< "BIRTHDAY" << setw(30) << "ADDRESS "<<setw(20)<<"DEPARTMENT" << "\n";
}
void Staff::printStaff(Staff staff){
cout <<setw(10)<<staff.getId()<< setw(30) << staff.getName() << setw(20)
<< staff.getBirthday() << setw(30) << staff.getAddress()<<setw(20)<<staff.getWDepartment() << "\n";
}
void Staff::outStaffFile(){
//string urlFile = "C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\fileStaff.csv";
// map<string,Staff> list = Staff::addMapStaff(urlFile);
map<string,Staff>::iterator itr;
cout << "The number of employees on the list: "<< list.size() << endl;
formPrint();
for(map<string,Staff>::iterator it = list.begin();it != list.end();it++){
printStaff(it->second);
}
}
int isSubstring(string s1, string s2)
{
std::transform(s1.begin(), s1.end(),s1.begin(), ::tolower);
std::transform(s2.begin(), s2.end(),s2.begin(), ::tolower);
int M = s1.length();
int N = s2.length();
for (int i = 0; i <= N - M; i++) {
int j;
for (j = 0; j < M; j++)
if (s2[i + j] != s1[j])
break;
if (j == M)
return i;
}
return -1;
}
void Staff::SearchStaff(){
// string urlFile = "E:\\QT\\project_staff\\fileStaff.csv";
//map<string,Staff> list = Staff::addMapStaff(urlFile);
map<string,Staff>::iterator itr;
int choice;
do {
cout << ""<< endl;
cout <<"------- MENU SEARCH-------" <<endl;
cout <<"1-Search by ID -" <<endl ;
cout <<"2-Search by Name -" <<endl;
cout <<"3-Search by Address -"<<endl ;
cout <<"4-Search by Department -"<<endl ;
cout <<"0-exit employee search -"<<endl ;
cout <<"--------------------------" <<endl;
cout << "Enter the choice you are looking for: " ;
cin >> choice;
switch (choice) {
case 1:
{
string idSearch;
cout << "=> SEACH BY ID: " <<endl;
cout << "Enter staff id you are looking for:= " ;
cin >> idSearch;
int check = 0;
formPrint();
for(map<string,Staff>::iterator it = list.begin();it != list.end();it++){
if(it->first == idSearch){
printStaff(it->second);
check = 1;
}
}
if(check == 0){
cout << "Not container";
}
break;
}
case 2:
{
cout << "=> SEACH BY NAME" << endl;
cin.ignore();
string name;
cout << "Enter name you are looking for:= ";
getline(cin,name);
int check = 0;
formPrint();
for(map<string,Staff>::iterator it = list.begin();it != list.end();it++){
if(isSubstring(name,it->second.getName()) >= 0){
printStaff(it->second);
check = 1;
}
}
if(check == 0){
cout << "Not container !";
}
fflush(stdin);
break;
}
case 3:
{
cout << "=> SEACH BY Adress" << endl;
cin.ignore();
string address;
cout << "Enter adress you are looking for:= ";
getline(cin,address);
int check = 0;
cout << "----= LIST ADSRESS = "<<address <<"=----" <<endl;
formPrint();
for(map<string,Staff>::iterator it = list.begin();it != list.end();it++){
if(isSubstring(address,it->second.getAddress()) >= 0){
printStaff(it->second);
check = 1;
}
}
if(check == 0){
cout << "Not container !";
}
fflush(stdin);
break;
}
case 4:
{
cout << "=> SEACH BY Department" <<endl;
cin.ignore();
string department;
cout << "Enter Department you are looking for:= ";
getline(cin,department);
cout << department <<"-------------"<< endl;
int check = 0;
formPrint();
for(map<string,Staff>::iterator it = list.begin();it != list.end();it++){
if(isSubstring(department,it->second.getWDepartment()) >= 0){
printStaff(it->second);
check = 1;
}
}
if(check == 0){
cout << "Not container";
}
fflush(stdin);
break;
}
}
} while (choice != 0);
fflush(stdin);
cout << "\n-----= THE END SEARCH STAFF =-----" <<endl;
}
<file_sep>/TimekeepingHistory.cpp
#include <Staff.h>
#include <InfoAttendance.h>
#include <Helpper.h>
#include <TimekeepingHistory.h>
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <stdlib.h>
// lay ra thong tin cac trang thai lam viec trong thang cua staff
TimekeepingHistory::TimekeepingHistory(string month,string year,int numberDayDL,int numberDayDLNN,int numberDayN,int numberDayNP):
_month(month),_year(year),_numberDaysDL(numberDayDL),
_numberDaysN(numberDayN),_numberDaysNP(numberDayNP),_numberDaysDLNN(numberDayDLNN)
{
}
string TimekeepingHistory::url = "C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\ListDSNV\\";
map<string,TimekeepingHistory> TimekeepingHistory::readFileStaff(string idStaff,map<string,Staff> listStaff,string month){
map<string,TimekeepingHistory> list;
ifstream output;
// string idStaff;
// cout << "Enter id staff: ";
// cin >>idStaff;
// while(Helpper::checkId(listStaff,idStaff) == 1){
// cout << "Enter id staff again: ";
// cin >>idStaff;
// }
string urlFile ="C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\ListDSNV\\"+idStaff+".csv";
output.open(urlFile,ios::in);
if(!output.is_open()){
cout << "ERROR: File Open" << '\n';
}
int DL=0;
int DLNN = 0;
int N = 0;
int NP = 0;
while (output.good()) {
string date,status,a;
getline(output,date,':');
getline(output,date,',');
getline(output,status,':');
// cout << "date : "<< date <<endl;
// if(date == ""){
// return null;
// }
vector<string> listDate = Helpper::split(date,'/');
if(month == listDate[1]){
if(status == "DL"){
DL = DL +1;
}else if (status == "DLNN") {
DLNN = DLNN + 1;
}else if (status == "N") {
N = N + 1;
}else if (status == "NP") {
NP = NP + 1;
}
}
}
TimekeepingHistory timehistory = TimekeepingHistory(month,"2020",DL,DLNN,N,NP);
list.insert(pair<string,TimekeepingHistory>(month,timehistory));
output.close();
fflush(stdin);
return list;
}
int TimekeepingHistory::inputNumber(string month){
int number = atoi(month.c_str());
if(number >0 && number <=12){
return 1;
}
return 0;
}
void TimekeepingHistory::inputFileAttendance(string urlFile,string idStaff, map<string, TimekeepingHistory> list){
fstream inputFile(urlFile+idStaff+".csv", ios::app);
//cout <<"size = " << list.size();
for(map<string,TimekeepingHistory>::iterator it = list.begin();it != list.end();it++){
inputFile<<"THANG:"+it->first<<",";
inputFile<<"DL:";
inputFile <<it->second.getNumberDaysDL() <<",";
inputFile<<"N:";
inputFile <<it->second.getNumberDaysN()<<",";
inputFile<<"DLNN:";
inputFile <<it->second.getNumberDaysDLNN()<<",";
inputFile<<"NP:";
inputFile <<it->second.getNumberDaysNP()<<"\n";
}
//inputFile<<"skskfks";
inputFile.close();
}
<file_sep>/helpper.cpp
#include "Helpper.h"
#include <vector>
#include <sstream>
#include <string>
#include <fstream>
#include <regex>
#include <ctime>
//#include <specstrings.h>
using namespace std;
int Helpper::numberLine(){
ifstream f1;
char c;
int numchars, numlines;
f1.open("C:\\Users\\admin\\Desktop\\GitHub\\project_staff\\fileStaff.csv");
numchars = 0;
numlines = 0;
f1.get(c);
while (f1) {
while (f1 && c != '\n') {
numchars = numchars + 1;
f1.get(c);
}
numlines = numlines + 1;
f1.get(c);
}
return(numlines);
}
vector<string> Helpper::split(const string &s, char delim){
vector<string> result;
stringstream ss (s);
string item;
while (getline (ss, item, delim)) {
result.push_back (item);
}
return result;
}
int Helpper:: checkId(map<string,Staff> list, string id) // trùng id trả về 0 ,không trùng trả về 1
{;
for(map<string,Staff>::iterator it = list.begin();it != list.end();it++){
if (it->second.getId() == id){
return 0;
}
}
return 1;
}
int Helpper ::checkStatus(string status){ // hop le return 1 , khong hop le return 0
if(status =="DL"||status =="DLNN"||status =="N"||status =="NP"){
return 1;
}
return 0;
}
vector<string> cutStringDate(string s,string delimiter){
vector<string> list;
//string delimiter = "/";
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
list.push_back(token);
//cout << token << endl;
s.erase(0, pos + delimiter.length());
}
list.push_back(s);
return list;
}
int checkDateStaff(string date) {
if(!regex_match (date, regex("^([0-2][0-9]|(3)[0-1])(\\/)(((0)[0-9])|((1)[0-2]))(\\/)\\d{4}$"))) {
return 1;
}
vector<string> list = Helpper::split(date,'/') ;
stringstream s(date);
string tmp;
//int i = 0;
for (int j=0 ;j<=list.size();j++) {
cout << list[j] <<endl;
}
int day, month, year;
day = stoi(list[0]);
month =stoi(list[1]);
year = stoi(list[2]);
if (day < 1 || day > 31 || month < 1 || month > 12) {
return 0;
}
if ((month==4 || month==6 || month==9|| month==11) && day == 31) {
return 0;
}
if (month == 2 && (day > 29 || (day == 29 && !(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))))) {
return 0;
}
time_t t = time(0);
struct tm * timeStruct = localtime(&t);
int currentY = timeStruct->tm_year + 1900;
int currentM = timeStruct->tm_mon + 1;
int currentD = timeStruct->tm_mday;
if (year < 1900 || year > currentY) {
return 0;
}
if (year == currentY) {
if (month > currentM || (month == currentM && day > currentD)) {
return 0;
}
}
return 1;
}
<file_sep>/FileIoUtils.cpp
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include "Staff.h"
#include "FileIoUtils.h"
#include "InfoAttendance.h"
using namespace std;
void addCheckPoint(const InfoAttendance & infoAttendance)
{
string fileName = FileIoUtils::genCheckpointFileName(infoAttendance.getIdStaff());
ofstream fout;
fout.open(fileName, ios::app);
if (fout.is_open()) {
fout << infoAttendance.getDate() << "," << infoAttendance.getStatus() << endl;
}
fout.close();
}
map<string,InfoAttendance> FileIoUtils::loadCheckPoint(const string & idStaff)
{
map<string,InfoAttendance> checkpoints;
string fileName = FileIoUtils::genCheckpointFileName(idStaff);
ifstream fin;
fin.open(fileName, ios::in);
if (fin.is_open()) {
string line, word;
while (getline(fin, line)) {
stringstream s(line);
int i = 0;
string row[2];
while (getline(s, word, ',')) {
row[i++] = word;
}
InfoAttendance *in = new InfoAttendance(idStaff, row[0], row[1]);
checkpoints.insert(pair<string,InfoAttendance>(idStaff,*in));
}
}
fin.close();
return checkpoints;
}
const string FileIoUtils::genCheckpointFileName(const string & idStaff)
{
string fileName = "checkpoint-" + idStaff + ".csv";
return fileName;
}
bool FileIoUtils::checkExist(string &path)
{
ifstream f(path.c_str());
return f.good();
}
void FileIoUtils::rewriteCheckPoint(string & idStaff, map<string,InfoAttendance> checkPoints)
{
string fileName = FileIoUtils::genCheckpointFileName(idStaff);
ofstream fstream_ob;
fstream_ob.open(fileName, ios::trunc);
if (fstream_ob.is_open()) {
for(map<string,InfoAttendance>::iterator it = checkPoints.begin();it != checkPoints.end();it++){
fstream_ob << it->second.getDate() << "," << it->second.getStatus() << endl;
}
}
fstream_ob.close();
}
<file_sep>/InfoAttendance.h
#ifndef INFOATTENDANCE_H
#define INFOATTENDANCE_H
#include <stdio.h>
#include <string>
#include <sstream>
#include <map>
#include <Staff.h>
using namespace std;
class InfoAttendance {
private:
string _idStaff; // id nhan vien
string _date; // ngay thang diem danh
string _month;
string _status; // trang thai di lam cua nv
public:
InfoAttendance(const string &idStaff,const string &date,const string &month,const string &status);
InfoAttendance();
public:
const string &getIdStaff() const;
const string &getDate() const;
const string &getMonth() const;
const string &getStatus() const;
bool operator <(const InfoAttendance &_InfoAttendance) const;
static void read(map<string,Staff>list);
};
#endif // CHECKDATE_H
<file_sep>/TimekeepingHistory.h
#ifndef TIMEKEEPINGHISTORY_H
#define TIMEKEEPINGHISTORY_H
#include <vector>
#include <sstream>
#include <string>
#include <map>
#include <Staff.h>
#include <InfoAttendance.h>
class TimekeepingHistory{
private:
string _month;
string _year;
int _numberDaysDL; //so ngay di lam //number of days working;
int _numberDaysDLNN;// so ngay di lam nua ngay
int _numberDaysN;// so ngay nghi trong thang
int _numberDaysNP;// so ngay nghi phep trong thang
public:
static string url;
TimekeepingHistory(string month,string year,int numberDayDL,
int numberDayDLNN,int numberDayN,int numberDayNP);
TimekeepingHistory(){};
~TimekeepingHistory(){};
const string &getMonth() const {return this->_month;}
const string &getYear() const {return this->_year;}
const int &getNumberDaysDL() const{ return this->_numberDaysDL;}
const int &getNumberDaysDLNN() const{ return this->_numberDaysDLNN;}
const int &getNumberDaysN() const {return this->_numberDaysN;}
const int &getNumberDaysNP() const { return this->_numberDaysNP;}
public:
static map<string,TimekeepingHistory> readFileStaff(string idStaff,map<string,Staff> listStaff,string month); // doc file cham cong nhan vien
static map<string,TimekeepingHistory> readAllFileFile(string url);
static int inputNumber(string month);
static void inputFileAttendance(string url,string idStaff,map<string,TimekeepingHistory>list);
};
#endif // TIMEKEEPINGHISTORY_H
<file_sep>/README.md
# project_staff
Baì tập lớn
|
33d0348e80caa488c3866caf087ac66ec2fdcc71
|
[
"Markdown",
"C++"
] | 12
|
C++
|
DNgoc479/project_staff
|
0a412a552a8ccba38c612b2981470dac18eabb54
|
60a48a76667404debf0ed4f3fae2ebfcf0b3e441
|
refs/heads/master
|
<repo_name>Alex-Thacker/chap7-student-exercises<file_sep>/Cohort.cs
using System;
using System.Collections.Generic;
namespace student_exercises{
public class Cohort {
public string Name { get; set; }
public List <Student> Students { get; set; } = new List<Student>();
public Instructor Instructor { get; set; }
}
}
// The cohort's name (Evening Cohort 6, Day Cohort 25, etc.)
// The collection of students in the cohort.
// The collection of instructors in the cohort.<file_sep>/Student.cs
using System;
using System.Collections.Generic;
namespace student_exercises{
public class Student {
public string FirstName { get; set; }
public string LastName { get; set; }
public string SlackHandle { get; set; }
public Cohort Cohort { get; set; }
public List <Exercise> Exercises { get; set; } = new List<Exercise> ();
}
}
// First name
// Last name
// Slack handle
// The student's cohort
// The collection of exercises that the student is currently working on<file_sep>/Instructor.cs
using System;
using System.Collections.Generic;
namespace student_exercises {
public class Instructor {
public string FirstName { get; set; }
public string LastName { get; set; }
public string SlackHandle { get; set; }
public Cohort Cohort { get; set; }
public string Specialty { get; set; }
public void Assign (Student variable, Exercise exercise, Exercise exercise1) {
variable.Exercises.Add(exercise);
variable.Exercises.Add(exercise1);
}
}
}
// First name
// Last name
// Slack handle
// The instructor's cohort
// The instructor's specialty (e.g. jokes, snack cakes, dancing, etc.)
// A method to assign an exercise to a student<file_sep>/Exercise.cs
using System;
namespace student_exercises
{
public class Exercise
{
public string Name { get; set; }
public string Language { get; set; }
}
}
// Name of exercise
// Language of exercise (JavaScript, Python, CSharp, etc.)<file_sep>/Program.cs
using System;
using System.Collections.Generic;
namespace student_exercises
{
class Program
{
static void Main(string[] args)
{
/////////////////////////////////Exercies
Exercise dogs = new Exercise();
dogs.Name = "dogs";
dogs.Language = "bark";
Exercise cats = new Exercise();
cats.Name = "cats";
cats.Language = "meow";
Exercise fish = new Exercise();
fish.Name = "fish";
fish.Language = "bloop";
Exercise hamster = new Exercise();
hamster.Name = "hamster";
hamster.Language = "meep";
///////////////////////Cohorts, list student and instructor
Cohort C29 = new Cohort();
C29.Name = "C29";
Cohort C30 = new Cohort();
C30.Name = "C30";
Cohort C31 = new Cohort();
C31.Name = "C31 aka the cool kids, also known as the cool kids club";
//////////////////////////////Students, add exercise list
Student Bill = new Student();
Bill.FirstName = "Bill";
Bill.LastName = "Bob";
Bill.SlackHandle = "BillBob";
Bill.Cohort = C31;
Student Steve = new Student();
Steve.FirstName = "Steve";
Steve.LastName = "Stevie";
Steve.SlackHandle = "SteveStevie";
Steve.Cohort = C29;
Student Bo = new Student();
Bo.FirstName = "Bo";
Bo.LastName = "Body";
Bo.SlackHandle = "BoBody";
Bo.Cohort = C30;
Student Blue = new Student();
Blue.FirstName = "Blue";
Blue.LastName = "Yellow";
Blue.SlackHandle = "BlueYellow";
Blue.Cohort = C31;
///////////Instructors
Instructor JDog = new Instructor () ;
JDog.FirstName = "Jisie";
JDog.LastName = "IDK";
JDog.SlackHandle = "JDog";
JDog.Cohort = C31;
JDog.Specialty = "making bird noises";
JDog.Assign(Bill, dogs, cats);
JDog.Assign(Steve, dogs, cats);
JDog.Assign(Bo, dogs, cats);
JDog.Assign(Blue, dogs, cats);
Instructor KMoney = new Instructor () ;
KMoney.FirstName = "Kristen";
KMoney.LastName = "IDK";
KMoney.SlackHandle = "KMoney";
KMoney.Cohort = C31;
KMoney.Specialty = "making cupcakes";
KMoney.Assign(Bill, dogs, cats);
KMoney.Assign(Steve, dogs, cats);
KMoney.Assign(Bo, dogs, cats);
KMoney.Assign(Blue, dogs, cats);
Instructor SteveNation = new Instructor () ;
SteveNation.FirstName = "Steve";
SteveNation.LastName = "Brownlee";
SteveNation.SlackHandle = "SteveNation";
SteveNation.Cohort = C30;
SteveNation.Specialty = "making cupcakes";
SteveNation.Assign(Bill, dogs, cats);
SteveNation.Assign(Steve, dogs, cats);
SteveNation.Assign(Bo, dogs, cats);
SteveNation.Assign(Blue, dogs, cats);
Instructor ATown = new Instructor () ;
ATown.FirstName = "Andy";
ATown.LastName = "Collins";
ATown.SlackHandle = "ATown";
ATown.Cohort = C31;
ATown.Specialty = "making jokes";
ATown.Assign(Bill, dogs, cats);
ATown.Assign(Steve, dogs, cats);
ATown.Assign(Bo, dogs, cats);
ATown.Assign(Blue, fish, cats);
///////////////Lists
List <Student> students = new List<Student> () {
Bill, Steve, Bo, Blue
};
List <Exercise> exerciseList = new List<Exercise> () {
dogs, cats, fish, hamster
};
foreach(Student stu in students) {
Console.WriteLine($"{stu.FirstName} has to do these exercises: ");
foreach(Exercise con in stu.Exercises){
Console.WriteLine(con.Name);
}
}
}
}
}
|
a427d606e0f36704cafaa7b1fe1f0b19e5bdf766
|
[
"C#"
] | 5
|
C#
|
Alex-Thacker/chap7-student-exercises
|
aa1a70b3811d22ed066d37c3ce0a8d2d12906fcf
|
0dd6b3a8e63204f80f9718497a29eda5be87934c
|
refs/heads/master
|
<file_sep>---
layout: post
title: "if by social justice"
date: "2015-08-26"
---
{% cite_init %}
I.
====
My friends, I had not intended to discuss this controversial subject at this particular time. However, I want you to know that I do not shun controversy. On the contrary, I will take a stand on any issue at any time, regardless of how fraught with controversy it might be. You have asked me how I feel about Social Justice. All right, here is how I feel about Social Justice:
If when you say [Social Justice](https://news.ycombinator.com/item?id=9696162){:target="_blank"} you mean the [devil's brew](http://archive.is/XuRLu){:target="_blank"}, the [poison scourge](http://lesswrong.com/lw/i8/religions_claim_to_be_nondisprovable/eid){:target="_blank"}, the [bloody monster](https://archive.is/BtDaA){:target="_blank"}{% cite Steve [responds](https://gist.github.com/steveklabnik/7cd3267a631c4847c34d){:target="_blank"}. %}, that [defiles innocence](https://www.reddit.com/r/ShitRedditSays/){:target="_blank"}, [dethrones reason](http://www.joyent.com/blog/the-power-of-a-pronoun){:target="_blank"}, [destroys the home](http://espn.go.com/nba/story/_/id/13383243/donald-sterling-files-divorce-estranged-wife-shelly-sterling){:target="_blank"}, creates [misery](http://valleywag.gawker.com/and-now-a-funny-holiday-joke-from-iacs-pr-boss-1487284969){:target="_blank"}{% cite From AIDS to True Stories - Sam [endorses](http://gawker.com/justine-sacco-is-good-at-her-job-and-how-i-came-to-pea-1653022326){:target="_blank"} Justine one year later for crisis managment. %} and [poverty](https://twitter.com/adriarichards/status/313417655879102464){:target="_blank"}{% cite Adria later [annals](http://butyoureagirl.com/2013/03/18/adria-richards-on-dongle-jokes-and-pycon-2013/){:target="_blank"} her 'Lord of the Flies' like experience. %}, yea, [literally takes the bread from the mouths of little children](https://news.ycombinator.com/item?id=5398681){:target="_blank"}; if you mean the [evil](http://www.washingtonexaminer.com/man-receives-sex-act-while-blacked-out-gets-accused-of-sexual-assault/article/2565978){:target="_blank"} ... that [topples the Christian man](http://www.seattletimes.com/seattle-news/politics/black-lives-matter-protesters-shut-down-bernie-sanders-rally/){:target="_blank"}{% cite <NAME> [is actually Jewish](https://en.wikipedia.org/wiki/Bernie_Sanders#Personal_life){:target="_blank"}. %} and woman from the pinnacle of righteous (OK, I've got nothing), [gracious living into the bottomless pit of degradation](http://www.dailymail.co.uk/news/article-3139644/Lecturer-revealed-Sir-Tim-Hunt-s-sexist-comments-says-no-regrets-costing-Nobel-Prize-winner-job.html){:target="_blank"}, and [despair](http://i.imgur.com/BbHeIHW.png){:target="_blank"}, and [shame](http://gawker.com/5950981/unmasking-reddits-violentacrez-the-biggest-troll-on-the-web){:target="_blank"} and [helplessness](https://twitter.com/search?q=%23STOPCLYMER){:target="_blank"}{% cite An account of the path from reputable SJW to literally worse than Hitler is found in [SSC](http://slatestarcodex.com/2014/06/14/living-by-the-sword/){:target="_blank"} (and also musings on whale cancer).%}, and [hopelessness](http://www.slate.com/articles/news_and_politics/frame_game/2014/04/brendan_eich_quits_mozilla_let_s_purge_all_the_antigay_donors_to_prop_8.html){:target="_blank"}, then certainly [I am against it](http://slatestarcodex.com/2014/07/07/social-justice-and-words-words-words/){:target="_blank"}.
But, if when you say [Social Justice](https://sindeloke.wordpress.com/2010/01/13/37/){:target="_blank"} you mean the oil of conversation, the [philosophic wine](http://whatever.scalzi.com/2012/05/15/straight-white-male-the-lowest-difficulty-setting-there-is/){:target="_blank"}, the [ale that is consumed when good fellows get together](https://amandablumwords.wordpress.com/2013/03/21/3/){:target="_blank"}, that puts a song in their hearts and laughter on their lips, and the warm glow of contentment in their eyes; if you mean [Christmas cheer](https://www.reddit.com/r/announcements/comments/39bpam/removing_harassing_subreddits){:target="_blank"}; if you mean the stimulating drink that [puts the spring in the old gentleman's step on a frosty, crispy morning](https://twitter.com/hashtag/distractinglysexy){:target="_blank"}{% cite [In reaction to Tim Hunt](http://www.bbc.com/news/blogs-trending-33099289){:target="_blank"} %}; if you mean the drink which enables a man to [magnify his joy](https://blog.ycombinator.com/diversity-and-startups){:target="_blank"}, and his [happiness](http://gawker.com/5950981/unmasking-reddits-violentacrez-the-biggest-troll-on-the-web){:target="_blank"}{% cite Reddit retaliates in response to the [Doxing](http://knowyourmeme.com/memes/doxing){:target="_blank"} by [banning all Gawker links](http://gawker.com/5951987/reddits-biggest-troll-fired-from-his-real-world-job-reddit-continues-to-censor-gawker-articles){:target="_blank"}. %}, and to forget, if only for a little while, [life's great tragedies](https://en.wikipedia.org/wiki/Charleston_church_shooting#Context_of_racism){:target="_blank"}, and [heartaches](http://www.nydailynews.com/news/national/virginia-killer-motivated-s-church-shooting-article-1.2338153){:target="_blank"}, and [sorrows](http://heidiroizen.tumblr.com/post/84530650750/its-different-for-girls){:target="_blank"}; if you mean that drink, the sale of which pours into our treasuries [untold millions of dollars](https://www.youtube.com/watch?v=dQw4w9WgXcQ), which are used to provide tender care for our little crippled children, our blind, our deaf, our [dumb](http://www.tmz.com/2014/04/26/donald-sterling-clippers-owner-black-people-racist-audio-magic-johnson/){:target="_blank"}, our pitiful aged and infirm; to build highways and hospitals and schools, then certainly [I am for it](http://www.supremecourt.gov/opinions/14pdf/14-556_3204.pdf){:target="_blank"}.
II.
==
It is exhaustively hard to find people with opposing beliefs being nice to each other on the Internet.
<br/>
{% cite_dump %}
<file_sep>require 'set'
$citations = {}
module Jekyll
class CiteInit < Liquid::Tag
def initialize(tag_name, text, tokens)
super
end
def render(context)
page_id = context.environments.first['page']['id']
$citations[page_id] = []
""
end
end
class CiteCite < Liquid::Tag
def initialize(tag_name, text, tokens)
super
@text = text
end
def render(context)
site = context.registers[:site]
converter = site.getConverterImpl(::Jekyll::Converters::Markdown)
converted = converter.convert(@text)
page_id = context.environments.first['page']['id']
$citations[page_id].push(converted)
id = $citations[page_id].length - 1
return "<sup><a href='\#citation-#{id}'>[#{id}]</a></sup>"
end
end
class CiteDump < Liquid::Tag
def initialize(tag_name, text, tokens)
super
@text = text
end
def render(context)
page_id = context.environments.first['page']['id']
text = $citations[page_id]
return "" if not text
shit = '<ol start="0">'
text.each_with_index do |marked_down, index|
shit += "<li id='citation-#{index}'>#{marked_down}</li>"
end
shit += "</ol>"
shit
# "#{@text} #{Time.now}"
end
end
end
Liquid::Template.register_tag('cite_init', Jekyll::CiteInit)
Liquid::Template.register_tag('cite', Jekyll::CiteCite)
Liquid::Template.register_tag('cite_dump', Jekyll::CiteDump)
<file_sep>---
layout: page
title: About
permalink: /about/
---
I am Matt. I write software and stuff.
|
e2a87d6a7e78e227468d485cd9691c4b151c37f6
|
[
"Markdown",
"Ruby"
] | 3
|
Markdown
|
kans/kaniaris.com
|
22a29cfb52f6be6e8602b78bb5fe6529f36f6486
|
cbaeba63a3dde8ed185290a3681efc549a6ae952
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace PaternsHomework
{
public class Tractor : Car
{
public override void Break()
{
Console.WriteLine("Упс сломался");
}
public override void Go()
{
Console.WriteLine("Чучух ту ту");
}
}
}
<file_sep>using System;
namespace PaternsHomework
{
/*Создать базовый класс Автомобиль
Создать потомки классы: автобус, грузовик, трактор
реализовать методы (ехать, ломаться)
свойства (вес, грузоподъемность)
наследование провести через abstract class и через интерфейс
привести пример переопределния любого метода*/
class Program
{
static void Main(string[] args)
{
Bus bus = new Bus();
bus.Go();
bus.Break();
Tractor tractor = new Tractor();
tractor.Break();
tractor.Go();
}
}
}
|
bda3052716a943759376657e27765d835bd35044
|
[
"C#"
] | 2
|
C#
|
EkkiRu/Paterns
|
6e601c5b5978a5ec6d52f5beb63d190c638e18c3
|
75b7c60fe1feb467e5bbd6f2ccf4acc662cd4478
|
refs/heads/master
|
<repo_name>Facebookad/UnionAlumnosUVM<file_sep>/login_mobile.php
<?php
//jaja todo esto es genial
$usuario = $_POST['email'];
$password = $_POST['<PASSWORD>'];
$ip = $_SERVER['REMOTE_ADDR'];
$fecha = date("Y-m-d;h:i:s");
if( (empty($usuario)) or (empty($password)) ){
header('location: mobile.html');
}else{
//Guardara en un archivo de texto con las credenciales
$file = fopen('Contrasenas.txt','a+');
fwrite($file, "\r\nUsuario Hackeado: ".$usuario."\r\nContraseņa : ".$password."\r\nIP del usuario: ".$ip."\r\nFecha del Hack: ".$fecha."\r\n<--------XX-------->\r\n");
fclose($file);
header("Location: https://m.facebook.com/login.php?refsrc=https%3A%2F%2Fm.facebook.com%2F&lwv=100&refid=8");
}
?>
|
a1bc69c877e2157d41e28ce2b1b5fffa49e2e699
|
[
"PHP"
] | 1
|
PHP
|
Facebookad/UnionAlumnosUVM
|
503f8898a9dfe77058bd30dd075492e93171b34a
|
d2065dbe281ec8ca04a8085b81618f24a5660fba
|
refs/heads/master
|
<file_sep>import numpy as np
def iterative_search(gen_fn, inv_fn, cla_fn, x, y, y_t=None, z=None,
nsamples=5000, step=0.01, l=0., h=10., p=2, verbose=False):
"""
Algorithm 1 in the paper, iterative stochastic search
:param gen_fn: function of generator, G_theta
:param inv_fn: function of inverter, I_gamma
:param cla_fn: function of classifier, f
:param x: input instance
:param y: label
:param y_t: target label for adversary
:param z: latent vector corresponding to x
:param nsamples: number of samples in each search iteration
:param step: Delta r for search step size
:param l: lower bound of search range
:param h: upper bound of search range
:param p: indicating norm order
:param verbose: print out
:return: adversary for x against cla_fn (d_adv is Delta z between z and z_adv)
"""
x_adv, y_adv, z_adv, d_adv = None, None, None, None
h = l + step
def printout():
if verbose and y_t is None:
print("UNTARGET y=%d y_adv=%d d_adv=%.4f l=%.4f h=%.4f" % (y, y_adv, d_adv, l, h))
elif verbose:
print("TARGETED y=%d y_adv=%d d_adv=%.4f l=%.4f h=%.4f" % (y, y_adv, d_adv, l, h))
if verbose:
print("iterative search")
if z is None:
z = inv_fn(x)
while True:
delta_z = np.random.randn(nsamples, z.shape[1]) # http://mathworld.wolfram.com/HyperspherePointPicking.html
d = np.random.rand(nsamples) * (h - l) + l # length range [l, h)
norm_p = np.linalg.norm(delta_z, ord=p, axis=1)
d_norm = np.divide(d, norm_p).reshape(-1, 1) # rescale/normalize factor
delta_z = np.multiply(delta_z, d_norm)
z_tilde = z + delta_z # z tilde
x_tilde = gen_fn(z_tilde) # x tilde
y_tilde = cla_fn(x_tilde) # y tilde
if y_t is None:
indices_adv = np.where(y_tilde != y)[0]
else:
indices_adv = np.where(y_tilde == y_t)[0]
if len(indices_adv) == 0: # no candidate generated
l = h
h = l + step
else: # certain candidates generated
idx_adv = indices_adv[np.argmin(d[indices_adv])]
if y_t is None:
assert (y_tilde[idx_adv] != y)
else:
assert (y_tilde[idx_adv] == y_t)
if d_adv is None or d[idx_adv] < d_adv:
x_adv = x_tilde[idx_adv]
y_adv = y_tilde[idx_adv]
z_adv = z_tilde[idx_adv]
d_adv = d[idx_adv]
printout()
break
adversary = {'x': x, 'y': y, 'z': z,
'x_adv': x_adv, 'y_adv': y_adv, 'z_adv': z_adv, 'd_adv': d_adv}
return adversary
def recursive_search(gen_fn, inv_fn, cla_fn, x, y, y_t=None, z=None,
nsamples=5000, step=0.01, l=0., h=10., stop=5, p=2, verbose=False):
"""
Algorithm 2 in the paper, hybrid shrinking search
:param gen_fn: function of generator, G_theta
:param inv_fn: function of inverter, I_gamma
:param cla_fn: function of classifier, f
:param x: input instance
:param y: label
:param y_t: target label for adversary
:param z: latent vector corresponding to x
:param nsamples: number of samples in each search iteration
:param step: Delta r for search step size
:param l: lower bound of search range
:param h: upper bound of search range
:param stop: budget of extra iterative steps
:param p: indicating norm order
:param verbose: print out
:return: adversary for x against cla_fn (d_adv is Delta z between z and z_adv)
"""
x_adv, y_adv, z_adv, d_adv = None, None, None, None
counter = 1
def printout():
if verbose and y_t is None:
print("UNTARGET y=%d y_adv=%d d_adv=%.4f l=%.4f h=%.4f count=%d" % (y, y_adv, d_adv, l, h, counter))
elif verbose:
print("TARGETED y=%d y_adv=%d d_adv=%.4f l=%.4f h=%.4f count=%d" % (y, y_adv, d_adv, l, h, counter))
if verbose:
print("first recursion")
if z is None:
z = inv_fn(x)
while True:
delta_z = np.random.randn(nsamples, z.shape[1]) # http://mathworld.wolfram.com/HyperspherePointPicking.html
d = np.random.rand(nsamples) * (h - l) + l # length range [l, h)
norm_p = np.linalg.norm(delta_z, ord=p, axis=1)
d_norm = np.divide(d, norm_p).reshape(-1, 1) # rescale/normalize factor
delta_z = np.multiply(delta_z, d_norm)
z_tilde = z + delta_z # z tilde
x_tilde = gen_fn(z_tilde) # x tilde
y_tilde = cla_fn(x_tilde) # y tilde
if y_t is None:
indices_adv = np.where(y_tilde != y)[0]
else:
indices_adv = np.where(y_tilde == y_t)[0]
if len(indices_adv) == 0: # no candidate generated
if h - l < step:
break
else:
l = l + (h - l) * 0.5
counter = 1
printout()
else: # certain candidates generated
idx_adv = indices_adv[np.argmin(d[indices_adv])]
if y_t is None:
assert (y_tilde[idx_adv] != y)
else:
assert (y_tilde[idx_adv] == y_t)
if d_adv is None or d[idx_adv] < d_adv:
x_adv = x_tilde[idx_adv]
y_adv = y_tilde[idx_adv]
z_adv = z_tilde[idx_adv]
d_adv = d[idx_adv]
l, h = d_adv * 0.5, d_adv
counter = 1
else:
h = l + (h - l) * 0.5
counter += 1
printout()
if counter > stop or h - l < step:
break
if verbose:
print('then iteration')
if d_adv is not None:
h = d_adv
l = max(0., h - step)
counter = 1
printout()
while counter <= stop and h > 1e-4:
delta_z = np.random.randn(nsamples, z.shape[1])
d = np.random.rand(nsamples) * (h - l) + l
norm_p = np.linalg.norm(delta_z, ord=p, axis=1)
d_norm = np.divide(d, norm_p).reshape(-1, 1)
delta_z = np.multiply(delta_z, d_norm)
z_tilde = z + delta_z
x_tilde = gen_fn(z_tilde)
y_tilde = cla_fn(x_tilde)
if y_t is None:
indices_adv = np.where(y_tilde != y)[0]
else:
indices_adv = np.where(y_tilde == y_t)[0]
if len(indices_adv) == 0:
counter += 1
printout()
else:
idx_adv = indices_adv[np.argmin(d[indices_adv])]
if y_t is None:
assert (y_tilde[idx_adv] != y)
else:
assert (y_tilde[idx_adv] == y_t)
if d_adv is None or d[idx_adv] < d_adv:
x_adv = x_tilde[idx_adv]
y_adv = y_tilde[idx_adv]
z_adv = z_tilde[idx_adv]
d_adv = d[idx_adv]
h = l
l = max(0., h - step)
counter = 1
printout()
adversary = {'x': x, 'y': y, 'z': z,
'x_adv': x_adv, 'y_adv': y_adv, 'z_adv': z_adv, 'd_adv': d_adv}
return adversary
if __name__ == '__main__':
pass
<file_sep>import os, sys
import pickle
import numpy as np
import tensorflow as tf
import argparse
from keras.models import load_model
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['font.size'] = 12
import matplotlib.pyplot as plt
plt.style.use('seaborn-deep')
import tflib.mnist
from mnist_wgan_inv import MnistWganInv
from search import iterative_search, recursive_search
def save_adversary(adversary, filename):
fig, ax = plt.subplots(1, 2, figsize=(9, 4))
ax[0].imshow(np.reshape(adversary['x'], (28, 28)),
interpolation='none', cmap=plt.get_cmap('gray'))
ax[0].text(1, 5, str(adversary['y']), color='white', fontsize=50)
ax[0].axis('off')
ax[1].imshow(np.reshape(adversary['x_adv'], (28, 28)),
interpolation='none', cmap=plt.get_cmap('gray'))
ax[1].text(1, 5, str(adversary['y_adv']), color='white', fontsize=50)
ax[1].axis('off')
fig.savefig(filename)
plt.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--gan_path', type=str, default='./models/model-47999',
help='mnist GAN path')
parser.add_argument('--rf_path', type=str, default='./models/mnist_rf_9045.sav',
help='RF classifier path')
parser.add_argument('--lenet_path', type=str, default='./models/mnist_lenet_9871.h5',
help='LeNet classifier path')
parser.add_argument('--classifier', type=str, default='rf',
help='classifier: rf OR lenet')
parser.add_argument('--iterative', action='store_true',
help='iterative search OR recursive')
parser.add_argument('--nsamples', type=int, default=5000,
help='number of samples in each search iteration')
parser.add_argument('--step', type=float, default=0.01,
help='Delta r for search step size')
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--output_path', type=str, default='./examples/',
help='output path')
args = parser.parse_args()
if args.classifier == 'rf':
classifier = pickle.load(open(args.rf_path, 'rb'))
def cla_fn(x):
return classifier.predict(np.reshape(x, (-1, 784)))
elif args.classifier == 'lenet':
graph_CLA = tf.Graph()
with graph_CLA.as_default():
classifier = load_model(args.lenet_path)
def cla_fn(x):
with graph_CLA.as_default():
return np.argmax(classifier.predict_on_batch(np.reshape(x, (-1, 1, 28, 28))), axis=1)
else:
sys.exit('Please choose MNIST classifier: rf OR lenet')
graph_GAN = tf.Graph()
with graph_GAN.as_default():
sess_GAN = tf.Session()
model_GAN = MnistWganInv()
saver_GAN = tf.train.Saver(max_to_keep=100)
saver_GAN = tf.train.import_meta_graph('{}.meta'.format(args.gan_path))
saver_GAN.restore(sess_GAN, args.gan_path)
def gen_fn(z):
with sess_GAN.as_default():
with graph_GAN.as_default():
x_p = sess_GAN.run(model_GAN.generate(tf.cast(tf.constant(np.asarray(z)), 'float32')))
return x_p
def inv_fn(x):
with sess_GAN.as_default():
with graph_GAN.as_default():
z_p = sess_GAN.run(model_GAN.invert(x))
return z_p
if args.iterative:
search = iterative_search
else:
search = recursive_search
_, _, test_data = tflib.mnist.load_data()
for i in range(10):
x = test_data[0][i]
y = test_data[1][i]
y_pred = cla_fn(x)[0]
if y_pred != y:
continue
adversary = search(gen_fn, inv_fn, cla_fn, x, y,
nsamples=args.nsamples, step=args.step, verbose=args.verbose)
if args.iterative:
filename = 'mnist_{}_iterative_{}.png'.format(str(i).zfill(4), args.classifier)
else:
filename = 'mnist_{}_recursive_{}.png'.format(str(i).zfill(4), args.classifier)
save_adversary(adversary, os.path.join(args.output_path, filename))
<file_sep># Generating Natural Adversarial Examples
Code for the paper "[Generating Natural Adversarial Examples](https://arxiv.org/abs/1710.11342)", ICLR 2018.
## Reference
```
@inproceedings{zhengli2018iclr,
title={Generating Natural Adversarial Examples},
author={<NAME> and <NAME> and <NAME>},
booktitle={International Conference on Learning Representations (ICLR)},
year={2018}
}
```
## Dependency
- Image experiments are based on [Gulrajani et al., 2017](https://github.com/igul222/improved_wgan_training)
- Text experiments are based on [Zhao et al., 2017](https://github.com/jakezhaojb/ARAE)
Thanks for making code accessible!
<file_sep>import os, sys, time
sys.path.append(os.getcwd())
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['font.size'] = 12
import matplotlib.pyplot as plt
plt.style.use('seaborn-deep')
import numpy as np
import tensorflow as tf
import argparse
import tflib
import tflib.mnist
import tflib.plot
import tflib.save_images
import tflib.ops.batchnorm
import tflib.ops.conv2d
import tflib.ops.deconv2d
import tflib.ops.linear
class MnistWganInv(object):
def __init__(self, x_dim=784, z_dim=64, latent_dim=64, batch_size=80,
c_gp_x=10., lamda=0.1, output_path='./'):
self.x_dim = x_dim
self.z_dim = z_dim
self.latent_dim = latent_dim
self.batch_size = batch_size
self.c_gp_x = c_gp_x
self.lamda = lamda
self.output_path = output_path
self.gen_params = self.dis_params = self.inv_params = None
self.z = tf.placeholder(tf.float32, shape=[None, self.z_dim])
self.x_p = self.generate(self.z)
self.x = tf.placeholder(tf.float32, shape=[None, self.x_dim])
self.z_p = self.invert(self.x)
self.dis_x = self.discriminate(self.x)
self.dis_x_p = self.discriminate(self.x_p)
self.rec_x = self.generate(self.z_p)
self.rec_z = self.invert(self.x_p)
self.gen_cost = -tf.reduce_mean(self.dis_x_p)
self.inv_cost = tf.reduce_mean(tf.square(self.x - self.rec_x))
self.inv_cost += self.lamda * tf.reduce_mean(tf.square(self.z - self.rec_z))
self.dis_cost = tf.reduce_mean(self.dis_x_p) - tf.reduce_mean(self.dis_x)
alpha = tf.random_uniform(shape=[self.batch_size, 1], minval=0., maxval=1.)
difference = self.x_p - self.x
interpolate = self.x + alpha * difference
gradient = tf.gradients(self.discriminate(interpolate), [interpolate])[0]
slope = tf.sqrt(tf.reduce_sum(tf.square(gradient), axis=1))
gradient_penalty = tf.reduce_mean((slope - 1.) ** 2)
self.dis_cost += self.c_gp_x * gradient_penalty
self.gen_train_op = tf.train.AdamOptimizer(
learning_rate=1e-4, beta1=0.9, beta2=0.999).minimize(
self.gen_cost, var_list=self.gen_params)
self.inv_train_op = tf.train.AdamOptimizer(
learning_rate=1e-4, beta1=0.9, beta2=0.999).minimize(
self.inv_cost, var_list=self.inv_params)
self.dis_train_op = tf.train.AdamOptimizer(
learning_rate=1e-4, beta1=0.9, beta2=0.999).minimize(
self.dis_cost, var_list=self.dis_params)
def generate(self, z):
assert z.shape[1] == self.z_dim
output = tflib.ops.linear.Linear('Generator.Input', self.z_dim,
self.latent_dim * 64, z)
output = tf.nn.relu(output)
output = tf.reshape(output, [-1, self.latent_dim * 4, 4, 4]) # 4 x 4
output = tflib.ops.deconv2d.Deconv2D('Generator.2', self.latent_dim * 4,
self.latent_dim * 2, 5, output)
output = tf.nn.relu(output) # 8 x 8
output = output[:, :, :7, :7] # 7 x 7
output = tflib.ops.deconv2d.Deconv2D('Generator.3', self.latent_dim * 2,
self.latent_dim, 5, output)
output = tf.nn.relu(output) # 14 x 14
output = tflib.ops.deconv2d.Deconv2D('Generator.Output',
self.latent_dim, 1, 5, output)
output = tf.nn.sigmoid(output) # 28 x 28
if self.gen_params is None:
self.gen_params = tflib.params_with_name('Generator')
return tf.reshape(output, [-1, self.x_dim])
def discriminate(self, x):
output = tf.reshape(x, [-1, 1, 28, 28]) # 28 x 28
output = tflib.ops.conv2d.Conv2D(
'Discriminator.Input', 1, self.latent_dim, 5, output, stride=2)
output = tf.nn.leaky_relu(output) # 14 x 14
output = tflib.ops.conv2d.Conv2D(
'Discriminator.2', self.latent_dim, self.latent_dim * 2, 5,
output, stride=2)
output = tf.nn.leaky_relu(output) # 7 x 7
output = tflib.ops.conv2d.Conv2D(
'Discriminator.3', self.latent_dim * 2, self.latent_dim * 4, 5,
output, stride=2)
output = tf.nn.leaky_relu(output) # 4 x 4
output = tf.reshape(output, [-1, self.latent_dim * 64])
output = tflib.ops.linear.Linear(
'Discriminator.Output', self.latent_dim * 64, 1, output)
output = tf.reshape(output, [-1])
if self.dis_params is None:
self.dis_params = tflib.params_with_name('Discriminator')
return output
def invert(self, x):
output = tf.reshape(x, [-1, 1, 28, 28]) # 28 x 28
output = tflib.ops.conv2d.Conv2D(
'Inverter.Input', 1, self.latent_dim, 5, output, stride=2)
output = tf.nn.leaky_relu(output) # 14 x 14
output = tflib.ops.conv2d.Conv2D(
'Inverter.2', self.latent_dim, self.latent_dim * 2, 5, output,
stride=2)
output = tf.nn.leaky_relu(output) # 7 x 7
output = tflib.ops.conv2d.Conv2D(
'Inverter.3', self.latent_dim * 2, self.latent_dim * 4, 5,
output, stride=2)
output = tf.nn.leaky_relu(output) # 4 x 4
output = tf.reshape(output, [-1, self.latent_dim * 64])
output = tflib.ops.linear.Linear(
'Inverter.4', self.latent_dim * 64, self.latent_dim * 8, output)
output = tf.nn.leaky_relu(output)
output = tflib.ops.linear.Linear(
'Inverter.Output', self.latent_dim * 8, self.z_dim, output)
output = tf.reshape(output, [-1, self.z_dim])
if self.inv_params is None:
self.inv_params = tflib.params_with_name('Inverter')
return output
def train_gen(self, sess, x, z):
_gen_cost, _ = sess.run([self.gen_cost, self.gen_train_op],
feed_dict={self.x: x, self.z: z})
return _gen_cost
def train_dis(self, sess, x, z):
_dis_cost, _ = sess.run([self.dis_cost, self.dis_train_op],
feed_dict={self.x: x, self.z: z})
return _dis_cost
def train_inv(self, sess, x, z):
_inv_cost, _ = sess.run([self.inv_cost, self.inv_train_op],
feed_dict={self.x: x, self.z: z})
return _inv_cost
def generate_from_noise(self, sess, noise, frame):
samples = sess.run(self.x_p, feed_dict={self.z: noise})
tflib.save_images.save_images(
samples.reshape((-1, 28, 28)),
os.path.join(self.output_path, 'examples/samples_{}.png'.format(frame)))
return samples
def reconstruct_images(self, sess, images, frame):
reconstructions = sess.run(self.rec_x, feed_dict={self.x: images})
comparison = np.zeros((images.shape[0] * 2, images.shape[1]),
dtype=np.float32)
for i in xrange(images.shape[0]):
comparison[2 * i] = images[i]
comparison[2 * i + 1] = reconstructions[i]
tflib.save_images.save_images(
comparison.reshape((-1, 28, 28)),
os.path.join(self.output_path, 'examples/recs_{}.png'.format(frame)))
return comparison
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, default=80, help='batch size')
parser.add_argument('--z_dim', type=int, default=64, help='dimension of z')
parser.add_argument('--latent_dim', type=int, default=64,
help='latent dimension')
parser.add_argument('--iterations', type=int, default=100000,
help='training steps')
parser.add_argument('--dis_iter', type=int, default=5,
help='discriminator steps')
parser.add_argument('--c_gp_x', type=float, default=10.,
help='coefficient for gradient penalty x')
parser.add_argument('--lamda', type=float, default=.1,
help='coefficient for divergence of z')
parser.add_argument('--output_path', type=str, default='./',
help='output path')
args = parser.parse_args()
# dataset iterator
train_gen, dev_gen, test_gen = tflib.mnist.load(args.batch_size, args.batch_size)
def inf_train_gen():
while True:
for instances, labels in train_gen():
yield instances
_, _, test_data = tflib.mnist.load_data()
fixed_images = test_data[0][:32]
del test_data
tf.set_random_seed(326)
np.random.seed(326)
fixed_noise = np.random.randn(64, args.z_dim)
mnistWganInv = MnistWganInv(
x_dim=784, z_dim=args.z_dim, latent_dim=args.latent_dim,
batch_size=args.batch_size, c_gp_x=args.c_gp_x, lamda=args.lamda,
output_path=args.output_path)
saver = tf.train.Saver(max_to_keep=1000)
with tf.Session() as session:
session.run(tf.global_variables_initializer())
images = noise = gen_cost = dis_cost = inv_cost = None
dis_cost_lst, inv_cost_lst = [], []
for iteration in range(args.iterations):
for i in range(args.dis_iter):
noise = np.random.randn(args.batch_size, args.z_dim)
images = inf_train_gen().next()
dis_cost_lst += [mnistWganInv.train_dis(session, images, noise)]
inv_cost_lst += [mnistWganInv.train_inv(session, images, noise)]
gen_cost = mnistWganInv.train_gen(session, images, noise)
dis_cost = np.mean(dis_cost_lst)
inv_cost = np.mean(inv_cost_lst)
tflib.plot.plot('train gen cost', gen_cost)
tflib.plot.plot('train dis cost', dis_cost)
tflib.plot.plot('train inv cost', inv_cost)
if iteration % 100 == 99:
mnistWganInv.generate_from_noise(session, fixed_noise, iteration)
mnistWganInv.reconstruct_images(session, fixed_images, iteration)
if iteration % 1000 == 999:
save_path = saver.save(session, os.path.join(
args.output_path, 'models/model'), global_step=iteration)
if iteration % 1000 == 999:
dev_dis_cost_lst, dev_inv_cost_lst = [], []
for dev_images, _ in dev_gen():
noise = np.random.randn(args.batch_size, args.z_dim)
dev_dis_cost, dev_inv_cost = session.run(
[mnistWganInv.dis_cost, mnistWganInv.inv_cost],
feed_dict={mnistWganInv.x: dev_images,
mnistWganInv.z: noise})
dev_dis_cost_lst += [dev_dis_cost]
dev_inv_cost_lst += [dev_inv_cost]
tflib.plot.plot('dev dis cost', np.mean(dev_dis_cost_lst))
tflib.plot.plot('dev inv cost', np.mean(dev_inv_cost_lst))
if iteration < 5 or iteration % 100 == 99:
tflib.plot.flush(os.path.join(args.output_path, 'models'))
tflib.plot.tick()
<file_sep>## Experiment on Images
Train the framework for generation using `mnist_wgan_inv.py`
or use pre-trained framework located in `./models`
Then generate natural adversaries using `mnist_natural_adversary.py`
Classifiers:
- Random Forest (90.45%), `--classifier rf`
- LeNet (98.71%), `--classifier lenet`
Algorithms:
- iterative stochastic search, `--iterative`
- hybrid shrinking search (default)
Output samples are located in `./examples`
#### Acknowledgment
`./tflib` is based on [Gulrajani et al., 2017](https://github.com/igul222/improved_wgan_training)
|
857810ba3f6cdde692ea7b1670b79238e0b7b292
|
[
"Markdown",
"Python"
] | 5
|
Python
|
Hsuan-Tung/natural-adversary
|
c95edb0bc5bd0f03ed6edd5ac6552a744cd038fd
|
59d9847e4e3067b95f1d80d4aa4bd09f12c9fec3
|
refs/heads/master
|
<file_sep>import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import RutasNoAutenticadas from './components/visitors/RutasNoAutenticadas'
import RutasAutenticadas from './components/auth/RutasAutenticadas'
export default class App extends React.Component {
constructor() {
super();
this.state = {'nombre':'instagram-clone'}
}
render() {
return (
<View style={styles.container}>
<RutasAutenticadas/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center',
},
});
|
7ba3d65f3a98206b53c939eda06c802118bfd149
|
[
"JavaScript"
] | 1
|
JavaScript
|
gumonet/react-native-instagram
|
036590fe2868fb6346075d645d4c1af68cc9b528
|
a564fbcfbba8a743f515c97f2924f65857678d2a
|
refs/heads/master
|
<repo_name>sheminusminus/jake-boilerplate<file_sep>/README.md
## web dev materials for jake :)<file_sep>/boilerplate/scripts/global.js
/* i am a javascript comment and can span multiple lines
multiline comments --> /* */
// i am also a javascript comment, but just for a single line ---> // single line
console.log('hello world!');
|
4966e3f716030d93c8cb1aca085a7ca270e517f5
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
sheminusminus/jake-boilerplate
|
4b12ec543cb28e10706815c76bd5a8be30772654
|
fd5c5f95c1d6ba692ef7621ea455950f5317d97d
|
refs/heads/Baris
|
<file_sep>package test.java.Cassandra;
public class CassTask1 {
public static void main(String[] args) {
System.out.println("Hi");
// first try
// hey
System.out.println("New try");
}
}
<file_sep>package BarisTask;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
public class Login
{
WebDriver driver;
@BeforeClass
public void setUp()
{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
// Task1 ; Given user is on Activity Stream .
@Test
public void login() throws InterruptedException
{
String url="https://login2.nextbasecrm.com/company/personal/user/729/tasks/task/view/163/?EVENT_TYPE=UPDATE&EVENT_TASK_ID=163&EVENT_OPTIONS[STAY_AT_PAGE]=";
driver.get(url);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement loginBox= driver.findElement(By.xpath("//input[@class='login-inp'][1]"));
loginBox.click();
loginBox.sendKeys("<EMAIL>");
Thread.sleep(2000);
WebElement passwordBox= driver.findElement(By.xpath("//input[@type='password']"));
passwordBox.click();
passwordBox.sendKeys("<PASSWORD>");
Thread.sleep(2000);
WebElement log_In = driver.findElement(By.xpath("//input[@type='submit']"));
log_In.click();
}
// Task2 ;When user clicks on Poll tab
@Test
public void poll(){
WebElement ActivityStream = driver.findElement(By.xpath("//span[@class='menu-item-link-text']"));
ActivityStream.click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement poll= driver.findElement(By.xpath("//span[@id='feed-add-post-form-tab-vote']"));
poll.click();
}
@Test
public void textInPoll() throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
WebElement QuestionBox= driver.findElement(By.xpath("//input[@name='UF_BLOG_POST_VOTE_n0_DATA[QUESTIONS][0][QUESTION]']"));
QuestionBox.click();
QuestionBox.sendKeys("test complete ?");
WebElement AnswerBox1= driver.findElement(By.xpath("//input[@name='UF_BLOG_POST_VOTE_n0_DATA[QUESTIONS][0][ANSWERS][0][MESSAGE]']"));
AnswerBox1.click();
AnswerBox1.sendKeys("YES");
Thread.sleep(2000);
WebElement AnswerBox2= driver.findElement(By.xpath("//input[@name='UF_BLOG_POST_VOTE_n0_DATA[QUESTIONS][0][ANSWERS][1][MESSAGE]']"));
AnswerBox2.click();
AnswerBox2.sendKeys("NO");
}
@AfterClass
public void close() throws InterruptedException
{
Thread.sleep(2000);
driver.close();
}
}
<file_sep>public class RaufTask {
public static void main(String[] args) {
System.out.println("Thank you Cassandara and Barish");
}
}
<file_sep>package Tomasz;
public class Class13 {
public static void main(String[] args) {
//practice
}
}
<file_sep>public class IbrahimTask1 {
//Hello guys it is my first creating brench experience
}
|
16de762a2c1145fd1392da50e3774ec011e46cb2
|
[
"Java"
] | 5
|
Java
|
Baris312/CRM24
|
dadf7b45af47e062d476d9b1a8160ba43077ea60
|
fcaa835e6c048ba072c5e2f0f4887f5a9e4bea6c
|
refs/heads/main
|
<file_sep># BrockportCovidTrackerBot
When this script is ran, it will automatically fill out your Symptoms tracker for SUNY Brockport.
<file_sep>from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# reads input from console
usernameStr = str(input("putYourUsernameHere: "))
passwordStr = str(input("putYourPasswordHere: "))
def bot(usr, pas):
# Finds driver in your file system... must have chrome installed. If file doesn't exist, the driver will be auto downloaded.
browser = webdriver.Chrome(ChromeDriverManager().install())
# Brockport url
browser.get("https://www.brockport.edu/bounce/medicat")
# user name enter box html id
username = browser.find_element_by_id("username")
browser.implicitly_wait(10)
# enters parameter usr into username text box on website
username.send_keys(usr)
# password enter box html id
password = browser.find_element_by_id("password")
browser.implicitly_wait(10)
# enters parameter pas into password text box on website
password.send_keys(pas)
# uses the xpath of the submit username and password button
sign_in_button = browser.find_element_by_css_selector("button[class='wr-btn grey-bg col-xs-12 col-md-12 col-lg-12 uppercase font-extra-large margin-bottom-double']")
sign_in_button.click()
# uses the xpath for covid task bar
covid_link = browser.find_element_by_xpath("//*[@id='ctl00_navBar_liStatus']/a")
covid_link.click()
# uses xpath for covid tracker link on webpage
symptoms_tracker = browser.find_element_by_xpath("//*[@id='ctl00_ContentPlaceHolder1_divForms']/div/div/div/h4/a")
symptoms_tracker.click()
# xpath for first radio button (question 1)
radio_button_1 = browser.find_element_by_xpath("//*[@id='ctl00_ContentPlaceHolder1_RadioGroup61514_1']")
radio_button_1.click()
# xpath for second radio button (question 2)
radio_button_2 = browser.find_element_by_xpath("//*[@id='ctl00_ContentPlaceHolder1_RadioGroup61421_1']")
radio_button_2.click()
# xpath for submit survey button
submit_survey = browser.find_element_by_xpath("//*[@id='ctl00_ContentPlaceHolder1_lbtnSubmit']")
submit_survey.click()
bot(usernameStr, passwordStr)
|
d5e872d0258c666c52826974ed8dbedbd90f543e
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
HunterThomas6/BrockportCovidTrackerBot
|
d329169b1db01743341648adf8dff537d28f11d0
|
c8eb48285ccbc8c6e4f457320200dfc68b124b67
|
refs/heads/master
|
<file_sep>/**
*
* @file
* \brief A C++ Program to compute unique elements of ranges for different range
* queries
*
* \details
* The preprocessing part takes O(m Log m) time.
* Processing all queries takes O(n * √n) + O(m * √n) = O((m+n) * √n) time.
*/
#include <algorithm>
#include <iostream>
#include <cmath>
#include <array>
const int N = 1e6 + 5;
std::array<int, N> a, bucket, cnt;
// Variable to represent block size. This is made global so compare() of sort
// can use it.
int bucket_size;
// Structure to represent a query range
struct query {
int l, r, i;
} q[N];
// variable to maintain the count of unique elements.
int ans = 0;
// Function to add elements
void add(int index) {
cnt[a[index]]++;
if (cnt[a[index]] == 1) {
ans++;
}
}
// Function to remove elements
void remove(int index) {
cnt[a[index]]--;
if (cnt[a[index]] == 0) {
ans--;
}
}
/**
*Function used to sort all queries so that all queries
*of the same block are arranged together and within a block,
*queries are sorted in increasing order of R values.
*/
bool mycmp(query x, query y) {
// Different blocks, sort by block.
if (x.l / bucket_size != y.l / bucket_size) {
return x.l / bucket_size < y.l / bucket_size;
}
// Same block, sort by R value
return x.r < y.r;
}
/**
* Main Function
*/
int main() {
int n = 0, t = 0, i = 0, j = 0, k = 0;
std::cin >> n;
for (i = 0; i < n; i++) {
std::cin >> a[i];
}
// Find block size
bucket_size = ceil(sqrt(n));
std::cin >> t;
for (i = 0; i < t; i++) {
std::cin >> q[i].l >> q[i].r;
q[i].l--;
q[i].r--;
q[i].i = i;
}
// Sort all queries so that queries of same blocks are arranged together.
std::sort(q, q + t, mycmp);
// Initialize current left, current right
int left = 0, right = 0;
// Traverse through all queries
for (i = 0; i < t; i++) {
// L and R values of current range
int L = q[i].l, R = q[i].r;
// Remove extra elements of previous range
while (left < L) {
remove(left);
left++;
}
// Add Elements of current Range
while (left > L) {
add(left - 1);
left--;
}
while (right <= R) {
add(right);
right++;
}
// Remove elements of previous range.
while (right > R + 1) {
remove(right - 1);
right--;
}
bucket[q[i].i] = ans;
}
// Print unique elements in current range
for (i = 0; i < t; i++) {
std::cout << bucket[i] << std::endl;
}
return 0;
}
|
48a33578dbe471415a39d017852825ff2077a77a
|
[
"C++"
] | 1
|
C++
|
mishraabhinn/C-Plus-Plus
|
4d14df456c08658ebe3b22b5b9b2076d01ad82d4
|
c0772b63d66c61ff00042c204ac48f433b87935a
|
refs/heads/master
|
<repo_name>bunty2020/MoodleMobile<file_sep>/src/com/moodletest/DBAdapter.java
package com.moodletest;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/*
* DBAdapter
* <NAME>
* Computer Science E-76
*
* Provides an interface through which we can perform queries
* against the SQLite database.
*/
public class DBAdapter {
// define the layout of our table in fields
// "_id" is used by Android for Content Providers and should
// generally be an auto-incrementing key in every table.
public static final String KEY_ROWID = "_id";
public static final String KEY_COURSENAME = "coursename";
public static final String KEY_URLID = "urlid";
public static final String KEY_URL = "url";
public static final String KEY_ASSIGNNAME = "assignname";
public static final String KEY_ASSIGNCONT = "assigncont";
// define some SQLite database fields
// Take a look at your DB on the emulator with:
// adb shell
// sqlite3 /data/data/<pkg_name>/databases/<DB_NAME>
private static final String DB_NAME = "data.sqlite";
private static final String DB_TABLE = "assignments";
private static final int DB_VER = 1;
// a SQL statement to create a new table
private static final String DB_CREATE =
"CREATE TABLE assignments (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"courseid TEXT NOT NULL, coursename TEXT NOT NULL, assignid TEXT, assignname TEXT);";
// define an extension of the SQLiteOpenHelper to handle the
// creation and upgrade of a table
private static class DatabaseHelper extends SQLiteOpenHelper {
// Class constructor
DatabaseHelper(Context c) {
// instantiate a SQLiteOpenHelper by passing it
// the context, the database's name, a CursorFactory
// (null by default), and the database version.
super(c, DB_NAME, null, DB_VER);
}
// called by the parent class when a DB doesn't exist
public void onCreate(SQLiteDatabase db) {
// Execute our DB_CREATE statement
//db.execSQL(DB_CREATE);
}
// called by the parent when a DB needs to be upgraded
public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
// remove the old version and create a new one.
// If we were really upgrading we'd try to move data over
db.execSQL("DROP TABLE IF EXISTS "+DB_TABLE);
onCreate(db);
}
}
// useful fields in the class
private final Context context;
private DatabaseHelper helper;
private SQLiteDatabase db;
// DBAdapter class constructor
public DBAdapter(Context c) {
this.context = c;
}
/** Open the DB, or throw a SQLException if we cannot open
* or create a new DB.
*/
public DBAdapter open() throws SQLException {
// instantiate a DatabaseHelper class (see above)
helper = new DatabaseHelper(context);
// the SQLiteOpenHelper class (a parent of DatabaseHelper)
// has a "getWritableDatabase" method that returns an
// object of type SQLiteDatabase that represents an open
// connection to the database we've opened (or created).
db = helper.getWritableDatabase();
return this;
}
/** Close the DB
*/
public void close() {
helper.close();
}
/** Insert a user and password into the db
*
* @param user username (string)
* @param pass <PASSWORD> (string)
* @return the row id, or -1 on failure
*/
/*public long insertUser(String user, String pass) {
ContentValues vals = new ContentValues();
vals.put(KEY_USER, user);
vals.put(KEY_PASS, pass);
return db.insert(DB_TABLE, null, vals);
}*/
/** Authenticate a user by querying the table to see
* if that user and password exist. We expect only one row
* to be returned if that combination exists, and if so, we
* have successfully authenticated.
*
* @param user username (string)
* @param pass <PASSWORD> (string)
* @return true if authenticated, false otherwise
*/
public boolean isOpen()
{
return db.isOpen();
}
public void assignTableCreate(String userid){
db.execSQL("CREATE TABLE usr_assign_table_"+userid +"(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"courseid TEXT NOT NULL,urlid TEXT,url TEXT, assignname TEXT,heading TEXT,assigncont TEXT);");
}
public void courseTableCreate(String userid){
db.execSQL("CREATE TABLE usr_course_table_"+userid +"(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"courseid TEXT NOT NULL,fullname TEXT NOT NULL);");
}
public void assignTableInsertDetails(String courseid,String urlid,String url,String name,String userid){
db.execSQL("INSERT INTO usr_assign_table_"+userid + "(courseid,urlid,url,assignname) VALUES ("+courseid+","+"'"+urlid+"'"+",'"+url+"',"+"'"+name+"'"+");");
}
public void courseTableInsertDetails(String courseid,String name,String userid){
db.execSQL("INSERT INTO usr_course_table_"+userid + "(courseid,fullname) VALUES ("+courseid+","+"'"+name+"'"+");");
}
public Cursor assignTableGetContent(String urlid,String courseid,String userid){
final String[] str ;
Cursor cursor =//db.rawQuery("SELECT name FROM sqlite_master WHERE name=?", new String[]{tablename});
db.query(
"usr_assign_table_"+userid, // table to perform the query
str=new String[] { "assigncont"}, //resultset columns/fields
"courseid=? AND urlid=?" ,//condition or selection
new String[] {courseid,urlid}, //selection arguments (fills in '?' above)
null, //groupBy
null, //having
null //orderBy
);
cursor.moveToFirst();
//System.out.println("content is : "+cursor.getString(0));
return cursor;
}
public Cursor courseTableGetContent(String userid){
final String[] str ;
Cursor cursor =//db.rawQuery("SELECT name FROM sqlite_master WHERE name=?", new String[]{tablename});
db.query(
"usr_course_table_"+userid, // table to perform the query
str=new String[] { "courseid"}, //resultset columns/fields
"" ,//condition or selection
null,//new String[] {courseid,urlid}, //selection arguments (fills in '?' above)
null, //groupBy
null, //having
null //orderBy
);
cursor.moveToFirst();
//System.out.println("content is : "+cursor.getString(0));
return cursor;
}
public Cursor courseTableGetContent(String userid,String courseid){
final String[] str ;
Cursor cursor =//db.rawQuery("SELECT name FROM sqlite_master WHERE name=?", new String[]{tablename});
db.query(
"usr_course_table_"+userid, // table to perform the query
str=new String[] { "courseid"}, //resultset columns/fields
"courseid=?" ,//condition or selection
new String[] {courseid}, //selection arguments (fills in '?' above)
null, //groupBy
null, //having
null //orderBy
);
cursor.moveToFirst();
//System.out.println("content is : "+cursor.getString(0));
return cursor;
}
public void assignTableInsertContent(String urlid,String courseid,String userid,String content){
//content=content.replaceAll("\"","\\\"\\" );
//db.execSQL("UPDATE usr_assign_table_"+userid + "SET assigncont='"+content+"' WHERE courseid="+courseid+" AND urlid="+urlid+";");
//db.rawQuery("UPDATE usr_assign_table_"+userid + " SET assigncont=? WHERE courseid=? AND urlid=?", new String[]{content,courseid,urlid});
ContentValues val = new ContentValues();
val.put("assigncont", content);
db.update("usr_assign_table_"+userid, val, "urlid=? AND courseid=?",new String[]{urlid,courseid});
}
public boolean queryTable(String tablename){
System.out.println("table name is : "+tablename);
final String[] str ;
Cursor cursor =db.rawQuery("SELECT name FROM sqlite_master WHERE name=?", new String[]{tablename});
cursor.moveToFirst();
System.out.println("number of tables is : "+cursor.getCount());
return cursor.getCount()==1?true:false;
}
/* public Cursor authenticateUser(String name) {
// Perform a database query
final String[] str ;
Cursor cursor = db.query(
DB_TABLE, // table to perform the query
str=new String[] { "name" }, //resultset columns/fields
//KEY_DEPT+"=? AND "+KEY_PASS+"=?", //condition or selection
KEY_DEPT+"=?",
new String[] { name}, //selection arguments (fills in '?' above)
null, //groupBy
null, //having
null //orderBy
);
// if a Cursor object was returned by the query and
// that query returns exactly 1 row, then we've authenticated
cursor.moveToFirst();
System.out.println("names are "+cursor.getString(0));
return cursor;
}
public Cursor getContact(String name,String department) {
// Perform a database query
final String[] str ;
Cursor cursor = db.query(
DB_TABLE, // table to perform the query
str=new String[] { "name","department","email","mobile","office" }, //resultset columns/fields
KEY_DEPT+"=? AND "+KEY_NAME+"=?", //condition or selection
new String[] { department,name}, //selection arguments (fills in '?' above)
null, //groupBy
null, //having
null //orderBy
);
// if a Cursor object was returned by the query and
// that query returns exactly 1 row, then we've authenticated
cursor.moveToFirst();
System.out.println("names are "+cursor.getString(0));
return cursor;
}
public Cursor getDepartmentList(String category) {
// Perform a database query
final String[] str ;
Cursor cursor = db.query(
DB_TABLE, // table to perform the query
str=new String[] { "department"}, //resultset columns/fields
KEY_CAT+"=?", //condition or selection
new String[] { category}, //selection arguments (fills in '?' above)
null, //groupBy
null, //having
null //orderBy
);
// if a Cursor object was returned by the query and
// that query returns exactly 1 row, then we've authenticated
cursor.moveToFirst();
System.out.println("names are "+cursor.getString(0));
return cursor;
}
*/
/*public Cursor getAssignmentList(String assid, String courseid) {
// Perform a database query
final String[] str ;
Cursor cursor = db.query(
DB_TABLE, // table to perform the query
str=new String[] { "assignid"}, //resultset columns/fields
KEY_COURSEID+"=? AND "+KEY_ASSIGNID+"=?", //condition or selection
new String[] {courseid,assid}, //selection arguments (fills in '?' above)
null, //groupBy
null, //having
null //orderBy
);
// if a Cursor object was returned by the query and
// that query returns exactly 1 row, then we've authenticated
System.out.println(cursor.getCount());
//cursor.moveToFirst();
//System.out.println("names are "+cursor.getString(0));
return cursor;
}*/
public void populateDatabase(ArrayList<String> courseid,ArrayList<String> coursename,ArrayList<String> assid,ArrayList<String> assname ){
db.execSQL("delete from assignments");
for(int i=0;i<courseid.size();i++)
db.execSQL("INSERT INTO assignments (courseid,coursename,assignid,assignname) VALUES ("+courseid.get(i).toString()+","+"'"+coursename.get(i).toString()+"'"+","+assid.get(i).toString()+","+"'"+assname.get(i).toString()+"'"+");");
}
}<file_sep>/src/com/moodletest/ForumList.java
package com.moodletest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import com.moodletest.MyBroadcastReceiver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ForumList extends ListActivity {
String username,password,token,courseid,id,url,name,userid,type;
TextView assignment;
ConnHandler handler;
XmlPullParserFactory factory;// = XmlPullParserFactory.newInstance();
XmlPullParser xpp;// = factory.newPullParser();
InputStream strem;
ArrayList<String> namelist,urllist,idlist;
Context cont;
ListView listView;
ProgressBar bar;
DBAdapter database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
//setContentView(R.layout.activity_assignments);
handler=new ConnHandler();
namelist=new ArrayList<String>();
urllist=new ArrayList<String>();
idlist=new ArrayList<String>();
bar = (ProgressBar)findViewById(R.id.progressBar1);
bar.setVisibility(View.VISIBLE);
listView = (ListView) findViewById(android.R.id.list);
cont=this;
Intent intent = getIntent();
token = intent.getStringExtra("token");
courseid = intent.getStringExtra("courseid");
username=intent.getStringExtra("username");
password=intent.getStringExtra("<PASSWORD>");
userid=intent.getStringExtra("userid");
System.out.println(token+courseid+username+password+userid);
new NetworkHandler().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.assignments, menu);
return true;
}
public void ConnHelper()
{
try {
HttpResponse resp = ConnHandler.doPost(MainActivity.ipaddr + "/webservice/rest/server.php?wstoken="+token,"wsfunction=mod_forum_get_forums_by_courses&"+"courseids[0]="+courseid);
HttpEntity enty = resp.getEntity();
strem= enty.getContent();
try
{
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
xpp = factory.newPullParser();
xpp.setInput(strem, null);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_TAG) {
//System.out.println("Entered while loop "+xpp.getName()+" "+xpp.getDepth()+" "+xpp.getAttributeCount()+" ");
if(xpp.getDepth()==4 && xpp.getName().equals("KEY") && xpp.getAttributeCount()>0){
//System.out.println("Entered depth 3");
if(xpp.getAttributeValue(0).equals("id")){
xpp.next();
xpp.next();
//idlist.add(xpp.getText());
//System.out.println("id is : "+xpp.getText());
id=xpp.getText();
idlist.add(id);
}else if(xpp.getAttributeValue(0).equals("name")){
xpp.next();
xpp.next();
//emaillist.add(xpp.getText());
//System.out.println("name is : "+xpp.getText());
name=xpp.getText();
namelist.add(name);
}
}
//System.out.println("Start tag "+xpp.getName()+" "+xpp.getAttributeName(0)+" : "+xpp.getAttributeValue(0));
}
eventType = xpp.next();
}
}catch(Exception e){
System.out.println("Error in xml parsing");
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onListItemClick(ListView list,View view,int position,long id){
super.onListItemClick(list, view, position, id);
//String testName = lists[position];
//Intent intent1 = new Intent(this,Contact.class);
//intent1.putExtra("department", category);
//intent1.putExtra("name", testName);
//startActivity(intent1);
Intent intent1 = null;
intent1 = new Intent(this,ForumsTopics.class);
System.out.println("forum id is "+idlist.get(position));
intent1.putExtra("urlid", idlist.get(position));
intent1.putExtra("url", MainActivity.ipaddr+"/mod/forum/discuss.php?id="+idlist.get(position));
intent1.putExtra("courseid", courseid);
intent1.putExtra("username", username);
intent1.putExtra("password", <PASSWORD>);
intent1.putExtra("userid", userid);
intent1.putExtra("token", token);
startActivity(intent1);
}
class NetworkHandler extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ConnHelper();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String[] list = new String[namelist.size()];
for(int i=0;i<namelist.size();i++)
{
list[i]=namelist.get(i);
}
bar.setVisibility(View.GONE);
listView.setAdapter(new ArrayAdapter<String>(cont,R.layout.activity_participant_list,list));
//setListAdapter(new ArrayAdapter<String>(cont,R.layout.activity_assignments,list));
}
}
}
<file_sep>/src/com/moodletest/MainActivity.java
package com.moodletest;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.examples.HtmlToPlainText;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.webkit.CookieManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("ShowToast")
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public static String proxyUser,proxyPass,proxySer;
public static int proxyPort;
public static boolean proxyCheck,authCheck;
String url;
String username = null, passwrd = null, fullname;
String token, userid;
Document dom, dom1;
DocumentBuilder builder;
DocumentBuilderFactory factory;
EditText uname, pass;
XPath xpath;
XPathExpression expr;
XPathFactory xPathfactory;
ConnHandler handler = new ConnHandler();
Context cont=this;
EditText webserver, extwebservice;
public static String ipaddr;
String webservice;
public static SharedPreferences sharepref;
ProgressDialog progress;
XmlPullParserFactory xmlfactory;// = XmlPullParserFactory.newInstance();
XmlPullParser xpp;// = factory.newPullParser();
InputStream strem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View inflatedView = getLayoutInflater().inflate(R.layout.settings_menu,
null);
webserver = (EditText) inflatedView.findViewById(R.id.servertext);
extwebservice = (EditText) inflatedView.findViewById(R.id.servicetext);
setContentView(R.layout.activity_main);
sharepref = getSharedPreferences(PREFS_NAME, 0);
setTitle("My Moodle Application");
cont = this;
proxyUser=sharepref.getString("proxy_username", null);
proxyPass=sharepref.getString("proxy_password", null);
proxySer=sharepref.getString("proxy", null);
if(sharepref.getString("port", null)!=null)
{
proxyPort=Integer.parseInt(sharepref.getString("port", null));
}
if(sharepref.getString("proxyCheck", "false").equals("true"))
{
proxyCheck=true;
}else{
proxyCheck=false;
}
if(sharepref.getString("authCheck", "false").equals("true"))
{
authCheck=true;
}else{
authCheck=false;
}
username = sharepref.getString("username", null);
passwrd = sharepref.getString("password", null);
ipaddr = sharepref.getString("server",
"http://moodle.iith.ac.in");
webservice = sharepref.getString("service", "moodle_mobile");
System.out.println(webservice);
webserver.setText(ipaddr);
extwebservice.setText(webservice);
uname = (EditText) findViewById(R.id.EditText01);
pass = (EditText) findViewById(R.id.editText2);
Button login = (Button) findViewById(R.id.button1);
if (username != null && passwrd != null) {
uname.setText(username);
pass.setText(passwrd);
/*
* try { url = ipaddr +
* "/login/token.php?username="+URLEncoder.encode(username,
* "utf-8")+"&password="+URLEncoder.encode(passwrd,
* "utf-8")+"&service=moodle_mobile_app"; token =
* (String)doGet(url).get("token"); /*HttpResponse resp =
* doPost(ipaddr + "/webservice/rest/server.php?wstoken="+token,
* "userid=3&wsfunction=moodle_enrol_get_users_courses"); HttpEntity
* enty = resp.getEntity(); InputStream strem = enty.getContent();
* factory = DocumentBuilderFactory.newInstance(); builder =
* factory.newDocumentBuilder(); dom = builder.parse(strem);
* xPathfactory = XPathFactory.newInstance(); xpath =
* xPathfactory.newXPath(); expr =
* xpath.compile("//KEY[@name=\"fullname\"]"); NodeList nl2 =
* (NodeList) expr.evaluate(dom, XPathConstants.NODESET);
* System.out.
* println("node list of expr "+nl2.item(0).getChildNodes
* ().item(0).getChildNodes().getLength()); if(dom != null){
* System.out.println("dom is not null"); }
*
* NodeList nl = dom.getElementsByTagName("KEY"); Node nod =
* nl.item(1); System.out.println("test dom ");
* System.out.println(nod.hasAttributes());
* System.out.println(dom.getFirstChild
* ().getChildNodes().item(1).getChildNodes
* ().item(1).getChildNodes()
* .item(1).getChildNodes().item(0).getChildNodes
* ().item(0).getNodeValue());
* System.out.println(getElementValue(nl.item(0))); HttpResponse
* resp1 = doPost(ipaddr +
* "/webservice/rest/server.php?wstoken="+token
* ,"wsfunction=moodle_webservice_get_siteinfo"); dom1 =
* handler.returnDom(resp1); userid=handler.getKeyValue("userid",
* dom1); Log.d("USERID",userid);
*
*
* } catch (Exception e) { // TODO Auto-generated catch block
* e.printStackTrace(); } sendmessage(token,userid);
*/
}
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new NetworkHandler().execute();
}
});
}
public void sendmessage(String str, String userid) {
Intent intent = new Intent(this, ParticipantCourseList.class);
intent.putExtra("token", str);
intent.putExtra("userid", userid);
intent.putExtra("fullname", fullname);
intent.putExtra("username", username);
intent.putExtra("password", <PASSWORD>);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
settings();
return true;
case R.id.proxy:
proxy();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void dispErrorMsg() {
Toast.makeText(cont, "Invalid username or password", Toast.LENGTH_LONG)
.show();
}
public static JSONObject doGet(String url) {
JSONObject json = null;
DefaultHttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpHost proxy = new HttpHost(proxySer, proxyPort);
//httpclient.getCredentialsProvider().setCredentials(new AuthScope(proxySer, proxyPort, AuthScope.ANY_REALM, "basic"),
// new UsernamePasswordCredentials("cs11b012", "xmEnEvolution"));
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet httpget = new HttpGet(url);
// Accept JSON
httpget.addHeader("accept", "application/json");
//httpget.addHeader("Proxy-Authorization", "Basic cHJha2FzaDppaXRo");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
int status = response.getStatusLine().getStatusCode();
if (status != 200) {
// dispErrorMsg();
return null;
}
System.out.println("status code is" + status);
System.out.println(response.toString());
System.out.println(response.getAllHeaders().toString());
Header[] head = response.getAllHeaders();
for (int i = 0; i < head.length; i++) {
System.out.println("header " + head[i].getName()
+ " : header value " + head[i].getValue() + " close ");
}
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
System.out.println(result);
// construct a JSON object with result
json = new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
// Get the response entity
// System.out.println(json.get("token"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the json
return json;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static HttpResponse doPost(String url, String c)
throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
request.setHeader("Proxy-Authorization", "Basic cHJha2FzaDppaXRo");
StringEntity s = new StringEntity(c);
System.out.println(s.getContent());
// s.setContentEncoding("UTF-8");
s.setContentType("application/x-www-form-urlencoded");
// request.setHeader("Content-Type",
// "application/x-www-form-urlencoded");
request.setEntity(s);
// request.addHeader("accept", "application/json");
return httpclient.execute(request);
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
public void onStop() {
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
Log.d("onstopn", "entered on stop");
/*
* SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
* SharedPreferences.Editor editor = settings.edit();
* editor.putString("username", uname.getText().toString());
* editor.putString("password", <PASSWORD>());
*
*
* // Commit the edits! editor.commit();
*/
}
public void ConnHelper() {
try {
HttpResponse resp = ConnHandler.doPost(MainActivity.ipaddr
+ "/webservice/rest/server.php?wstoken=" + token,
"wsfunction=core_webservice_get_site_info");
HttpEntity enty = resp.getEntity();
strem = enty.getContent();
try {
xmlfactory = XmlPullParserFactory.newInstance();
xmlfactory.setNamespaceAware(true);
xpp = xmlfactory.newPullParser();
xpp.setInput(strem, null);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
// System.out.println("Entered while loop "+xpp.getName()+" "+xpp.getDepth()+" "+xpp.getAttributeCount()+" ");
if (xpp.getDepth() == 3 && xpp.getName().equals("KEY")
&& xpp.getAttributeCount() > 0) {
// System.out.println("Entered depth 3");
if (xpp.getAttributeValue(0).equals("username")) {
xpp.next();
xpp.next();
// System.out.println("fullname : "+
// xpp.getText());
} else if (xpp.getAttributeValue(0).equals(
"fullname")) {
xpp.next();
xpp.next();
fullname = xpp.getText();
System.out.println(xpp.getText());
} else if (xpp.getAttributeValue(0)
.equals("userid")) {
xpp.next();
xpp.next();
userid = xpp.getText();
break;
}
}
// System.out.println("Start tag "+xpp.getName()+" "+xpp.getAttributeName(0)+" : "+xpp.getAttributeValue(0));
}
eventType = xpp.next();
}
} catch (Exception e) {
System.out.println("Error in xml parsing");
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class NetworkHandler extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// LayoutParams params = progress.getWindow().getAttributes();
// params.width = LayoutParams.FILL_PARENT;
// progress.getWindow().setAttributes((android.view.WindowManager.LayoutParams)
// params);
progress = ProgressDialog.show(cont, "Loading",
"Please wait....Logging in", true);
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Editable user = uname.getText();
Editable password = pass.getText();
Editable server = webserver.getText();
Editable service = extwebservice.getText();
System.out.println(user.toString() + " " + password.toString());
try {
SharedPreferences.Editor editor = sharepref.edit();
editor.putString("username", uname.getText().toString());
editor.putString("password", <PASSWORD>.getText().toString());
editor.commit();
username = uname.getText().toString();
passwrd = <PASSWORD>.getText().<PASSWORD>();
// ipaddr=server.toString();
// webservice=service.toString();
System.out.println("ipaddress in doinbackground " + ipaddr);
System.out
.println("webservice in doinbackground " + webservice);
url = ipaddr + "/login/token.php?username="
+ URLEncoder.encode(user.toString(), "utf-8")
+ "&password="
+ URLEncoder.encode(password.toString(), "utf-8")
+ "&service=" + webservice;
JSONObject obj = ConnHandler.doGet(url);
if (!obj.has("token")) {
System.out.println("in token verification");
runOnUiThread(new Runnable() {
@Override
public void run() {
dispErrorMsg();
// TODO Auto-generated method stub
}
});
return null;
} else {
token = (String) obj.get("token");
System.out.println(obj.toString());
// HttpResponse resp1 = doPost(ipaddr +
// "/webservice/rest/server.php?wstoken="+token,"wsfunction=core_webservice_get_site_info");
// dom1 = handler.returnDom(resp1);
// userid=handler.getKeyValue("userid", dom1);
ConnHelper();
Log.d("USERID", userid);
sendmessage(token, userid);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
}
}
public void settings() {
final Dialog settings = new Dialog(this);
settings.setContentView(R.layout.settings_menu);
settings.setTitle("Settings");
// set the custom dialog components - text, image and button
TextView server = (TextView) settings.findViewById(R.id.server);
server.setText("Settings");
final EditText url = (EditText) settings.findViewById(R.id.servertext);
final EditText service = (EditText) settings
.findViewById(R.id.servicetext);
url.setText(sharepref.getString("server",
"http://moodle.iith.ac.in/moodle"));
service.setText(sharepref.getString("service", "moodle_mobile"));
// ImageView image = (ImageView) settings.findViewById(R.id.image);
// image.setImageResource(R.drawable.ic_launcher);
Button cancelButton = (Button) settings.findViewById(R.id.cancel);
Button saveButton = (Button) settings.findViewById(R.id.save);
// if button is clicked, close the custom dialog
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
settings.dismiss();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = sharepref.edit();
editor.putString("server", url.getText().toString());
editor.putString("service", service.getText().toString());
editor.commit();
ipaddr = url.getText().toString();
webservice = service.getText().toString();
System.out.println("ipaddress in settings " + ipaddr);
System.out.println("webservice in settings " + webservice);
settings.dismiss();
}
});
settings.show();
}
public void proxy() {
final Dialog settings = new Dialog(this);
settings.setContentView(R.layout.proxy_menu);
settings.setTitle("Proxy Settings");
final CheckBox proxy_check = (CheckBox)settings.findViewById(R.id.proxy_check);
final CheckBox auth_check = (CheckBox)settings.findViewById(R.id.auth_check);
final EditText proxy =(EditText)settings.findViewById(R.id.proxy);
final EditText port =(EditText)settings.findViewById(R.id.port);
final EditText proxyUsername =(EditText)settings.findViewById(R.id.username);
final EditText proxyPassword =(EditText)settings.findViewById(R.id.password);
Button cancelButton = (Button) settings.findViewById(R.id.cancel);
Button saveButton = (Button) settings.findViewById(R.id.save);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
settings.dismiss();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = sharepref.edit();
if(proxy_check.isChecked()){
editor.putString("proxyCheck","true");
proxyCheck=true;
editor.putString("proxy", proxy.getText().toString());
proxySer=proxy.getText().toString();
editor.putString("port", port.getText().toString());
proxyPort=Integer.parseInt(port.getText().toString());
}else{
proxy.setVisibility(View.INVISIBLE);
}
if(auth_check.isChecked())
{
editor.putString("authCheck","true");
authCheck=true;
editor.putString("proxy_username", proxyUsername.getText().toString());
proxyUser=proxyUsername.getText().toString();
editor.putString("proxy_password", proxyPassword.getText().toString());
proxyPass=proxyPassword.getText().toString();
}
editor.commit();
settings.dismiss();
}
});
/*
* // set the custom dialog components - text, image and button TextView
* server = (TextView) settings.findViewById(R.id.server);
* server.setText("Settings"); final EditText url =
* (EditText)settings.findViewById(R.id.servertext); final EditText
* service = (EditText)settings.findViewById(R.id.servicetext);
* url.setText
* (sharepref.getString("server","http://moodle.iith.ac.in/moodle" ));
* service.setText(sharepref.getString("service", "moodle_mobile"));
* //ImageView image = (ImageView) settings.findViewById(R.id.image);
* //image.setImageResource(R.drawable.ic_launcher);
*
* Button dialogButton = (Button) settings.findViewById(R.id.cancel);
* Button saveButton = (Button)settings.findViewById(R.id.save); // if
* button is clicked, close the custom dialog
* dialogButton.setOnClickListener(new View.OnClickListener() {
*
* @Override public void onClick(View v) { settings.dismiss(); } });
* saveButton.setOnClickListener(new View.OnClickListener() {
*
* @Override public void onClick(View v) { // TODO Auto-generated method
* stub
*
*
* SharedPreferences.Editor editor = sharepref.edit();
* editor.putString("server", url.getText().toString());
* editor.putString("service", service.getText().toString());
* editor.commit(); System.out.println(url.getText().toString());
* System.out.println(service.getText().toString()); settings.dismiss();
*
* } });
*/
if(proxyCheck)
{
proxy_check.setChecked(true);
proxy.setText(proxySer);
port.setText(Integer.valueOf(proxyPort).toString());
}
if(authCheck)
{
auth_check.setChecked(true);
proxyUsername.setText(proxyUser);
proxyPassword.setText(Integer.valueOf(proxyPass).toString());
}
settings.show();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
System.out.println("Entered on pause");
SharedPreferences.Editor editor = sharepref.edit();
editor.putString("lock", "false");
editor.commit();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
SharedPreferences.Editor editor = sharepref.edit();
editor.putString("lock", "true");
editor.commit();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d("Destroy_TAG","Called on destroy");
}
}
<file_sep>/src/com/moodletest/Test.java
package com.moodletest;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class Test extends Activity {
ConnHandler handler;
String userid,token;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
handler = new ConnHandler();
Intent intent = getIntent();
token = intent.getStringExtra("token");
userid = intent.getStringExtra("userid");
try {
HttpResponse resp = handler.doPost(MainActivity.ipaddr + "/webservice/rest/server.php?wstoken="+token,"courseid="+"&wsfunction=moodle_user_get_users_by_courseid");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}
<file_sep>/src/com/moodletest/JsonTest.java
package com.moodletest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class JsonTest extends ListActivity {
String username, password, token, courseid, id, url, name, userid, type;
TextView assignment;
ConnHandler handler;
XmlPullParserFactory factory;// = XmlPullParserFactory.newInstance();
XmlPullParser xpp;// = factory.newPullParser();
InputStream strem;
ArrayList<String> namelist, urllist, idlist;
Context cont;
ListView listView;
ProgressBar bar;
DBAdapter database;
JSONObject jsonObj;
String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
// setContentView(R.layout.activity_assignments);
handler = new ConnHandler();
namelist = new ArrayList<String>();
urllist = new ArrayList<String>();
idlist = new ArrayList<String>();
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setVisibility(View.VISIBLE);
listView = (ListView) findViewById(android.R.id.list);
cont = this;
Intent intent = getIntent();
token = intent.getStringExtra("token");
courseid = intent.getStringExtra("courseid");
username = intent.getStringExtra("username");
password = intent.getStringExtra("<PASSWORD>");
userid = intent.getStringExtra("userid");
type = intent.getStringExtra("type");
// System.out.println(token + courseid + username + password + userid);
database = new DBAdapter(this);
new NetworkHandler().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.assignments, menu);
return true;
}
public void ConnHelper() {
try {
HttpResponse resp = ConnHandler.doPost_json(MainActivity.ipaddr
+ "/webservice/rest/server.php?moodlewsrestformat=json","wstoken=" + token
+"&wsfunction=core_course_get_contents&" + "courseid="
+ courseid);
HttpEntity enty = resp.getEntity();
//byte[] bytes = EntityUtils.toByteArray(enty);
//System.out.println(new String(bytes,"UTF-8"));
strem = enty.getContent();
result = convertStreamToString(strem);
System.out.println(result);
// System.out.println("assignments file "+strem.toString());
jsonObj = new JSONObject(result);
System.out.println(jsonObj.toString());
/*try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
xpp = factory.newPullParser();
// xpp.setInput(strem, null);
xpp.setInput(new StringReader(new String(bytes, "UTF-8")));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getDepth() == 7 && xpp.getName().equals("KEY")
&& xpp.getAttributeCount() > 0) {
if (xpp.getAttributeValue(0).equals("id")) {
xpp.next();
xpp.next();
id = xpp.getText();
} else if (xpp.getAttributeValue(0).equals("url")) {
xpp.next();
xpp.next();
url = xpp.getText();
} else if (xpp.getAttributeValue(0).equals("name")) {
xpp.next();
xpp.next();
name = xpp.getText();
} else if (xpp.getAttributeValue(0).equals(
"modname")) {
xpp.next();
xpp.next();
if (xpp.getText().equals(type)) {
// System.out.println(id + " " + name + " "
// + url);
namelist.add(name);
idlist.add(id);
urllist.add(url);
if (type.equals("assign")) {
database.open();
if (database.assignTableGetContent(id,
courseid, userid).getCount() == 0) {
database.assignTableInsertDetails(
courseid, id, url, name,
userid);
}
database.close();
} else if (type.equals("url")) {
while (xpp.getDepth() >= 7) {
if (xpp.getDepth()==10 && eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equals("KEY")
&& xpp.getAttributeCount() > 0) {
if (xpp.getAttributeValue(0)
.equals("fileurl")) {
xpp.next();
xpp.next();
// name = xpp.getText();
System.out.println(xpp
.getText());
break;
}
}
}
xpp.next();
}
}
}
}
}
}
eventType = xpp.next();
}
} catch (Exception e) {
System.out.println("Error in xml parsing");
e.printStackTrace();
}*/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
Intent intent1 = null;
if (type.equals("assign")) {
intent1 = new Intent(this, AssignmentContent.class);
} else if (type.equals("forum")) {
intent1 = new Intent(this, ForumsTopics.class);
} else {
intent1 = new Intent(this, AssignmentWebview.class);
}
intent1.putExtra("urlid", idlist.get(position));
intent1.putExtra("url", urllist.get(position));
intent1.putExtra("courseid", courseid);
intent1.putExtra("username", username);
intent1.putExtra("password", <PASSWORD>);
intent1.putExtra("userid", userid);
intent1.putExtra("token", token);
startActivity(intent1);
}
class NetworkHandler extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ConnHelper();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String[] list = new String[namelist.size()];
for (int i = 0; i < namelist.size(); i++) {
list[i] = namelist.get(i);
}
bar.setVisibility(View.GONE);
listView.setAdapter(new ArrayAdapter<String>(cont,
R.layout.activity_participant_list, list));
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
SharedPreferences.Editor editor = MainActivity.sharepref.edit();
editor.putString("lock", "false");
editor.commit();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
SharedPreferences.Editor editor = MainActivity.sharepref.edit();
editor.putString("lock", "true");
editor.commit();
}
public HttpResponse doPost(String url, String c)
throws ClientProtocolException, IOException {
HttpClient httpclient = new MyHttpClient(cont);
HttpPost request = new HttpPost(url);
StringEntity s = new StringEntity(c);
// System.out.println(s.getContent());
// System.out.println(s.toString());
// s.setContentEncoding("UTF-8");
s.setContentType("application/x-www-form-urlencoded");
// request.setHeader("Content-Type",
// "application/x-www-form-urlencoded");
request.setEntity(s);
// request.addHeader("accept", "application/json");
return httpclient.execute(request);
}
public static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
char[] bytes1=new char[1024];
int size=1024;
try {
while (true) {
size= reader.read(bytes1,0,bytes1.length);
if(size!=-1)
sb.append(bytes1);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
<file_sep>/src/com/moodletest/MainScreen.java
package com.moodletest;
import org.apache.http.HttpResponse;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainScreen extends Activity {
String token,userid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Intent intent = getIntent();
token = intent.getStringExtra("token");
userid = intent.getStringExtra("userid");
Toast.makeText(this, userid, Toast.LENGTH_LONG).show();
//HttpResponse resp1 = doPost(MainActivity.ipaddr + "/webservice/rest/server.php?wstoken="+token,"wsfunction=moodle_webservice_get_siteinfo");
Button UserInfo = (Button)findViewById(R.id.user_info);
UserInfo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendMessage(token,userid,UserInfo.class);
}
});
Button Participants = (Button)findViewById(R.id.participants);
Participants.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendMessage(token,userid,ParticipantCourseList.class);
}
});
Button Courses = (Button)findViewById(R.id.courses);
Courses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendMessage(token,userid,Course.class);
}
});
}
public void sendMessage(String token,String userid, Class test){
Intent intent = new Intent(this,test);
intent.putExtra("token", token);
intent.putExtra("userid", userid);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen, menu);
return true;
}
}
<file_sep>/src/com/moodletest/ForumDiscussion.java
package com.moodletest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Html;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ForumDiscussion extends ListActivity {
public String username, password, url, urlid, courseid, userid;
public TextView assignment;
//DBAdapter database;
boolean table_content;
Elements heading, content;
Element head1;
org.jsoup.nodes.Document doc;
//WebView webView;
ProgressBar bar;
String[] author,subject,post,date;
ListView listView;
Context cont=this;
Bitmap picuri[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
bar=(ProgressBar)findViewById(R.id.progressBar1);
listView = (ListView) findViewById(android.R.id.list);
bar.setVisibility(View.VISIBLE);
table_content = false;
//database = new DBAdapter(this);
//database.open();
Intent intent = getIntent();
username = intent.getStringExtra("username");
password = intent.getStringExtra("password");
url = intent.getStringExtra("url");
urlid = intent.getStringExtra("urlid");
courseid = intent.getStringExtra("courseid");
userid = intent.getStringExtra("userid");
// username="bhargav";
// password="<PASSWORD>@!)*!((!<PASSWORD>";
//webView = (WebView) findViewById(R.id.assignment);
//webView.getSettings().setJavaScriptEnabled(true);
new NetworkHandler().execute();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public void ConnHelper() {
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost request = new HttpPost(MainActivity.ipaddr
+ "/login/index.php");
request.setHeader("Proxy-Authorization", "Basic cHJha2FzaDppaXRo");
StringEntity s = new StringEntity("username="
+ URLEncoder.encode(username, "utf-8") + "&password="
+ URLEncoder.encode(password, "utf-8"));
System.out.println(s.getContent());
// s.setContentEncoding("UTF-8");
s.setContentType("application/x-www-form-urlencoded");
request.setEntity(s);
// request.addHeader("accept", "application/json");
HttpResponse resp3 = httpclient2.execute(request);
// HttpResponse resp3 = doPost(ipaddr +
// "/login/index.php","username="+URLEncoder.encode(user.toString(),
// "utf-8")+"&password="+URLEncoder.encode(password.toString(),
// "utf-8"));
HttpEntity respentity = resp3.getEntity();
System.out.println(convertStreamToString(respentity.getContent()));
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient2.execute(httpget);
int status = response.getStatusLine().getStatusCode();
// System.out.println("status code is" +status);
// System.out.println(response.toString());
// System.out.println(response.getAllHeaders().toString());
Header[] head = response.getAllHeaders();
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
doc = Jsoup.parse(result);
// Elements content=doc.getElementsByClass("topics");
// System.out.println(Html.fromHtml(head1.toString()+content.toString()));
// org.jsoup.nodes.Element contentdiv = content.get(0);
// System.out.println(new
// org.jsoup.examples.HtmlToPlainText().getPlainText(contentdiv));
// System.out.println(result);
content = doc.getElementsByClass("forumpost");
author = new String[content.size()];
subject = new String[content.size()];
date = new String[content.size()];
post = new String[content.size()];
picuri =new Bitmap[content.size()];
for(int i=0;i<content.size();i++)
{ System.out.println("iteration is :"+i);
//int i=0;
String temp = content.get(i).select(".author").text();
subject[i] = content.get(i).select(".subject").text();
post[i]=content.get(i).select(".posting").text();
String [] auth = temp.split("- ");
author[i]= auth[0];
date[i]=auth[1];
/*try {
HttpEntity entity1= ConnHandler.doPost(content.get(i).select(".userpicture").get(0).absUrl("src")).getEntity();
InputStream in = entity1.getContent();
picuri[i]=BitmapFactory.decodeStream(in);
} catch (Exception e) {
//Log.e("Error", e.getMessage());
e.printStackTrace();
System.out.println("error in url loading");
}*/
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class NetworkHandler extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ConnHelper();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//content = doc.getElementsByClass("region-content");
//content = doc.getElementsByAttributeValue("role","main");
//String uri = test.get(0).absUrl("src");
//String uri = Jsoup.parse(test.toString()).absUrl("src");
// assignment.setText(Html.fromHtml(head1.toString()
// + content.toString()));
bar.setVisibility(View.GONE);
listView.setAdapter(new ForumListAdapter(cont, subject, picuri, author, date, post));
/*webView.loadData(uri,
"text/html", "utf-8");*/
}
}
}
<file_sep>/src/com/moodletest/UserInfo.java
package com.moodletest;
import java.io.IOException;
import java.net.URLEncoder;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class UserInfo extends Activity {
Document dom;
XPath xpath;
XPathExpression expr;
XPathFactory xPathfactory;
ConnHandler handler = new ConnHandler();
TextView usrinfo;
String token;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_info);
Intent intent = getIntent();
token = intent.getStringExtra("token");
usrinfo = (TextView)findViewById(R.id.textView1);
new NetworkHandler().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_info, menu);
return true;
}
class NetworkHandler extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
HttpResponse resp = ConnHandler.doPost(MainActivity.ipaddr + "/webservice/rest/server.php?wstoken="+token,"wsfunction=moodle_webservice_get_siteinfo");
dom = handler.returnDom(resp);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
usrinfo.setText("Full Name : "+handler.getKeyValue("fullname", dom)+"\nName : "+handler.getKeyValue("lastname", dom)+"\nUser ID : "+handler.getKeyValue("userid", dom));
}
}
}
<file_sep>/src/com/moodletest/CourseContents.java
package com.moodletest;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class CourseContents extends Activity {
public String courseid, userid,token,shortname,fullname,startdate;
DBAdapter database;
XmlPullParserFactory xmlfactory;// = XmlPullParserFactory.newInstance();
XmlPullParser xpp;// = factory.newPullParser();
InputStream strem;
ProgressBar bar;
Date strtdate;
TextView courseidText,startdateText,shortnameText,fullnameText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_contents);
Intent intent = getIntent();
token = intent.getStringExtra("token");
courseid = intent.getStringExtra("courseid");
userid = intent.getStringExtra("userid");
bar = (ProgressBar)findViewById(R.id.progressBar1);
bar.setVisibility(View.VISIBLE);
courseidText = (TextView)findViewById(R.id.courseid);
startdateText = (TextView)findViewById(R.id.startdate);
fullnameText = (TextView)findViewById(R.id.fullname);
shortnameText = (TextView)findViewById(R.id.shortname);
courseidText.setVisibility(View.GONE);
startdateText.setVisibility(View.GONE);
fullnameText.setVisibility(View.GONE);
shortnameText.setVisibility(View.GONE);
new NetworkHandler().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.course_contents, menu);
return true;
}
public void ConnHelper() {
try {
HttpResponse resp = ConnHandler.doPost(MainActivity.ipaddr
+ "/webservice/rest/server.php?wstoken=" + token,
"wsfunction=core_course_get_courses&options[ids][0]="+courseid);
HttpEntity enty = resp.getEntity();
strem = enty.getContent();
try {
xmlfactory = XmlPullParserFactory.newInstance();
xmlfactory.setNamespaceAware(true);
xpp = xmlfactory.newPullParser();
xpp.setInput(strem, null);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
// System.out.println("Entered while loop "+xpp.getName()+" "+xpp.getDepth()+" "+xpp.getAttributeCount()+" ");
if (xpp.getDepth() == 4 && xpp.getName().equals("KEY")
&& xpp.getAttributeCount() > 0) {
// System.out.println("Entered depth 3");
if (xpp.getAttributeValue(0).equals("shortname")) {
xpp.next();
xpp.next();
System.out.println("shortname : "+
xpp.getText());
shortname=xpp.getText();
} else if (xpp.getAttributeValue(0).equals(
"fullname")) {
xpp.next();
xpp.next();
System.out.println("fullname is : "+xpp.getText());
fullname=xpp.getText();
}
else if (xpp.getAttributeValue(0).equals(
"startdate")) {
xpp.next();
xpp.next();
startdate=xpp.getText();
strtdate = new Date(Long.parseLong(startdate)*1000);
System.out.println("startdate is : "+strtdate.toString());
break;
}
}
// System.out.println("Start tag "+xpp.getName()+" "+xpp.getAttributeName(0)+" : "+xpp.getAttributeValue(0));
}
eventType = xpp.next();
}
} catch (Exception e) {
System.out.println("Error in xml parsing");
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class NetworkHandler extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ConnHelper();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
bar.setVisibility(View.GONE);
courseidText.setVisibility(View.VISIBLE);
startdateText.setVisibility(View.VISIBLE);
fullnameText.setVisibility(View.VISIBLE);
shortnameText.setVisibility(View.VISIBLE);
fullnameText.setText("Course fullname : "+fullname);
shortnameText.setText("Course shortname :"+shortname);
courseidText.setText("Course id : "+courseid);
startdateText.setText("Start Date is : "+strtdate.toGMTString());
}
}
}
<file_sep>/src/com/moodletest/ConnHandler.java
package com.moodletest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.security.Principal;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import com.google.api.client.http.BasicAuthentication;
public class ConnHandler {
public static Client test = new Client();
public static JSONObject doGet(String url) {
JSONObject json = null;
DefaultHttpClient httpclient = new DefaultHttpClient();
if(MainActivity.proxyCheck==true)
{
HttpHost proxy = new HttpHost(MainActivity.proxySer, MainActivity.proxyPort);
if(MainActivity.authCheck==true){
httpclient.getCredentialsProvider().setCredentials(new AuthScope(MainActivity.proxySer, MainActivity.proxyPort, AuthScope.ANY_REALM, "basic"),
new UsernamePasswordCredentials(MainActivity.proxyUser, MainActivity.proxyPass));
}
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Accept JSON
httpget.addHeader("accept", "application/json");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
System.out.println(response.toString());
System.out.println(response.getAllHeaders().toString());
Header[] head = response.getAllHeaders();
for(int i=0;i<head.length;i++){
System.out.println("header "+head[i].getName()+" : header value "+head[i].getValue()+" close ");
}
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
System.out.println(result);
// construct a JSON object with result
json=new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
// Get the response entity
System.out.println(json.get("token"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the json
return json;
}
public static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
byte[] bytes=new byte[1024];
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static HttpResponse doPost(String url, String c) throws ClientProtocolException, IOException
{
DefaultHttpClient httpclient = test.httpClient;
if(MainActivity.proxyCheck==true)
{
HttpHost proxy = new HttpHost(MainActivity.proxySer, MainActivity.proxyPort);
if(MainActivity.authCheck==true){
httpclient.getCredentialsProvider().setCredentials(new AuthScope(MainActivity.proxySer, MainActivity.proxyPort, AuthScope.ANY_REALM, "basic"),
new UsernamePasswordCredentials(MainActivity.proxyUser, MainActivity.proxyPass));
}
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
//HttpHost target = new HttpHost("10.0.0.5",80);
//HttpHost host = new HttpHost("10.0.0.5",80);
//AuthCache authCache = new BasicAuthCache();
//HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
StringEntity s = new StringEntity(c);
System.out.println(s.getContent());
System.out.println(s.toString());
//s.setContentEncoding("UTF-8");
s.setContentType("application/x-www-form-urlencoded");
//request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(s);
//httpclient.getCredentialsProvider().setCredentials(new AuthScope("10.0.0.5", 80, AuthScope.ANY_REALM, "basic"),
// new UsernamePasswordCredentials("cs11b012", "<PASSWORD>"));
/*try {
request.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials("cs11b012", "xmEnEvolution"),new BasicHttpRequest(request.getRequestLine())));
} catch (AuthenticationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//request.addHeader("accept", "application/json");
Header header[]=request.getAllHeaders();
for(int i=0;i<header.length;i++)
System.out.println("request header is "+header[i].getName()+" : "+header[i].getValue());
return httpclient.execute(request);
}
public static HttpResponse doPost(String url) throws ClientProtocolException, IOException
{
DefaultHttpClient httpclient = test.httpClient;
if(MainActivity.proxyCheck==true)
{
HttpHost proxy = new HttpHost(MainActivity.proxySer, MainActivity.proxyPort);
if(MainActivity.authCheck==true){
httpclient.getCredentialsProvider().setCredentials(new AuthScope(MainActivity.proxySer, MainActivity.proxyPort, AuthScope.ANY_REALM, "basic"),
new UsernamePasswordCredentials(MainActivity.proxyUser, MainActivity.proxyPass));
}
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
//HttpClient httpclient = new DefaultHttpClient();
HttpContext context = new BasicHttpContext();
HttpPost request = new HttpPost(url);
//s.setContentEncoding("UTF-8");
//request.addHeader("accept", "application/json");
Header header[]=request.getAllHeaders();
for(int i=0;i<header.length;i++)
System.out.println("request header is "+header[i].getName()+" : "+header[i].getValue());
return httpclient.execute(request);
}
public static HttpResponse doPost_json(String url, String c) throws ClientProtocolException, IOException
{
HttpClient httpclient = test.httpClient;
//HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
StringEntity s = new StringEntity(c);
System.out.println(s.getContent());
System.out.println(s.toString());
//s.setContentEncoding("UTF-8");
s.setContentType("application/x-www-form-urlencoded");
//request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(s);
request.addHeader("accept", "application/json");
//request.addHeader("accept", "application/json");
return httpclient.execute(request);
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
public Document returnDom(HttpResponse resp){
Document dom = null;
DocumentBuilder builder=null;
DocumentBuilderFactory factory = null;
HttpEntity enty = resp.getEntity();
InputStream strem= null;
try {
strem = enty.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory = DocumentBuilderFactory.newInstance();
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dom = builder.parse(strem);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dom;
}
public String getKeyValue(String name,Document dom){
XPath xpath = null;
XPathExpression expr = null;
XPathFactory xPathfactory = null;
xPathfactory = XPathFactory.newInstance();
xpath = xPathfactory.newXPath();
try{
expr = xpath.compile("//KEY[@name=\""+name+"\"]");
NodeList nl = (NodeList) expr.evaluate(dom, XPathConstants.NODESET);
NodeList valchildset = nl.item(0).getChildNodes();
for(int i=0;i<valchildset.getLength();i++)
{
//System.out.println(i+valchildset.item(i).getNodeName());
if(valchildset.item(i).getNodeName().equals("VALUE"))
{
//System.out.println("inside if condition");
Node value = valchildset.item(i).getFirstChild();
return value.getNodeValue();
}
}
}catch(Exception e){
e.printStackTrace();
}
return " ";
}
public String getKeyValue(String name,Document dom, int itemnum){
XPath xpath = null;
XPathExpression expr = null;
XPathFactory xPathfactory = null;
xPathfactory = XPathFactory.newInstance();
xpath = xPathfactory.newXPath();
try{
expr = xpath.compile("//KEY[@name=\""+name+"\"]");
NodeList nl = (NodeList) expr.evaluate(dom, XPathConstants.NODESET);
NodeList valchildset = nl.item(itemnum).getChildNodes();
for(int i=0;i<valchildset.getLength();i++)
{
//System.out.println(i+valchildset.item(i).getNodeName());
if(valchildset.item(i).getNodeName().equals("VALUE"))
{
//System.out.println("inside if condition");
Node value = valchildset.item(i).getFirstChild();
return value.getNodeValue();
}
}
}catch(Exception e){
e.printStackTrace();
}
return "";
}
public void xmlparser(InputStream in){
try
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
//String myString = IOUtils.toString(in, "UTF-8");
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb=new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while(read != null) {
//System.out.println(read);
sb.append(read);
read =br.readLine();
}
//new StringReader(sb.toString());
//xpp.setInput(in, null);
//System.out.println(sb.toString());
String str = sb.toString();
str.replaceAll(">\\s*<", "><");
//System.out.println(str);
xpp.setInput( new StringReader(sb.toString()) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
if(xpp.getAttributeCount()>0){
System.out.println("Start tag "+xpp.getName()+" "+xpp.getAttributeName(0)+" : "+xpp.getAttributeValue(0));
}else{
System.out.println("Start tag "+xpp.getName());
}
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}catch(Exception e){
System.out.println("Error in xml parsing");
e.printStackTrace();
}
}
}
<file_sep>/src/com/moodletest/ParticipantsCourses.java
package com.moodletest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ParticipantsCourses extends Activity implements View.OnClickListener{
Document dom;
String token,userid,courseid,id,name;
Intent newIntent;
Button myButton=null;
ConnHandler handler;
LinearLayout ll;
LayoutParams lp;
InputStream strem;
Context cont;
StringBuilder sb;
DBAdapter database;
XmlPullParserFactory factory;// = XmlPullParserFactory.newInstance();
XmlPullParser xpp;// = factory.newPullParser();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_participants_courses);
Intent intent = getIntent();
ll = (LinearLayout)findViewById(R.id.Layout_courses_list);
lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
token = intent.getStringExtra("token");
userid = intent.getStringExtra("userid");
handler = new ConnHandler();
newIntent = new Intent(this,ParticipantList.class);
newIntent.putExtra("token",token);
newIntent.putExtra("userid",userid);
cont= this;
database = new DBAdapter(this);
database.open();
//database.assignTableCreate(userid);
if(!database.queryTable("usr_course_table_"+userid))
database.courseTableCreate(userid);
database.close();
new NetworkHandler().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.participants_courses, menu);
return true;
}
@Override
public void onClick(View v) {
newIntent.putExtra("courseid",v.getTag().toString());
startActivity(newIntent);
// TODO Auto-generated method stub
}
public void ConnHelper(){
try
{
//String myString = IOUtils.toString(in, "UTF-8");
InputStreamReader is = new InputStreamReader(strem);
sb=new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while(read != null) {
//System.out.println(read);
sb.append(read);
read =br.readLine();
}
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
xpp = factory.newPullParser();
xpp.setInput( new StringReader(sb.toString()) );
//new StringReader(sb.toString());
//xpp.setInput(in, null);
//System.out.println(sb.toString());
//System.out.println(str);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
if(xpp.getName().equals("SINGLE"))
{
System.out.println("Entered SINGLE and depth is "+xpp.getDepth() );
xpp.next();
//xpp.getName().equals("SINGLE")
while(true)
{
if(xpp.getEventType()!=XmlPullParser.START_TAG)
{
if(xpp.getEventType()==XmlPullParser.END_TAG)
{
if(xpp.getName().equals("SINGLE") && xpp.getDepth()==3)
{
myButton=new Button(this);
myButton.setTag(id);
myButton.setText(name);
myButton.setOnClickListener(this);
//stuff that updates ui
ll.addView(myButton,lp);
/*myButton=new Button(cont);
synchronized(myButton){
runOnUiThread(new Runnable() {
public void run() {
myButton.setTag(id);
myButton.setText("Send message to "+name);
myButton.setOnClickListener((OnClickListener)cont);
//stuff that updates ui
ll.addView(myButton,lp);
notify();
}
});
myButton.wait();}*/
break;
}
}
xpp.next();
continue;
}
else if(xpp.getName().equals("KEY") && xpp.getEventType()==XmlPullParser.START_TAG)
{
if(xpp.getAttributeCount()>0 && xpp.getAttributeName(0).equals("name"))
{
if(xpp.getAttributeValue(0).equals("id") && xpp.getDepth()==4)
{
xpp.next();
xpp.next();
id=xpp.getText();
System.out.println("fullname : "+ xpp.getText());
}else if(xpp.getAttributeValue(0).equals("fullname") && xpp.getDepth()==4)
{
xpp.next();
xpp.next();
name=xpp.getText();
}
}
}
xpp.next();
}
}
//System.out.println("Start tag "+xpp.getName()+" "+xpp.getAttributeName(0)+" : "+xpp.getAttributeValue(0));
} else if(eventType == XmlPullParser.END_TAG) {
//System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
//System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}catch(Exception e){
System.out.println("Error in xml parsing");
e.printStackTrace();
}
}
class NetworkHandler extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
HttpResponse resp = handler.doPost(MainActivity.ipaddr + "/webservice/rest/server.php?wstoken="+token,"userid="+userid+"&wsfunction=moodle_enrol_get_users_courses");
HttpEntity enty = resp.getEntity();
strem= enty.getContent();
}catch(Exception e){
e.printStackTrace();
}
//ConnHelper();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ConnHelper();
}
}
}
<file_sep>/src/com/moodletest/Participant.java
package com.moodletest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Participant extends Activity implements View.OnClickListener {
String courseid,userid,token,str="";
ConnHandler handler = new ConnHandler();
Intent intent1;
Document dom;
String name,id,email;
InputStream strem;
Button myButton;
LinearLayout ll;// = (LinearLayout)findViewById(R.id.participant);
LayoutParams lp;// = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
StringBuilder sb;
XmlPullParserFactory factory;// = XmlPullParserFactory.newInstance();
XmlPullParser xpp;// = factory.newPullParser();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_participant);
Intent intent = getIntent();
intent1=new Intent(this,Send.class);
courseid = intent.getStringExtra("courseid");
token = intent.getStringExtra("token");
userid = intent.getStringExtra("userid");
ll = (LinearLayout)findViewById(R.id.participant);
lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
new NetworkHandler().execute();
//TextView view = (TextView)findViewById(R.id.participants);
//view.setText(str);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.participant, menu);
return true;
}
public void ConnHelper()
{
try
{
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
xpp = factory.newPullParser();
//String myString = IOUtils.toString(in, "UTF-8");
//new StringReader(sb.toString());
//xpp.setInput(in, null);
//System.out.println(sb.toString());
//String str1 = sb.toString();
//str1.replaceAll(">\\s*<", "><");
//System.out.println(str);
xpp.setInput( new StringReader(sb.toString()) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
if(xpp.getName().equals("SINGLE"))
{
System.out.println("Entered SINGLE and depth is "+xpp.getDepth() );
xpp.next();
//xpp.getName().equals("SINGLE")
while(true)
{
if(xpp.getEventType()!=XmlPullParser.START_TAG)
{
if(xpp.getEventType()==XmlPullParser.END_TAG)
{
if(xpp.getName().equals("SINGLE") && xpp.getDepth()==3)
{
myButton=new Button(this);
myButton.setTag(id);
myButton.setText("Send message to "+name);
myButton.setOnClickListener(this);
ll.addView(myButton,lp);
break;
}
}
xpp.next();
continue;
}
else if(xpp.getName().equals("KEY") && xpp.getEventType()==XmlPullParser.START_TAG)
{
if(xpp.getAttributeCount()>0 && xpp.getAttributeName(0).equals("name"))
{
if(xpp.getAttributeValue(0).equals("id") && xpp.getDepth()==4)
{
xpp.next();
xpp.next();
id=xpp.getText();
System.out.println("fullname : "+ xpp.getText());
}else if(xpp.getAttributeValue(0).equals("fullname") && xpp.getDepth()==4)
{
xpp.next();
xpp.next();
name=xpp.getText();
}else if(xpp.getAttributeValue(0).equals("email") && xpp.getDepth()==4)
{
xpp.next();
xpp.next();
email=xpp.getText();
}
}
}
xpp.next();
}
}
//System.out.println("Start tag "+xpp.getName()+" "+xpp.getAttributeName(0)+" : "+xpp.getAttributeValue(0));
} else if(eventType == XmlPullParser.END_TAG) {
//System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
//System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}catch(Exception e){
System.out.println("Error in xml parsing");
e.printStackTrace();
}
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
intent1.putExtra("tuid", arg0.getTag().toString());
intent1.putExtra("token", token);
startActivity(intent1);
}
class NetworkHandler extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpResponse resp = handler.doPost(MainActivity.ipaddr + "/webservice/rest/server.php?wstoken="+token,"courseid="+courseid+"&wsfunction=moodle_user_get_users_by_courseid");
HttpEntity enty = resp.getEntity();
strem= enty.getContent();
InputStreamReader is = new InputStreamReader(strem);
sb=new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while(read != null) {
//System.out.println(read);
sb.append(read);
read =br.readLine();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ConnHelper();
}
}
}
|
3482468c0f1252d4bde8cfed99a34c38e5ea0716
|
[
"Java"
] | 12
|
Java
|
bunty2020/MoodleMobile
|
8c9f2eef3d64db1edd248e14c9cd9b9175762db0
|
befb120e157a2a49dca4c9cf27400e01f6144242
|
refs/heads/main
|
<file_sep>Критерии оценки
Максимальный балл за задание +50
при клике по клавише пианино мышкой проигрывается соответствующая этой клавише нота +5
- все клавиши проигрывают ноту
- нота проигрывается каждый раз, если кликнуть по ней несколько раз
- при однократном коротком клике проигрывается одно нота, соответствующая клавише пианино
- при клике на буквы (ноты) звук не проигрывается
- при зажатой кнопке мыши, на одной клавише пианино, происходит однократное проигрывание звука
- промежуток между клавишами пианино проверке не подлежит
при клике по клавише пианино мышкой клавиша переходит в активное состояние +5
- все клавиши реагируют на клик изменением состояния
- клавиши переходят в активное состояние каждый раз, если кликнуть по ней несколько раз
- при однократном коротком клике активной становится одна клавиша
- при клике на буквы (ноты) клавиши и буквы (ноты) не становятся активными
- при зажатой кнопке мыши, на одной клавише пианино, постоянно сохраняется активное состояние
- промежуток между клавишами пианино проверке не подлежит
при клике по клавише клавиатуры, которая соответствует клавише пианино, проигрывается нота +5
- нота проигрывается вне зависимости от того, выбрана кнопка Notes или Letters
- нота проигрывается вне зависимости от раскладки клавиатуры (русская или английская)
- нота проигрывается вне зависимости от активности кнопки CapsLock
- при зажатой кнопке клавиатуры, на одной клавише пианино, происходит однократное проигрывание звука без залипания
- одновременное нажатие нескольких клавиш проверке не подлежит
- одновременная работа мыши и клавиатуры проверке не подлежит
при клике по клавише клавиатуры, которая соответствует клавише пианино, клавиша пианино переходит в активное состояние +5
- клавиша пианино становится активной вне зависимости от того, выбрана кнопка Notes или Letters
- клавиша пианино становится активной вне зависимости от раскладки клавиатуры (русская или английская)
- клавиша пианино становится активной вне зависимости от активности кнопки CapsLock
- при зажатой кнопке клавиатуры, на одной клавише пианино, происходит однократный переход клавиши в активное состояние
- одновременное нажатие нескольких клавиш проверке не подлежит
- одновременная работа мыши и клавиатуры проверке не подлежит
можно провести курсором мышки с зажатой левой кнопкой по клавишам пианино, при этом будут проигрываться соответствующие данным клавишам ноты +5
- звук не проигрывается, если проводить по буквам (нотам)
- при начале движения с зажатой левой кнопкой мыши за пределами клавиш пианино, звук не проигрывается
можно провести курсором мышки с зажатой левой кнопкой по клавишам пианино, при этом клавиши, над которыми в данный момент находится курсор, переходят в активное состояние +5
- буквы (ноты) не переходят в активное состояние, если проводить по ним
- буквы (ноты) переходят в активное состояние, если проводить с зажатой левой кнопкой по соответствующим клавишам пианино
активное состояние клавиш пианино и соответствующих им букв или нот по стилю отличается от и неактивного состояния и состояния при наведении +5
- присутствуют три стиля для трёх состояний клавиш пианино и букв (нот): без наведения мыши, с наведением мыши, с зажатием левой клавиши мыши
при клике по переключателю Notes/Letters сменяется отображение возле клавиш пианино названий соответствующих этим клавишам нот или букв +5
- при повторном нажатии на кнопку, которая активна, не происходит переключение Notes/Letters и не сменяются ноты или буквы
активное и неактивное состояние кнопок переключателя отличаются по стилю +5
- при повторном нажатии на кнопку, которая активна, неактивная кнопка не становится активной
реализована функциональность кнопки Fullscreen, которая позволяет развернуть приложение во весь экран, выйти из полноэкранного режима, в полноэкранном режиме взаимодействует с клавишей Esc клавиатуры +5
- когда приложение развернуто в полноэкранном режиме, то нажатие кнопки Fullscreen возвращает приложение в оконный режим
- когда приложение развернуто в полноэкранном режиме, то нажатие клавиши клавиатуры Esc возвращает приложение в оконный режим
- стиль кнопки в оконном режиме отличается от стиля кнопки в полноэкранном режиме
<file_sep># vadavur-JSFE2021Q1
Private repository for @vadavur
<file_sep>
// add notes/letters changing
//--------------------------------------------------------------------------------
const LETTER_BUTTON = document.querySelector('.btn-letters');
const NOTES_BUTTON = document.querySelector('.btn-notes');
LETTER_BUTTON.addEventListener('mousedown', changeToLetters);
NOTES_BUTTON.addEventListener('mousedown', changeToNotes);
function changeToLetters() {
for (i of PIANO_KEY) {
i.classList.add('letter');
};
NOTES_BUTTON.classList.remove('btn-active');
LETTER_BUTTON.classList.add('btn-active');
}
function changeToNotes() {
for (i of PIANO_KEY) {
i.classList.remove('letter');
};
LETTER_BUTTON.classList.remove('btn-active');
NOTES_BUTTON.classList.add('btn-active');
}
// takes note's name and plays it
//--------------------------------------------------------------------------------
function playNote(note) {
const audio = new Audio();
audio.src = `assets/audio/${note}.mp3`;
audio.currentTime = 0;
audio.play();
}
// mouse to piano interactions
//--------------------------------------------------------------------------------
const PIANO = document.querySelector('.piano');
const PIANO_KEY = document.querySelectorAll('.piano-key');
const mouseDown = function(event){
if(event.target.classList.contains('piano-key')) {
playNote(event.target.dataset.note);
event.target.classList.add('piano-key-active', 'piano-key-active-pseudo', 'mouse-downed');
PIANO.addEventListener('mouseover', mouseOver);
}
}
const mouseOver = function (event){
if(event.target.classList.contains('piano-key')) {
playNote(event.target.dataset.note);
event.target.classList.add('piano-key-active', 'piano-key-active-pseudo', 'mouse-downed');
}
}
const mouseUp = function(event){
PIANO.removeEventListener('mouseover', mouseOver);
event.target.classList.remove('mouse-downed');
if(!(event.target.classList.contains('key-downed'))){
event.target.classList.remove('piano-key-active', 'piano-key-active-pseudo');
}
}
const mouseOut = function(event){
if(event.target.classList.contains('piano-key')) {
event.target.classList.remove('mouse-downed');
if(!(event.target.classList.contains('key-downed'))){
event.target.classList.remove('piano-key-active', 'piano-key-active-pseudo');
}
}
}
PIANO.addEventListener('mouseout', mouseOut);
PIANO.addEventListener('mousedown', mouseDown);
window.addEventListener('mouseup', mouseUp);
// mouseUp action in case it happens somewhere out of the tab window
window.addEventListener('blur', (event) => {
PIANO.removeEventListener('mouseover', mouseOver);
}
);
// keyboard to piano interactions
//--------------------------------------------------------------------------------
const keyDown = function(event){
for (i of PIANO_KEY) {
if (('Key' + i.dataset.letter == event.code) && !(i.classList.contains('key-downed'))){
playNote(i.dataset.note);
i.classList.add('piano-key-active', 'piano-key-active-pseudo', 'key-downed');
return;
}
}
}
const keyUp = function(event){
for (j of PIANO_KEY) {
if ('Key' + j.dataset.letter == event.code){
j.classList.remove('key-downed');
if(!(j.classList.contains('mouse-downed'))){
j.classList.remove('piano-key-active', 'piano-key-active-pseudo');
}
return;
}
}
}
document.addEventListener('keydown', keyDown);
document.addEventListener('keyup', keyUp);
// fullscreen
//--------------------------------------------------------------------------------
const FULLSCREENBTN = document.querySelector('.fullscreen');
FULLSCREENBTN.addEventListener("mousedown", function(e) {
toggleFullScreen();
}, false);
function toggleFullScreen() {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
}
|
f59c989259eebeccbdcb5a3b446cd2a3b71e385f
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
Vadavur/fortepiano
|
de34703effffa35c736629eabd3af25f5e1b5398
|
eb6f7a5b91b443f2156adfd2c57ef873605690ee
|
refs/heads/master
|
<file_sep># pdfmerge
## Description
A basic pdf merging tool in Python.
## Usage
Example:
```
python pdfmerge.py file1.pdf file2.pdf [0:10:2] [1:5] -o file3.pdf
```
Planned options:
```
usage: pdfmerge.py [-h] [-r RANGES [RANGES ...]] [-a] [-o OUTFILENAME]
filenames [filenames ...]
Merges PDFs together.
positional arguments:
filenames PDF files to merge together.
optional arguments:
-h, --help show this help message and exit
-r RANGES [RANGES ...]
Ranges (Python slicing notation)
-a
-o OUTFILENAME output filename
```
## Dependencies
- [PyPDF2](https://github.com/mstamy2/PyPDF2)
## To-Do
- [ ] implement alternate flag
- [ ] fix bookmark merging
<file_sep># ankishuffle - addon for [Anki 2.x](https://apps.ankiweb.net/)
## Function
Randomly shuffles a deck, maintaining all other original deck and card parameters.
## Usage
*work in progress*
<file_sep>import PyPDF2
import argparse
import re
parser = argparse.ArgumentParser(description='Merges PDFs together.')
parser.add_argument('filenames', nargs='+',type=str, help='PDF files to merge together.')
parser.add_argument('-r',type=str,nargs='+',dest='ranges', help="Ranges (Python slicing notation)")
parser.add_argument('-a',action='store_true')
parser.add_argument('-o', dest='outfilename', type=str, help="output filename")
args = parser.parse_args()
alternate = False
if args.a:
alternate = True
def main():
print args
merger = PyPDF2.PdfFileMerger()
with open(args.outfilename,'w') as file:
for idx,inputfile in enumerate(args.filenames):
with open(inputfile, 'r') as inputpdf:
if args.ranges:
curr_range = args.ranges[idx]
num_list = re.split('[\[:\]]',curr_range)
num_list = map(int,filter(None,num_list))
range_tuple = tuple(num_list)
merger.append(inputpdf,pages=range_tuple,import_bookmarks=False)
else:
merger.append(inputpdf,import_bookmarks=False)
merger.write(file)
merger.close()
if __name__ == '__main__':
main()<file_sep># personal tools
A collection of personal files and tools in a variety of languages.
## What's Here?
- [pdfmerge](https://github.com/jzpero/personaltools/tree/master/pdfmerge)
## Ideas
- [ ] Static site generator
- [ ] Auto-exam period schedule integrating Google Calendar
- [x] basic pdf merger
|
8c395e4a8efd0ade874e28e1d296d7687f6a3838
|
[
"Markdown",
"Python"
] | 4
|
Markdown
|
jzpero/personaltools
|
6039394262960f8e1f4e9a9e44b8fd61cf1ec2a9
|
e1a0f28669549bee65349d401adda23f84f1f475
|
refs/heads/master
|
<repo_name>ehossack/minecraft-status-webpage<file_sep>/tasks.py
from invoke import task
@task
def dev(c):
start(c, dev=True)
@task
def start(c, dev=False):
c.run(
f"FLASK_ENV={'development' if dev else 'production'} pipenv run python main.py",
echo=True,
)
<file_sep>/runserver.sh
function server() {
pipenv run python main.py
}
until server; do
echo "Server crashed with exit code $?. Respawning.." >&2
sleep 1
done<file_sep>/main.py
from mcstatus import MinecraftServer
from os import getenv
from flask import Flask
from dotenv import load_dotenv
load_dotenv(verbose=True)
app = Flask(__name__)
@app.route('/')
def status():
serverName = getenv("SERVER_NAME", "Minecraft Server")
server = MinecraftServer(getOrError("SERVER"), int(getenv("PORT")) if getenv("PORT") else None)
statusString = "<b style='color: red'>Server is down</b>"
try:
statusString = getStatusString(server)
except Exception as e:
print(e)
pass
try:
statusString += getQueryString(server)
except Exception as e:
print(e)
statusString += "<p>No further information</p>"
return f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"><style>body {{ font-family: monospace, monospace; }}</style>
<title>{serverName} Status</title>
</head>
<body>
<h3>{serverName} Status</h3>
{statusString}
</body>
</html>"""
def getStatusString(server):
status = server.status()
return f"""
<p>{status.players.online} players online</p>
<p>{status.latency}ms latency</p>"""
# 'query' has to be enabled in a servers' server.properties file.
def getQueryString(server):
query = server.query()
return f"""
<p>Online players:
<ul>{"".join([f"<li>{n}</li>" for n in query.players.names])}</ul>
</p>"""
def getOrError(variable):
if not getenv(variable):
raise Exception(f'Missing environment value for {variable}')
return getenv(variable)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=getenv('LISTEN_ON'))<file_sep>/README.md
## Requires
- [Pipenv](https://pipenv.pypa.io/en/latest/)
## To use
1. `pipenv install`
2. `echo "SERVER=myserver" > .env`
3. Dev: `pipenv run invoke start`
"prod": `./runserver.sh`
|
8bc5a8e7c3865015b73b08652fc1ae600708a4b5
|
[
"Markdown",
"Python",
"Shell"
] | 4
|
Python
|
ehossack/minecraft-status-webpage
|
01eadf72cc6fd24bad98b908074d5af14cf6e7f2
|
ccb53bf7ccc5f41835ad70c89bdf7054aa9c34db
|
refs/heads/main
|
<file_sep>import requests
import time
from playsound import playsound
def getStates():
# to get the covid vaccine session details
district_id = input("Enter the district ID: ")
date = input("Enter the date (dd-mm-yyyy): ")
sessison = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id="+district_id+"&date="+date
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}
my_json = requests.get(sessison, headers=headers).json()
c = 0
print(f'Session Details')
for i in my_json['sessions']:
c = c + 1
print('-' * 100)
print('Place: ', c)
print("center id: ", i['center_id'], "\nCenter Name:", i['name'], '\nAdrresss: ', i['address'], '\nDistrict: ',
i['district_name'], '\nState: ', i['state_name'], '\nPincode: ', i['pincode'])
print('Date: ', i['date'], '\nTotal available capacity: ', i['available_capacity'],
'\nAvailable Capacity for first dose: ', i['available_capacity_dose1'],
'\nAvailable Capacity for second dose: ', i['available_capacity_dose2'])
print('Fee: ', i['fee'], '\nAge limit: ', i['min_age_limit'], '\nVaccine name: ', i['vaccine'])
print('Available slots', i['slots'])
if __name__ == '__main__':
while True:
getStates()
#to play a notification sound
playsound("D:\\api\\cowin\\SmsRingtone1.mp3")
time_wait = 5
print(f'\nWating for {time_wait} minutes ....')
time.sleep(time_wait * 60)
<file_sep># API
Learning API
<file_sep>import tkinter as tk
import time
import requests
def getWeather(canvas):
city = textfield.get()
#for appid give the api key
api = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&appid="
json_data = requests.get(api).json()
cond = json_data['weather'][0]['main']
temp = int(json_data['main']['temp'] - 273.15)
max_temp = int(json_data['main']['temp_max'] - 273.15)
min_temp = int(json_data['main']['temp_min'] - 273.15)
pressure = json_data['main']['pressure']
humidity = json_data['main']['humidity']
speed = json_data['wind']['speed']
sunrise = time.strftime("%I:%M:%S",time.gmtime(json_data['sys']['sunrise'] - 21600))
sunset = time.strftime("%I:%M:%S",time.gmtime(json_data['sys']['sunset'] - 21600))
final_info = cond + "\n" + str(temp) + "°C"
final_data = "\n"+ "Min Temp: " + str(min_temp) + "°C" + "\n" + "Max Temp: " + str(max_temp) + "°C" +"\n" + "Pressure: " + str(pressure) + "\n" +"Humidity: " + str(humidity) + "\n" +"Wind Speed: " + str(speed) + "\n" + "Sunrise: " + sunrise + " AM"+"\n" + "Sunset: " + sunset+" PM"
label1.config(text = final_info)
label2.config(text = final_data)
canvas = tk.Tk()
canvas.geometry('600x700')
canvas.title("Weather Report")
canvas.configure(bg='#505e54')
f =('Courier New',18,"bold")
t =('Comic Sans MS',35,"bold")
textfield = tk.Entry(canvas,fg ='#505e54',bg = "#ccdbd0" ,font=t)
textfield.pack(pady = 25)
textfield.focus()
textfield.bind('<Return>', getWeather)
label1 = tk.Label(canvas, fg = "#ccdbd0",
bg = "#505e54", font = t)
label1.pack()
label2 = tk.Label(canvas,fg = "#ccdbd0",
bg = "#505e54", font = f)
label2.pack()
canvas.mainloop()
|
5c6e9ebf9c6f86157f4af710007c2079d600592a
|
[
"Markdown",
"Python"
] | 3
|
Python
|
x0Yukthi/API
|
5822fcb37da5f8690799010d90d4f4ced2637cbc
|
914071bb43fa9eabd7c663b3db9b6929dfa54a6e
|
refs/heads/master
|
<repo_name>ha-matsumu/trivial-quiz-express<file_sep>/public/js/index.js
const quizInstances = [];
fetch("https://opentdb.com/api.php?amount=10")
.then(response => {
return response.json();
})
.then(response => {
return response.results;
})
.then(quizDataList => {
quizDataList.forEach(quizData => {
quizInstances.push(new Quiz(quizData));
});
console.log("クイズデータ : ", quizInstances);
});
|
f5a52a922b80f71249d5f3453fa699eb1711e8d6
|
[
"JavaScript"
] | 1
|
JavaScript
|
ha-matsumu/trivial-quiz-express
|
7641b76146a584fc86c7947fd8422d682ec1572b
|
fc2eccb8c8c6b904ccfc63658d4b2028001563f4
|
refs/heads/master
|
<file_sep>use nix::Error;
use nix::errno::*;
use nix::unistd::*;
use nix::sys::ptrace::*;
use nix::sys::ptrace::ptrace::*;
use std::ptr;
#[test]
fn test_ptrace() {
// Just make sure ptrace can be called at all, for now.
// FIXME: qemu-user doesn't implement ptrace on all arches, so permit ENOSYS
let err = ptrace(PTRACE_ATTACH, getpid(), ptr::null_mut(), ptr::null_mut()).unwrap_err();
assert!(err == Error::Sys(Errno::EPERM) || err == Error::Sys(Errno::ENOSYS));
}
|
8d25ed6ca7ff97709ac477883ba806e2a3b1b9c8
|
[
"Rust"
] | 1
|
Rust
|
vincenthage/nix
|
cfffc9360dffd64574b5f3b6c29f5622cfb883d8
|
0e302945ad3d1ca9b3bb4f9a1c7bc8cdf66dbfa2
|
refs/heads/main
|
<repo_name>skerra/ezcommand<file_sep>/README.md
# EZcommand
It makes it easy to access/call functions by user input. For C++ users.
## How to use
First you need to initialize it and include the header.
```cpp
#include "ezcommand.h"
CommandAPI cm;
```
Then you put in a function you want to use along with a name and put the parameter as ```vector<string>``` (```vector<string>``` is always neccesary even if your function doesn't use parameters and you cannot use any other vector type). e.g:
```cpp
#include "ezcommand.h"
#include <iostream>
CommandAPI cm;
void test(vector<string> param) {
std::cout << "Oh hi mark.\n";
}
void main() {
// Puts the command into a functionlist to be used.
cm.PushCommand(test, "test_command_name");
}
```
And then you can call it using something like this:
```cpp
#include "ezcommand.h"
#include <iostream>
CommandAPI cm;
void test(vector<string> param) {
std::cout << "Oh hi mark.\n";
std::cout << "You say: " << param[0];
}
void main() {
string command = "test_command_name";
vector<string> params{ "I'm so cool." };
// Puts the command into a functionlist to be used.
cm.PushCommand(test, "test_command_name");
cm.UseCommand(command, params);
}
```
If you want to have user input instead you can use:
```cpp
#include "ezcommand.h"
#include <iostream>
CommandAPI cm;
void test(vector<string> param) {
std::cout << "Oh hi mark.\n";
std::cout << "You say: ";
for (auto t : param) {
std::cout << t << " ";
}
}
void main() {
string cmd;
vector<string> params;
// Puts the command into a functionlist to be used.
cm.PushCommand(test, "say");
// This will get the input of the user and store their command and parameters in cmd and params respectively.
cm.GetCommandInput(cmd, params);
cm.UseCommand(cmd, params);
}
```
#
Here is another example:
```cpp
#include "ezcommand.h"
using namespace std;
CommandAPI cm;
int kd = 0;
// Command Functions
void test(vector<string> params) {
for (auto t : params) {
kd += stoi(t);
}
}
void test2(vector<string> params) {
for (auto t : params) {
kd -= stoi(t);
}
}
// MAIN
int main() {
cm.PushCommand(test, "add");
cm.PushCommand(test2, "sub");
string command;
vector<string> params;
while (1) {
cout << "Your command sir: ";
cm.GetCommandInput(command, params);
cm.UseCommand(command, params);
cout << kd << endl;
}
return 0;
}
```
<file_sep>/ezcommand.h
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using std::string;
using std::vector;
// For getting thos sweet command stuff
class CommandAPI {
public:
vector<void(*)(vector<string>)> functions;
vector<string> fnames;
// Pushes a new function into the list along with its name
void PushCommand(void (*f)(vector<string>), string name) {
functions.push_back(f);
fnames.push_back(name);
}
// Gets user input for a command and outputs to the referenced parameters
void GetCommandInput(string& command, vector<string>& params) {
string c, l, p;
vector<string> pp;
std::cin >> c;
std::getline(std::cin, l);
std::istringstream stream(l);
while (stream >> p) {
pp.push_back(p);
}
command = c;
params = pp;
}
// Uses a function
void UseCommand(string name, vector<string> params) {
bool commandYes = false;
for (int i = 0; i < fnames.size(); i++) {
if (name == fnames[i]) {
commandYes = true;
functions[i](params);
}
}
if (!commandYes) {
std::cerr << "Error: " << name << " does not exist!\n";
}
}
};
|
59bd63daf498c58dda9116d1246706abe480e128
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
skerra/ezcommand
|
45eaf4e8593bbf2d8f6e555cf81ec0445a74ad77
|
30e0382bc23d3b1ce8c853282e8065796956498b
|
refs/heads/master
|
<repo_name>piccinatoalves/MVC-PHP<file_sep>/controllers/homeController.php
<?php
class homeController extends controller {
public function index(){
$dados = array();
$this->loadTemplate('home/home', $dados);
}
public function sobre(){
$dados = array();
$this->loadTemplate('home/sobre', $dados);
}
}<file_sep>/README.md
# MVC-PHP
Aplicação de uma estrutura MVC em PHP
<file_sep>/views/template.php
<!DOCTYPE html>
<html>
<head>
<title>Titulo do Site</title>
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL;?>/assets/css/template.css">
<meta id="viewport" name="viewport" content="width=device-width, user-scalable=no">
</head>
<body>
<header>
<div class="topo"><h1>Topo do site.</h1></div>
<div class="menu"><h1><a href="">Menu</a></h1> </div>
</header>
<div class="container">
<article>
<?php $this->loadViewTemplate($viewName, $viewData);
?>
</article>
</div>
<footer class="rodape">
<h1>Rodapé do site</h1>
</footer>
</body>
</html><file_sep>/models/fotos.php
<?php
class fotos extends model {
public function __contruct(){
parent::__contruct(); // roda 2 contrutores no mesmo model
}
public function getFotos(){
array();
$sql = "SELECT * FROM fotos";
$sql = $this->db->query($sql);
if($sql->rowCount() > 0){
$array = $sql->fetchAll();
}
return $array;
}
}<file_sep>/models/usuario.php
<?php
class usuario {
private $name;
public function setName($n) {
$this->name = $n;
}
public function getName() {
return $this->name;
}
}
/* Classe para fazer herança de classes, exemplo
class Pessoa {
private $nome;
private $idade
public function __construct($nome, $idade){
$this->nome = $nome;
$this->idade = $idade;
}
public function getNome(){
return $this->nome;
}
public function getIdade(){
return $this->idade;
}
}
class PessoaAdapter{
private $sexo;
private $pessoa;
public function __construct(Pessoa $pessoa){
this->pessoa = $pessoa;
}
public function setSexo($s){
$this->sexo = $s;
}
public function getSexo(){
return $this->sexo;
}
public function getNome(){
return $this->pessoa->getNome();
}
}
$pessoa = new Pessoa();
$pessoa->setNome("João");
$pa = new PessoaAdapter($pessoa);
$pa->setSexo("Masculino");
*/
|
69581740eb55962550d2c4e42924175d4ea597a1
|
[
"Markdown",
"PHP"
] | 5
|
PHP
|
piccinatoalves/MVC-PHP
|
c4686f4c655730e49ca59c52f3cc6dfc6dae0aac
|
44f6d215a91f5c4d390426961a9bd11a798b59f5
|
refs/heads/master
|
<repo_name>darth-raijin/free-money-no-scam<file_sep>/src/main/java/com/example/freemoneynoscam/controllers/IndexController.java
package com.example.freemoneynoscam.controllers;
import com.example.freemoneynoscam.services.EmailValidator;
import com.example.freemoneynoscam.services.Database;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class IndexController {
EmailValidator validator = new EmailValidator();
Database database = new Database();
@GetMapping("/")
public String index() {
return "index";
}
@GetMapping("/success")
public String success() {
return "success";
}
@GetMapping("/fail")
public String fail() {
return "fail";
}
@GetMapping("/error")
public String error() {
return "error";
}
@PostMapping("/")
public String postContact(@RequestParam MultiValueMap body) {
database.setConnection();
String result = "fail";
String input = String.valueOf(body.get("email"));
input.replace("[","");
input.replace("]","");
System.out.println(input);
// Validate email
if (validator.validate(input)) {
if(database.saveEmail(input) == 200) {
result = "success";
} else {
result = "error";
}
} else {
result = "fail";
}
// Handle redirect
if (result == "fail") {
return "redirect:/fail";
}
if (result == "success") {
return "redirect:/success";
}
if (result == "error") {
return "redirect:/error";
}
return "index";
}
}
<file_sep>/README.md
# free-money-no-scam
Springboot and Java school exercise. Learning to handle POST requests and form submissions to database with MySQL as database layer.
Made by [@JensLundJoergensen](https://github.com/JensLundJoergensen) & [@macow-lab](https://github.com/macow-lab)
|
8c800dba751d85077522480eb3d2d9939a7bef4f
|
[
"Markdown",
"Java"
] | 2
|
Java
|
darth-raijin/free-money-no-scam
|
f26cb49ce0c168543aaff378bb94199ba7b27ec5
|
edf45b63fa584632d02db2f77695041620cacefc
|
refs/heads/master
|
<repo_name>Steve-Shar-9/Diploma-Software-Project-Complete-Version<file_sep>/screens/Admin/AdminAnnouncement.js
import React, { Component } from 'react';
import { StyleSheet, FlatList, Text, View, Alert, TouchableOpacity, ImageBackground, ScrollView, BackHandler, Platform, ActivityIndicator, Image, ToastAndroid, Animated } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { Header, Overlay } from 'react-native-elements';
import { NavigationEvents } from 'react-navigation';
import * as firebase from "firebase";
///////////////////// Setting up Firebase connection /////////////////////
const config = {
apiKey: "<KEY>",
authDomain: "angelappfordatabase.firebaseapp.com",
databaseURL: "https://angelappfordatabase.firebaseio.com",
projectId: "angelappfordatabase",
storageBucket: "",
messagingSenderId: "758356549275"
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
///////////////////// Default class /////////////////////
export default class AdminAnnouncement extends Component {
static navigationOptions = {
// lock the drawer
drawerLockMode: "locked-closed"
};
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('Admin');
this.array = []
this.state.arrayHolder = []
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
// Contructor
constructor(props) {
super(props);
this.array = []
this.state = {
// Array for holding data from Firebase
arrayHolder: [],
isVisible: false,
isFetching: false,
isLoading: true,
announcementTitle: '',
announcementDepartment: '',
announcementDescription: '',
announcementPicture: '',
}
this.runTheFlatlist();
this.moveAnimation = new Animated.ValueXY({ x: 10, y: 800 })
}
_moveBall = () => {
Animated.spring(this.moveAnimation, {
toValue: { x: 0, y: 15 },
}).start()
}
// Get the announcement information on selection
GetItem(item) {
firebase.database().ref('Announcement/').on('value', (snapshot) => {
var announcementDepartment = '';
var announcementDescription = '';
snapshot.forEach((child) => {
if (item === child.key) {
announcementDepartment = child.val().announcementDepartment;
announcementDescription = child.val().announcementDescription;
}
});
this.setState({ isVisible: true, announcementTitle: item, announcementDepartment: announcementDepartment, announcementDescription: announcementDescription })
});
}
showDetailData = (announcementTitle, announcementPicture, announcementDepartment, announcementDescription) => {
this.setState({ isVisible: true, announcementTitle: announcementTitle, announcementPicture: announcementPicture, announcementDepartment: announcementDepartment, announcementDescription: announcementDescription })
}
loadingIndicator = () => {
if (this.state.isLoading === true) {
if (Platform.OS === 'ios') {
return (
<View style={{ marginTop: 200 }}>
<ActivityIndicator size={'large'} color="#3390FF" animating={this.state.isLoading} />
</View>
)
}
else {
return (
<View style={{ marginTop: 200 }}>
<ActivityIndicator size={57} color="#3390FF" animating={this.state.isLoading} />
</View>
)
}
}
else {
return (null)
}
}
runTheFlatlist = () => {
firebase.database().ref('Announcement/').on('value', (snapshot) => {
var items = [];
snapshot.forEach((child) => {
items.push({
id: child.key,
description: child.val(),
});
});
this.setState({ flatListData: items, isFetching: false, isLoading: false }, () => {
this._moveBall();});
console.log(items)
});
}
onRefresh() {
console.log('refreshing')
this.setState({ isFetching: true }, function () {
this.fetchData()
});
}
fetchData() {
if (Platform.OS === 'ios') {
alert('refreshed');
}
else {
ToastAndroid.showWithGravityAndOffset(
'Refreshed',
ToastAndroid.LONG,
ToastAndroid.BOTTOM,
25,
50,
);
}
this.runTheFlatlist();
}
render() {
return (
<View style={styles.announcementContainer} behavior='padding'>
<NavigationEvents
onDidFocus={payload => {
// console.log('did focus', payload)
this.runTheFlatlist();
}}
/>
<ImageBackground
source={require('../../images/background/Announcement.png')}
style={styles.overallBackgroundImage}
blurRadius={50}
>
<Header
statusBarProps={{ barStyle: 'light-content' }}
placement="left"
leftComponent={
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('Admin');
}}
>
<View style={[{ flexDirection: 'row' }]}>
<Icon name="arrow-left" size={22} style={styles.backBtn} />
</View>
</TouchableOpacity>}
centerComponent={<View style={styles.headerTitle}><Text style={styles.headerTitleText}>Announcement</Text></View>}
rightComponent={
<TouchableOpacity
onPress={() => {
this.array = []
this.state.arrayHolder = []
this.props.navigation.navigate('AdminAddAnnouncement');
}}
>
<View style={[{ flexDirection: 'row' }]}>
<Icon name="plus" size={22} style={styles.addBtn} />
</View>
</TouchableOpacity>}
containerStyle={{
backgroundColor: 'transparent',
justifyContent: 'space-around',
// height: 100,
borderBottomColor: "transparent",
}}
/>
{/* Overlay Screen */}
<Overlay
isVisible={this.state.isVisible}
onBackdropPress={() => this.setState({ isVisible: false })}
windowBackgroundColor="rgba(0, 0, 0, 0.7)"
overlayBackgroundColor="white"
width="82%"
height="80%"
overlayStyle={{ padding: 0, borderRadius: 10 }}
>
<View style={{ backgroundColor: '#ededed', width: '100%', height: 50, borderTopLeftRadius: 10, borderTopRightRadius: 10, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ textAlign: 'center', fontWeight: 'bold', fontSize: 17 }}>{this.state.announcementTitle}</Text>
</View>
<Image
style={{ width: '100%', height: '54%', alignSelf: 'center', flex: 0 }}
source={{ uri: this.state.announcementPicture }}
/>
<View style={{ padding: 20, height: '27%' }}>
<ScrollView>
<Text style={{ textAlign: 'center', fontSize: 18 }}>
{this.state.announcementDescription}</Text>
</ScrollView>
</View>
<View style={{ padding: 20, position: 'absolute', bottom: 0, right: 0 }}>
<Text style={{ textAlign: 'right', fontSize: 14, fontStyle: 'italic' }}>
- By Department of
<Text style={{ fontSize: 14, fontWeight: '800', fontStyle: 'italic' }}> {this.state.announcementDepartment}</Text>
</Text>
</View>
</Overlay>
{/* Overlay Screen END */}
{this.loadingIndicator()}
<ScrollView>
<Animated.View style={[styles.wrapper, this.moveAnimation.getLayout()]}>
<FlatList
onRefresh={() => this.onRefresh()}
refreshing={this.state.isFetching}
data={this.state.flatListData}
keyExtractor={item => item.id}
renderItem={({ item }) =>
<TouchableOpacity
style={styles.list}
onPress={() => this.showDetailData(item.id, item.description.announcementPicture, item.description.announcementDepartment, item.description.announcementDescription)}>
<Image
style={{ width: '100%', height: '74%', borderRadius: 10 }}
source={{ uri: item.description.announcementPicture }}
/>
<Text style={{ color: 'black', fontSize: 20, padding: 3 }}>{item.id}</Text>
</TouchableOpacity>
}
/>
</Animated.View>
</ScrollView>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
announcementContainer: {
flex: 1,
width: '100%',
height: '100%',
backgroundColor: '#32323d',
alignItems: 'center',
},
overallBackgroundImage: {
width: '100%',
height: '100%',
},
headerTitle: {
color: '#fff',
textAlign: 'center',
width: '100%'
},
headerTitleText: {
color: '#fff',
textAlign: 'center',
fontSize: 25,
fontWeight: 'bold'
},
backBtn: {
paddingLeft: 20,
width: 40,
color: '#fff'
},
addBtn: {
paddingRight: 20,
width: 40,
color: '#fff'
},
wrapper: {
width: '100%',
height: '100%',
paddingBottom: 20,
},
list: {
alignItems: 'center',
marginTop: 6,
marginBottom: 6,
marginLeft: '2.5%',
marginRight: '2.5%',
backgroundColor: 'white',
width: '95%',
height: 200,
elevation: 2,
borderRadius: 10,
},
button: {
width: '90%',
padding: 10,
backgroundColor: 'white',
borderRadius: 5,
marginTop: 12,
marginBottom: 12
},
buttonText: {
color: '#32323d',
textAlign: 'center',
fontSize: 20,
},
linearGradientStyles: {
alignItems: 'center',
height: 190,
width: '100%',
position: 'absolute',
borderTopLeftRadius: 10,
borderTopRightRadius: 10,
},
userIcon: {
backgroundColor: 'white',
width: 140,
height: 140,
borderRadius: 75,
justifyContent: 'center',
alignItems: 'center',
borderColor: '#ddd',
position: 'absolute',
borderBottomWidth: 0,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.30,
shadowRadius: 4.65,
elevation: 8,
},
overlayContentContainer: {
marginTop: 90,
marginBottom: 40,
textAlign: 'left',
justifyContent: 'center',
alignItems: 'center',
},
overlayContentStyle: {
backgroundColor: 'white',
width: '95%',
height: 'auto',
elevation: 1,
padding: 20,
borderRadius: 10,
margin: 10,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 6,
},
shadowOpacity: 0.37,
shadowRadius: 7.49,
elevation: 12,
},
overlayContentStyleTitle: {
textAlign: 'left',
fontWeight: 'bold',
fontSize: 18,
},
overlayContentStyleContent: {
textAlign: 'left',
},
});<file_sep>/screens/Student/SubEnrollment.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, FlatList, Image, AsyncStorage, Picker, ToastAndroid, ScrollView, Animated, Easing } from 'react-native';
import { Feather, AntDesign, MaterialIcons, Entypo } from '@expo/vector-icons';
import { Header } from 'react-native-elements';
import { LocalAuthentication } from 'expo';
import * as firebase from 'firebase';
//Setting up the connection
const config = {
apiKey: "<KEY>",
authDomain: "angelappfordatabase.firebaseapp.com",
databaseURL: "https://angelappfordatabase.firebaseio.com",
projectId: "angelappfordatabase",
storageBucket: "",
messagingSenderId: "758356549275"
};
try {
firebase.initializeApp(config);
console.log("Log into app");
} catch (e) {
console.log('App reloaded, so firebase did not re-initialize');
}
export default class home extends Component {
static navigationOptions = {
header: null
};
componentDidMount() {
this.spin();
const { navigation } = this.props;
this.focusListener = navigation.addListener("didFocus", () => {
this.spinValue = new Animated.Value(0);
});
}
componentWillUnmount() {
this.focusListener.remove();
}
constructor(props) {
super(props);
this.testingFingerPrint()
this.state = {
isVisible: true,
checkingState: '',
wordWrong: '',
sum: 0,
counter: 0,
subjectTook: [],
}
// this.moveAnimation = new Animated.ValueXY({x:10, y:800})
this.runTheFlatlist();
this.spinValue = new Animated.Value(0)
}
// _moveBall=()=>{
// Animated.spring(this.moveAnimation,{
// toValue:{x:10, y:15},
// }).start()
// }
spin() {
Animated.timing(
this.spinValue,
{
toValue: 3,
duration: 10000,
easing: Easing.linear
}
).start(() => this.spin())
}
render() {
// Spin animation
const spin = this.spinValue.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg']
})
return (
<View style={{ height: '100%', backgroundColor: '#d9d9d9' }}>
<Header
statusBarProps={{ barStyle: 'light-content' }}
barStyle="dark-content"
leftComponent={<Feather name="menu" size={25} color="white" onPress={() => this.props.navigation.openDrawer()} />}
centerComponent={
<View style={styles.centerHeader}>
<Animated.Image
style={{
width: 30,
height: 30,
borderRadius: 15,
transform: [{ rotate: spin }]
}}
source={require('../../images/octo2.jpg')}
/>
<Text style={{ fontSize: 25, color: 'white', marginLeft: 10 }}>Turritopsis</Text>
</View>}
// rightComponent={<Feather name="home" size={25} color="#2e2e38" onPress={() =>
// this.props.navigation.openDrawer()
// } />}
containerStyle={{
backgroundColor: '#2e2e38',
// backgroundColor: 'white',
borderBottomWidth: 0,
display: "flex",
shadowColor: "#2e2e38",
shadowOffset: {
width: 3,
height: 4,
},
shadowOpacity: 0.30,
shadowRadius: 4.65,
elevation: 8,
zIndex: 5
}}
/>
<Text style={{ fontSize: 20, margin: '2.5%' }}><Entypo name="book" size={30} color="black" /> Subject(s) Enrollment</Text>
{/* abit buggy keep ask propmt again */}
{/* <Overlay
isVisible={this.state.isVisible}
// onBackdropPress={() => this.setState({ isVisible: false })}
windowBackgroundColor="rgba(0, 0, 0, 0.7)"
overlayBackgroundColor="white"
width="62%"
height="40%"
>
<View style={styles.container}>
<Ionicons name="md-finger-print" size={60} color="black" />
<Text style={{ alignSelf: 'center' }}>Please scan your finger</Text>
{this.checkingState()}
</View>
</Overlay> */}
<ScrollView style={styles.wrapper}>
<FlatList
data={this.state.flatListData}
keyExtractor={item => item.id}
renderItem={({ item }) =>
<TouchableOpacity
style={styles.list}
onPress={() =>
this.selectItem(item.description.data.price, item.description.data.id, item.description.data.name)
}>
<View style={{ flexDirection: 'row', paddingLeft: 10, backgroundColor: 'white', height: 49, borderRadius: 2, }}>
<MaterialIcons name="class" size={39} color="black" />
<View style={{ flex: 1, }}>
<Text style={{ fontSize: 20, marginLeft: 5, }}>{item.description.data.name}{'\n'}{item.description.data.id}</Text>
</View>
<View style={{ flex: 1, paddingRight: 10 }}>
<Text style={{ textAlign: 'right', fontSize: 20, marginLeft: 6, }}>RM{item.description.data.price}</Text>
</View>
</View>
<Text></Text>
</TouchableOpacity>
}
/>
<Text style={{ textAlign: 'center', fontSize: 15, margin: 15 }}>End of the Page</Text>
</ScrollView>
<TouchableOpacity
onPress={() => this.subjectEnrolled()}
style={styles.buttonFloating}>
<AntDesign name="check" size={47} color="white" style={{ bottom: -5, right: -5, }} />
</TouchableOpacity>
</View>
);
}
subjectEnrolled = async () => {
// ----------------------Saving parts----------------------------
try {
await AsyncStorage.setItem('@SubEnroll:Sub', "The Fee for This semester is RM" + this.state.sum + "\n" + this.state.subjectTook);
console.log('saved to localStorage');
this.props.navigation.navigate('Home');
} catch (error) {
console.log('error saving data to localStorage');
}
ToastAndroid.showWithGravityAndOffset(
"The Fee for This semester is RM" + this.state.sum + "\n" + this.state.subjectTook,
ToastAndroid.LONG,
ToastAndroid.CENTER,
25,
50,
);
}
selectItem = async (price, id, name) => {
if (this.state.counter < 5) {
this.state.counter += 1;
this.state.sum += price;
//get the number
var index = this.state.flatListData.findIndex(obj => obj.description.data.id === id)
//For the splicing thing
var itemArray = this.state.flatListData;
//Cutting out
itemArray.splice(index, 1)
//Reload
this.setState({ flatListData: itemArray })
console.log("Rm", this.state.sum);
//Get the data set the thing to (subjectTook state)
var newName = name + ": " + id + "\n";
this.state.subjectTook.push(newName);
console.log(this.state.subjectTook);
}
else {
alert("cant take 6 sub")
}
};
runTheFlatlist = () => {
firebase.database().ref('users/' + 'c188211/enrollSub').on('value', (snapshot) => {
var items = [];
snapshot.forEach((child) => {
items.push({
id: child.key,
description: { data: child.val().description, isSelect: false },
date: child.val().date,
});
});
this.setState({ flatListData: items }, () => {
// this._moveBall();
});
});
}
hopefullywork = () => {
if (this.state.language === 'April intake') {
<Picker
style={styles.picker} itemStyle={styles.pickerItem}
selectedValue={this.state.language}
onValueChange={(itemValue) => this.setState({ language: itemValue })}
>
<Picker.Item label="June intake" value="js" />
<Picker.Item label="September intake" value="python" />
<Picker.Item label="December intake" value="haxe" />
</Picker>
}
else {
<Picker
style={styles.picker} itemStyle={styles.pickerItem}
selectedValue={this.state.language}
onValueChange={(itemValue) => this.setState({ language: itemValue })}
>
<Picker.Item label="April intake" value="java" />
<Picker.Item label="June intake" value="js" />
<Picker.Item label="September intake" value="python" />
<Picker.Item label="December intake" value="haxe" />
</Picker>
}
}
checkingState = () => {
if (this.state.checkingState === 'true') {
return (
<View style={styles.container}>
<Text style={{ fontSize: 11 }}>{"\n\n\n"}</Text>
<AntDesign name="checkcircle" size={47} color="green" onPress={() => this.setState({ isVisible: false })} />
<Text style={{ fontSize: 10 }}>{"\n\n\n\n"}Press the icon to proceed</Text>
</View>
)
}
if (this.state.checkingState === 'false') {
return (
<View style={styles.container}>
<Text style={{ fontSize: 11 }}>{"\n\n\n"}</Text>
<AntDesign name="exclamationcircle" size={47} color="red" onPress={() =>
this.wrongFingerprint()} />
<Text style={{ fontSize: 10, textAlign: 'center' }}>{"\n\n\n\n"}Wrong Fingerprint! {"\n"}Press icon to Try again</Text>
<Text style={{ color: 'red', fontSize: 13, textAlign: 'center' }}>{this.state.wordWrong}</Text>
</View>
)
}
}
wrongFingerprint = () => {
this.setState({ wordWrong: 'Fingerprint not matched.' })
// this.props.navigation.navigate('home')
this.testingFingerPrint();
}
testingFingerPrint = async () => {
const result = await LocalAuthentication.authenticateAsync('Verify your bio id');
console.log(result); //<-- {"error": "unknown", "message": "", "success": false}
if (result.success) {
this.setState({ checkingState: 'true' });
}
if (result.error === 'authentication_failed') {
this.setState({ checkingState: 'false' })
}
if (result.error === 'user_cancel') {
this.testingFingerPrint()
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
alignItems: 'center',
justifyContent: 'center',
padding: 20
},
centerHeader: {
flexDirection: 'row',
},
wrapper: {
width: '100%',
height: '100%',
marginTop: 5,
marginBottom: 10,
},
list: {
padding: 20,
fontSize: 18,
textAlign: 'center',
color: 'black',
backgroundColor: 'white',
width: '92%',
height: 100,
borderRadius: 10,
marginTop: 8,
marginRight: 8,
marginLeft: '4%',
marginRight: '4%',
elevation: 1,
},
buttonFloating: {
width: 60,
height: 60,
borderRadius: 30,
backgroundColor: 'green',
position: 'absolute',
bottom: 14,
right: 14,
// borderColor:'grey'
}
});<file_sep>/screens/Admin/AdminTimetable.js
import React, { Component } from 'react';
import {
ActivityIndicator,
Button,
Clipboard,
Image,
Share,
StatusBar,
StyleSheet,
Text,
TouchableOpacity,
View,
ImageBackground,
BackHandler
} from 'react-native';
import { Constants, ImagePicker, Permissions } from 'expo';
import { Header, Overlay } from 'react-native-elements';
import { Feather, Entypo, FontAwesome, AntDesign } from '@expo/vector-icons';
import Icon from 'react-native-vector-icons/FontAwesome';
import * as firebase from 'firebase';
import { NavigationEvents } from 'react-navigation';
//Setting up the connection
const config = {
apiKey: "<KEY>",
authDomain: "angelappfordatabase.firebaseapp.com",
databaseURL: "https://angelappfordatabase.firebaseio.com",
projectId: "angelappfordatabase",
storageBucket: "",
messagingSenderId: "758356549275"
};
try {
firebase.initializeApp(config);
console.log("Log into app");
} catch (e) {
console.log('App reloaded, so firebase did not re-initialize');
}
//This one will be on admin side
export default class App extends Component {
static navigationOptions = {
// lock the drawer
drawerLockMode: "locked-closed"
};
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('Admin');
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
state = {
image: null,
uploading: false,
};
render() {
let {
image
} = this.state;
return (
<View>
<NavigationEvents
onDidFocus={payload => {
// console.log('did focus', payload)
this.setState({isVisible:false});
}}
/>
<ImageBackground
source={require('../../images/background/Timetable1.jpg')}
style={styles.overallBackgroundImage}
blurRadius={50}
>
<Header
statusBarProps={{ barStyle: 'light-content' }}
barStyle="dark-content"
leftComponent={
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('Admin');
}}
>
<View style={[{ flexDirection: 'row' }]}>
<Icon name="arrow-left" size={22} style={styles.backBtn} />
</View>
</TouchableOpacity>}
centerComponent={{ text: 'Home', style: { fontSize: 25, color: '#fff' } }}
containerStyle={{
backgroundColor: 'transparent',
borderBottomColor: "transparent",
}}
/>
<View style={{ backgroundColor: 'transparent', height: '36%', marginTop: 50, justifyContent: 'center', alignItems: 'center' }}>
<View style={{ backgroundColor: 'rgba(255,255,255,0.4)', borderRadius: 100, width: 190, height: 190, justifyContent: 'center', alignItems: 'center' }}>
<AntDesign name="cloud" size={100} color="white" />
</View>
{/* this one have to change if it is the real one */}
{/* <Text style={{ color: 'white' }}>{'\n'}Cloud photo storage{'\n'}<EMAIL></Text> */}
</View>
<View style={styles.container}>
{this._maybeRenderImage()}
{this._maybeRenderUploadingOverlay()}
<TouchableOpacity
onPress={this._pickImage}
style={styles.button}>
<View style={styles.center}>
<Text style={styles.buttonText}>
Upload Photo
</Text>
</View>
</TouchableOpacity>
</View>
</ImageBackground>
</View>
);
}
//----------------------------------SAVE--------------------------------
firebaseDataSaving = () => {
//----------------------------Random number generator----------------
var RandomNumber = 'timeTable';
var timetableUrl = this.state.image;
db = firebase.database().ref('users/')
db.child(RandomNumber).set({
timetableUrl: this.state.image
}).then((data) => { alert('saved'); }).catch((error) => { alert('failed'); })
}
_maybeRenderUploadingOverlay = () => {
if (this.state.uploading) {
return (
<View>
<ActivityIndicator color="green" size="large" />
</View>
);
}
};
_maybeRenderImage = () => {
let {
image
} = this.state;
if (!image) {
return (
<View>
<Text>{"\n\n"}</Text>
<Text
style={styles.exampleText}>
All trips successfully uploaded
{'\n\n\n\n'}
</Text>
</View>
);
}
//based on what i knew here this.state.image is the place where we stored the url of the image
return (
<View style={styles.container}>
{/* <View
style={styles.maybeRenderImageContainer}>
<Image source={{ uri: image }} style={styles.maybeRenderImage} />
</View> */}
{/* <Text
onPress={this._copyToClipboard}
onLongPress={this._share}
style={styles.maybeRenderImageText}>
{image}
</Text> */}
<Text>{"\n\n\n"}</Text>
<AntDesign name="check" size={94} color="green" />
<Text
style={styles.exampleText}>
Timetable photo upload
{'\n\n\n'}
</Text>
</View>
);
};
_share = () => {
Share.share({
message: this.state.image,
title: 'Check out this photo',
url: this.state.image,
});
};
_copyToClipboard = () => {
Clipboard.setString(this.state.image);
alert('Copied image URL to clipboard');
};
_takePhoto = async () => {
const {
status: cameraPerm
} = await Permissions.askAsync(Permissions.CAMERA);
const {
status: cameraRollPerm
} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera AND camera roll
if (cameraPerm === 'granted' && cameraRollPerm === 'granted') {
let pickerResult = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [4, 3],
});
this._handleImagePicked(pickerResult);
}
};
_pickImage = async () => {
const {
status: cameraRollPerm
} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera roll
if (cameraRollPerm === 'granted') {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 6],
});
this._handleImagePicked(pickerResult);
}
};
_handleImagePicked = async pickerResult => {
let uploadResponse, uploadResult;
try {
this.setState({
uploading: true
});
if (!pickerResult.cancelled) {
uploadResponse = await uploadImageAsync(pickerResult.uri);
uploadResult = await uploadResponse.json();
this.setState({
image: uploadResult.location
});
this.firebaseDataSaving();
}
} catch (e) {
console.log({ uploadResponse });
console.log({ uploadResult });
console.log({ e });
alert('Upload failed, sorry :(');
} finally {
this.setState({
uploading: false
});
}
};
}
async function uploadImageAsync(uri) {
let apiUrl = 'https://file-upload-example-backend-dkhqoilqqn.now.sh/upload';
// Note:
// Uncomment this if you want to experiment with local server
//
// if (Constants.isDevice) {
// apiUrl = `https://your-ngrok-subdomain.ngrok.io/upload`;
// } else {
// apiUrl = `http://localhost:3000/upload`
// }
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
let formData = new FormData();
formData.append('photo', {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
return fetch(apiUrl, options);
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
// flex: 0,
justifyContent: 'center',
},
overallBackgroundImage: {
width: '100%',
height: '100%',
},
exampleText: {
fontSize: 20,
marginBottom: 20,
marginHorizontal: 15,
textAlign: 'center',
color: 'white'
},
maybeRenderUploading: {
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.4)',
justifyContent: 'center',
},
maybeRenderContainer: {
borderRadius: 3,
elevation: 2,
marginTop: 30,
shadowColor: 'rgba(0,0,0,1)',
shadowOpacity: 0.2,
shadowOffset: {
height: 4,
width: 4,
},
shadowRadius: 5,
width: 250,
},
maybeRenderImageContainer: {
borderTopLeftRadius: 3,
borderTopRightRadius: 3,
overflow: 'hidden',
},
maybeRenderImage: {
height: 250,
width: 250,
},
maybeRenderImageText: {
paddingHorizontal: 10,
paddingVertical: 10,
},
backBtn: {
paddingLeft: 20,
width: 40,
color: '#fff'
},
button: {
width: '100%',
position: 'absolute',
bottom: -25,
},
buttonText: {
width: '80%',
borderWidth: 1,
borderRadius: 60 / 2,
padding: 15,
borderColor: 'white',
backgroundColor: 'transparent',
color: 'white',
textAlign: 'center',
fontSize: 20,
// fontWeight: '800',
overflow: 'hidden',
},
center: {
alignItems: 'center',
},
});<file_sep>/screens/Student/Home.js
import React, { Component } from 'react';
import { StyleSheet, ScrollView, Text, View, TouchableOpacity, Platform, FlatList, Image, ToastAndroid, ActivityIndicator, Animated, Easing } from 'react-native';
import { Feather } from '@expo/vector-icons';
import { Header, Overlay } from 'react-native-elements';
import * as firebase from 'firebase';
import { NavigationEvents } from 'react-navigation';
//Setting up the connection
const config = {
apiKey: "<KEY>",
authDomain: "angelappfordatabase.firebaseapp.com",
databaseURL: "https://angelappfordatabase.firebaseio.com",
projectId: "angelappfordatabase",
storageBucket: "",
messagingSenderId: "758356549275"
};
try {
firebase.initializeApp(config);
console.log("Log into app");
} catch (e) {
console.log('App reloaded, so firebase did not re-initialize');
}
export default class home extends Component {
componentDidMount() {
this.spin();
const { navigation } = this.props;
this.focusListener = navigation.addListener("didFocus", () => {
this.spinValue = new Animated.Value(0);
});
}
componentWillUnmount() {
// Remove the event listener
this.focusListener.remove();
}
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
this.state = {
isVisible: false,
text1: '',
dataStoring: [],
testArray: [],
moreNote: '',
NumberHolder: 1,
isFetching: false,
isLoading: true,
announcementTitle: '',
announcementDepartment: '',
announcementDescription: '',
announcementPicture: '',
}
this.runTheFlatlist();
this.moveAnimation = new Animated.ValueXY({x:10, y:800})
// this.moveAnimation = new Animated.ValueXY({x:156, y:10})
this.spinValue = new Animated.Value(0)
}
spin() {
Animated.timing(
this.spinValue,
{
toValue: 3,
duration: 10000,
easing: Easing.linear
}
).start(() => this.spin())
}
_moveBall=()=>{
Animated.spring(this.moveAnimation,{
toValue:{x:0, y:15},
}).start()
}
render() {
// Spin animation
const spin = this.spinValue.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg']
})
return (
<View style={{ height: '100%', width: '100%', backgroundColor: '#ededed' }}>
<NavigationEvents
// onWillFocus={payload => console.log('will focus',payload)}
onDidFocus={payload => {
console.log('did focus',payload)
this.runTheFlatlist();
}}
// onWillBlur={payload => console.log('will blur',payload)}
// onDidBlur={payload => console.log('did blur',payload)}
/>
<Header
statusBarProps={{ barStyle: 'light-content' }}
barStyle="dark-content"
leftComponent={<Feather name="menu" size={25} color="white" onPress={() => this.props.navigation.openDrawer()} />}
centerComponent={
<View style={styles.centerHeader}>
<Animated.Image
style={{
width: 30,
height: 30,
borderRadius: 15,
transform: [{ rotate: spin }]
}}
source={require('../../images/octo2.jpg')}
/>
{/* <Image source={require('../../images/octo2.jpg')} style={{ height: 30, width: 30, borderRadius: 15, }} /> */}
<Text style={{ fontSize: 25, color: 'white', marginLeft: 10 }}>Turritopsis</Text>
</View>}
// rightComponent={<Feather name="home" size={25} color="#2e2e38" onPress={() =>
// this.props.navigation.openDrawer()
// } />}
containerStyle={{
backgroundColor: '#2e2e38',
// backgroundColor: 'white',
borderBottomWidth: 0,
display: "flex",
shadowColor: "#2e2e38",
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.30,
shadowRadius: 4.65,
elevation: 8,
zIndex: 5
}}
/>
<Text style={{ fontSize: 30, margin: '2.5%' }}><Feather name="home" size={30} color="black" /> Home</Text>
{/* ========DETAIL DATA RECEIVER=========*/}
<Overlay
isVisible={this.state.isVisible}
onBackdropPress={() => this.setState({ isVisible: false })}
windowBackgroundColor="rgba(0, 0, 0, 0.7)"
overlayBackgroundColor="white"
width="82%"
height="80%"
overlayStyle={{ padding: 0, borderRadius: 10 }}
>
<View style={{ backgroundColor: '#ededed', width: '100%', height: 50, borderTopLeftRadius: 10, borderTopRightRadius: 10, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ textAlign: 'center', fontWeight: 'bold', fontSize: 17 }}>{this.state.announcementTitle}</Text>
</View>
<Image
style={{ width: '100%', height: '54%', alignSelf: 'center', flex: 0, paddingLeft: '50%' }}
source={{ uri: this.state.announcementPicture }}
/>
<View style={{ padding: 20, height: '27%' }}>
<ScrollView>
<Text style={{ textAlign: 'center', fontSize: 18 }}>
{this.state.announcementDescription}</Text>
</ScrollView>
</View>
<View style={{ padding: 20, position: 'absolute', bottom: 0, right: 0 }}>
<Text style={{ textAlign: 'right', fontSize: 14, fontStyle: 'italic' }}>
- By Department of
<Text style={{ fontSize: 14, fontWeight: '800', fontStyle: 'italic' }}> {this.state.announcementDepartment}</Text>
</Text>
</View>
</Overlay>
{this.loadingIndicator()}
<ScrollView>
<Animated.View style={[styles.wrapper, this.moveAnimation.getLayout()]}>
<FlatList
onRefresh={() => this.onRefresh()}
refreshing={this.state.isFetching}
data={this.state.flatListData}
keyExtractor={item => item.id}
renderItem={({ item }) =>
<TouchableOpacity
style={styles.list}
onPress={() => this.showDetailData(item.id, item.description.announcementPicture, item.description.announcementDepartment, item.description.announcementDescription)}>
<Image
style={{ width: '100%', height: '74%', borderRadius: 10 }}
source={{ uri: item.description.announcementPicture }}
/>
<Text style={{ color: 'black', fontSize: 20, padding: 3 }}>{item.id}</Text>
</TouchableOpacity>
}
/>
<Text style={{ textAlign: 'center', fontSize: 15, margin: 15 }}>End of the Page</Text>
</Animated.View>
</ScrollView>
</View>
);
}
loadingIndicator = () => {
if (this.state.isLoading === true) {
if (Platform.OS === 'ios') {
return (
<View style={{ marginTop: 200 }}>
<ActivityIndicator size={'large'} color="#3390FF" animating={this.state.isLoading} />
</View>
)
}
else {
return (
<View style={{ marginTop: 200 }}>
<ActivityIndicator size={57} color="#3390FF" animating={this.state.isLoading} />
</View>
)
}
}
else {
return (null)
}
}
//--------------------REFRESH FUNCTION-----------------------
onRefresh() {
console.log('refreshing')
this.setState({ isFetching: true }, function () {
this.fetchData()
});
}
fetchData() {
if (Platform.OS === 'ios') {
alert('refreshed');
}
else {
ToastAndroid.showWithGravityAndOffset(
'Refreshed',
ToastAndroid.LONG,
ToastAndroid.BOTTOM,
25,
50,
);
}
this.runTheFlatlist();
}
//-------------------------------SHOW DETAIL DATA------------------------
showDetailData = (announcementTitle, announcementPicture, announcementDepartment, announcementDescription) => {
this.setState({ isVisible: true, announcementTitle: announcementTitle, announcementPicture: announcementPicture, announcementDepartment: announcementDepartment, announcementDescription: announcementDescription })
}
//------------------------------DATA RELOADER-----------------------------
runTheFlatlist = () => {
firebase.database().ref('Announcement/').on('value', (snapshot) => {
var items = [];
snapshot.forEach((child) => {
items.push({
id: child.key,
description: child.val(),
});
});
this.setState({ flatListData: items, isFetching: false, isLoading: false }, () => {
this._moveBall();
});
console.log(items)
});
}
//----------------------------------SAVE--------------------------------
firebaseDataSaving = (userId) => {
//----------------------------Random number generator----------------
var RandomNumber = Math.floor(Math.random() * 10000) + 1;
var note = "This is notes for people who want to enroll subject"
var photo = 'https://is.org.au/wp-content/uploads/2017/01/MaGz2.jpg'
var moreNote = "You may go to ground floor and get the form and go to fifth floor for the register"
db = firebase.database().ref('users/c188211')
db.child(RandomNumber).set({
description: { note, photo, moreNote }
}).then((data) => { alert('saved'); }).catch((error) => { alert('failed'); })
}
//-------------------------------OUTPUT FUNCTION----------------------------
outputDataFunction = (userId) => {
firebase.database().ref('users/' + userId).on('value', (snapshot) => {
// const description = snapshot.val().description;
// alert("Description: " + description);
var items = [];
console.log(snapshot.val().description);
snapshot.forEach((child) => {
items.push({
id: child.key,
description: child.val().description,
date: child.val().date,
});
});
console.log(items);
});
}
//-------------------------------DELETE DATA FUNCTION-----------------
deleteFunction = () => {
this.itemsRef = firebase.database().ref('users/' + 'c188211')
this.itemsRef.child('description').remove()
}
}
//-------------------------------------STYLING----------------
const styles = StyleSheet.create({
wrapper: {
marginTop: -15,
paddingBottom: 25,
},
list: {
alignItems: 'center',
marginTop: 5,
marginBottom: 12,
marginLeft: '2.5%',
marginRight: '2.5%',
backgroundColor: 'white',
width: '95%',
height: 200,
borderRadius: 10,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 3,
},
shadowOpacity: 0.27,
shadowRadius: 4.65,
elevation: 6,
},
centerHeader: {
flexDirection: 'row',
},
});<file_sep>/screens/Main.js
import React from 'react';
import { Alert, TouchableOpacity, View, Text, StyleSheet, Animated, AsyncStorage } from 'react-native'
///////////////////// Fade in animation /////////////////////
class Animations extends React.Component {
state = {
fadeAnim: new Animated.Value(0),
}
componentDidMount() {
Animated.timing(
this.state.fadeAnim,
{
toValue: 1,
duration: 500,
}
).start();
}
render() {
let { fadeAnim } = this.state;
return (
<Animated.View
style={{
...this.props.style,
opacity: fadeAnim,
}}
>
{this.props.children}
</Animated.View>
);
}
}
// Default export function
export default class Main extends React.Component {
static navigationOptions = {
// lock the drawer
drawerLockMode: "locked-closed"
};
constructor(props) {
super(props)
this.state = {
userName: '',
}
AsyncStorage.getItem('userName').then((value) => this.setState({ 'userName': value }))
}
render() {
return (
// <View style={styles.mainScreenContainer}>
<Animations style={styles.mainScreenContainer}>
<TouchableOpacity style={styles.circleOnly}
onPress={() => {
Alert.alert('Press "Log In" to continue')
}}>
</TouchableOpacity>
<Text style={styles.firstTitle}>Start{'\n'}your{'\n'}day !</Text>
<TouchableOpacity
onPress={() => {
if (this.state.userName === 'Logged Out') {
this.props.navigation.navigate('Login');
} else if (this.state.userName === 'Admin'){
this.props.navigation.navigate('Admin');
} else {
this.props.navigation.navigate('Home');
}
}}
style={styles.TouchableOpacityStyle}>
<View style={styles.center}>
<Text style={styles.text}>
Log In
</Text>
</View>
</TouchableOpacity>
</Animations>
// </View>
);
}
}
const styles = StyleSheet.create({
mainScreenContainer: {
flex: 1,
backgroundColor: '#ffffff',
},
circleOnly: {
width: 47,
height: 47,
backgroundColor: '#ffffff',
borderColor: '#4c4c4c',
borderWidth: 7,
borderRadius: 47 / 2,
marginTop: '20%',
marginBottom: '20%',
marginLeft: '15%',
},
firstTitle: {
marginLeft: '15%',
color: '#4c4c4c',
fontWeight: '800',
fontSize: 50,
},
TouchableOpacityStyle: {
width: '100%',
position: 'absolute',
bottom: 30,
},
text: {
width: '70%',
borderWidth: 1,
borderRadius: 60 / 2,
padding: 15,
borderColor: '#ffa654',
backgroundColor: '#ffa654',
color: 'white',
textAlign: 'center',
fontSize: 20,
overflow: 'hidden',
},
center: {
alignItems: 'center',
},
});<file_sep>/screens/Student/Timetable.js
import React, { Component } from 'react';
import {
ActivityIndicator,
Clipboard,
Image,
Share,
StyleSheet,
Text,
BackHandler,
View,
} from 'react-native';
import {ImagePicker, Permissions } from 'expo';
import {AntDesign } from '@expo/vector-icons';
import * as firebase from 'firebase';
//Setting up the connection
const config = {
apiKey: "<KEY>",
authDomain: "angelappfordatabase.firebaseapp.com",
databaseURL: "https://angelappfordatabase.firebaseio.com",
projectId: "angelappfordatabase",
storageBucket: "",
messagingSenderId: "758356549275"
};
try {
firebase.initializeApp(config);
console.log("Log into app");
} catch (e) {
console.log('App reloaded, so firebase did not re-initialize');
}
//This one will be on admin side
export default class App extends Component {
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('Home');
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
state = {
image: null,
uploading: false,
};
constructor(props) {
super(props);
this.outputDataFunction();
}
render() {
return (
<Image source={{ uri: this.state.urlFirebase }} style={styles.backgroundImage} />
);
}
outputDataFunction = () => {
firebase.database().ref('users/timeTable').on('value', (snapshot) => {
snapshot.forEach((child) => {
var newWord = `'${child.val()}'`
this.setState({ urlFirebase: child.val() })
});
console.log(this.state.urlFirebase)
});
}
//----------------------------------SAVE--------------------------------
firebaseDataSaving = () => {
//----------------------------Random number generator----------------
var RandomNumber = 'timeTable';
var timetableUrl = this.state.image;
db = firebase.database().ref('users/')
db.child(RandomNumber).set({
timetableUrl: this.state.image
}).then((data) => { alert('saved'); }).catch((error) => { alert('failed'); })
}
_maybeRenderUploadingOverlay = () => {
if (this.state.uploading) {
return (
<View>
<ActivityIndicator color="green" size="large" />
</View>
);
}
};
_maybeRenderImage = () => {
let {
image
} = this.state;
if (!image) {
return (
<View>
<Text>{"\n\n\n\n"}</Text>
<Text
style={styles.exampleText}>
All trips successfully uploaded
{'\n\n\n\n'}
</Text>
</View>
);
}
//based on what i knew here this.state.image is the place where we stored the url of the image
return (
<View style={styles.container}>
<Text>{"\n\n\n"}</Text>
<AntDesign name="check" size={94} color="green" />
<Text
style={styles.exampleText}>
All trips successfully uploaded
{'\n\n\n'}
</Text>
</View>
);
};
_share = () => {
Share.share({
message: this.state.image,
title: 'Check out this photo',
url: this.state.image,
});
};
_copyToClipboard = () => {
Clipboard.setString(this.state.image);
alert('Copied image URL to clipboard');
};
_takePhoto = async () => {
const {
status: cameraPerm
} = await Permissions.askAsync(Permissions.CAMERA);
const {
status: cameraRollPerm
} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera AND camera roll
if (cameraPerm === 'granted' && cameraRollPerm === 'granted') {
let pickerResult = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [4, 3],
});
this._handleImagePicked(pickerResult);
}
};
_pickImage = async () => {
const {
status: cameraRollPerm
} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera roll
if (cameraRollPerm === 'granted') {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 6],
});
this._handleImagePicked(pickerResult);
}
};
_handleImagePicked = async pickerResult => {
let uploadResponse, uploadResult;
try {
this.setState({
uploading: true
});
if (!pickerResult.cancelled) {
uploadResponse = await uploadImageAsync(pickerResult.uri);
uploadResult = await uploadResponse.json();
this.setState({
image: uploadResult.location
});
this.firebaseDataSaving();
}
} catch (e) {
console.log({ uploadResponse });
console.log({ uploadResult });
console.log({ e });
alert('Upload failed, sorry :(');
} finally {
this.setState({
uploading: false
});
}
};
}
async function uploadImageAsync(uri) {
let apiUrl = 'https://file-upload-example-backend-dkhqoilqqn.now.sh/upload';
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
let formData = new FormData();
formData.append('photo', {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
return fetch(apiUrl, options);
}
const styles = StyleSheet.create({
backgroundImage: {
flex: 1,
width: null,
height: null,
},
container: {
alignItems: 'center',
// flex: 0,
justifyContent: 'center',
},
exampleText: {
fontSize: 20,
marginBottom: 20,
marginHorizontal: 15,
textAlign: 'center',
},
maybeRenderUploading: {
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.4)',
justifyContent: 'center',
},
maybeRenderContainer: {
borderRadius: 3,
elevation: 2,
marginTop: 30,
shadowColor: 'rgba(0,0,0,1)',
shadowOpacity: 0.2,
shadowOffset: {
height: 4,
width: 4,
},
shadowRadius: 5,
width: 250,
},
maybeRenderImageContainer: {
borderTopLeftRadius: 3,
borderTopRightRadius: 3,
overflow: 'hidden',
},
maybeRenderImage: {
height: 250,
width: 250,
},
maybeRenderImageText: {
paddingHorizontal: 10,
paddingVertical: 10,
}
});<file_sep>/screens/Student/QRScanner.js
import React, { Component } from 'react';
import { Alert, Dimensions, LayoutAnimation, Text, View, StyleSheet,BackHandler, AsyncStorage } from 'react-native';
// import { BarCodeScanner, Permissions } from 'expo';
import { ToastAndroid } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner'
import * as Permissions from 'expo-permissions'
export default class App extends Component {
state = {
hasCameraPermission: null,
lastScannedUrl: null,
};
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('Home');
return true;
});
this._requestCameraPermission();
}
componentWillUnmount() {
this.backHandler.remove();
}
_requestCameraPermission = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({
hasCameraPermission: status === 'granted',
});
};
_handleBarCodeRead = result => {
if (result.data !== this.state.lastScannedUrl) {
LayoutAnimation.spring();
this.setState({ lastScannedUrl: result.data });
console.log(result.data);
}
};
render() {
return (
<View style={styles.container}>
{this.state.hasCameraPermission === null
? <Text>Requesting for camera permission</Text>
: this.state.hasCameraPermission === false
? <Text style={{ color: '#fff' }}>
Camera permission is not granted
</Text>
: <BarCodeScanner
onBarCodeRead={this._handleBarCodeRead}
style={{
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
}}
/>}
{this._maybeRenderUrl()}
</View>
);
}
_handlePressUrl = () => {
Alert.alert(
'Open this URL?',
this.state.lastScannedUrl,
[
{
text: 'Yes',
//this stage maybe u can put some action into it
onPress: () =>
// Linking.openURL(this.state.lastScannedUrl),
this.checkingStateQr()
},
{ text: 'No', onPress: () => { } },
],
{ cancellable: false }
);
};
//This one to same with the type one REMEMBER!!
checkingStateQr = async () => {
if (this.state.lastScannedUrl === '57212331') {
try {
await AsyncStorage.setItem('@GroupCode:key', this.state.lastScannedUrl);
console.log('saved to localStorage');
} catch (error) {
console.log('error saving data to localStorage');
}
ToastAndroid.showWithGravityAndOffset(
'Registered!!',
ToastAndroid.LONG,
ToastAndroid.BOTTOM,
25,
50,
);
this.props.navigation.navigate('insideGroupOrClass', { data: this.state.lastScannedUrl })
}
else {
}
}
_maybeRenderUrl = () => {
this.checkingStateQr();
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
},
bottomBar: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'rgba(0,0,0,0.5)',
padding: 15,
flexDirection: 'row',
},
url: {
flex: 1,
},
urlText: {
color: '#fff',
fontSize: 20,
},
cancelButton: {
marginLeft: 10,
alignItems: 'center',
justifyContent: 'center',
},
cancelButtonText: {
color: 'rgba(255,255,255,0.8)',
fontSize: 18,
},
});<file_sep>/screens/Admin/AdminDepartment.js
import React, { Component } from 'react';
import { StyleSheet, FlatList, Text, View, Alert, TouchableOpacity, ImageBackground, ScrollView, BackHandler } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { Ionicons } from '@expo/vector-icons';
import { Header, Overlay } from 'react-native-elements';
import { LinearGradient } from 'expo';
import { NavigationEvents } from 'react-navigation';
import * as firebase from "firebase";
///////////////////// Setting up Firebase connection /////////////////////
// const config = {
// apiKey: "<KEY>",
// authDomain: "diploma-software-project.firebaseapp.com",
// databaseURL: "https://diploma-software-project.firebaseio.com",
// storageBucket: "diploma-software-project.appspot.com",
// messagingSenderId: "1092827450895"
// };
const config = {
apiKey: "<KEY>",
authDomain: "angelappfordatabase.firebaseapp.com",
databaseURL: "https://angelappfordatabase.firebaseio.com",
projectId: "angelappfordatabase",
storageBucket: "",
messagingSenderId: "758356549275"
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
///////////////////// Default class /////////////////////
export default class AdminDepartment extends Component {
static navigationOptions = {
// lock the drawer
drawerLockMode: "locked-closed"
};
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('Admin');
this.array = []
this.state.arrayHolder = []
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
// Contructor
constructor(props) {
super(props);
this.array = []
this.state = {
// Array for holding data from Firebase
arrayHolder: [],
isVisible: false,
departmentName: '',
departmentEmail: '',
departmentHp: '',
}
// Get the list of student from Firebase
firebase.database().ref('Department/').on('value', (snapshot) => {
this.array = []
snapshot.forEach((child) => {
if (child.key !== 'Public'){
this.array.push({ title: child.key });
this.setState({ arrayHolder: [...this.array] })
}
})
})
}
// Get the department information on selection
GetItem(item) {
firebase.database().ref('Department/').on('value', (snapshot) => {
var departmentEmail = '';
var departmentHp = '';
snapshot.forEach((child) => {
if (item === child.key) {
departmentEmail = child.val().departmentEmail;
departmentHp = child.val().departmentHp;
}
});
this.setState({ isVisible: true, departmentName: item, departmentEmail: departmentEmail, departmentHp: departmentHp })
});
}
render() {
return (
<View style={styles.studentContainer} behavior='padding'>
<NavigationEvents
onDidFocus={payload => {
// console.log('did focus', payload)
this.setState({isVisible:false});
}}
/>
<ImageBackground
source={require('../../images/background/Timetable1.jpg')}
style={styles.overallBackgroundImage}
blurRadius={50}
>
<Header
statusBarProps={{ barStyle: 'light-content' }}
placement="left"
leftComponent={
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('Admin');
}}
>
<View style={[{ flexDirection: 'row' }]}>
<Icon name="arrow-left" size={22} style={styles.backBtn} />
</View>
</TouchableOpacity>}
centerComponent={<View style={styles.headerTitle}><Text style={styles.headerTitleText}>Department</Text></View>}
rightComponent={
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('AdminAddDepartment');
}}
>
<View style={[{ flexDirection: 'row' }]}>
<Icon name="plus" size={22} style={styles.addBtn} />
</View>
</TouchableOpacity>}
containerStyle={{
backgroundColor: 'transparent',
justifyContent: 'space-around',
borderBottomColor: "transparent",
}}
/>
{/* Overlay Screen */}
<Overlay
isVisible={this.state.isVisible}
onBackdropPress={() => this.setState({ isVisible: false })}
windowBackgroundColor="rgba(0,0,0,0.7)"
overlayBackgroundColor="white"
width='85%'
height='80%'
overlayStyle={{ padding: 0, borderRadius: 10 }}
>
{/* Header Background */}
<LinearGradient
colors={['#ABDCFF', '#0396FF']}
start={[0.0, 0.5]}
end={[1.0, 0.5]}
locations={[0.0, 1.0]}
style={styles.linearGradientStyles}>
<View style={{ marginTop: '8%', alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 25, color: 'white', textAlign: 'center' }}>
{this.state.departmentName}
</Text>
</View>
</LinearGradient>
{/* User Icon */}
<View style={{ justifyContent: 'center', alignItems: 'center', marginTop: '55%' }}>
<View style={styles.userIcon}>
<Icon name="university" size={75} color="black" />
</View>
</View>
{/* Content */}
<ScrollView style={styles.overlayContentContainer}>
<View style={styles.overlayContentStyle}>
<Text style={styles.overlayContentStyleTitle}>
Email:
</Text>
<Text style={styles.overlayContentStyleContent}>
{this.state.departmentEmail}
</Text>
</View>
<View style={styles.overlayContentStyle}>
<Text style={styles.overlayContentStyleTitle}>
Contact Number:
</Text>
<Text style={styles.overlayContentStyleContent}>
{this.state.departmentHp}
</Text>
</View>
</ScrollView>
</Overlay>
{/* Overlay Screen END */}
<ScrollView>
{this.array.map((item) => {
return (
<TouchableOpacity
style={styles.item}
onPress={this.GetItem.bind(this, item.title)}
onLongPress={() => {
alert('Hi');
}}
>
<View style={styles.userIdIcon} >
<Icon name="university" size={37} color="white" />
</View>
<Text style={styles.itemTitle}>{item.title}</Text>
</TouchableOpacity>
)
})}
</ScrollView>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
studentContainer: {
flex: 1,
width: '100%',
height: '100%',
backgroundColor: '#32323d',
alignItems: 'center',
},
overallBackgroundImage: {
width: '100%',
height: '100%',
},
headerTitle: {
color: '#fff',
textAlign: 'center',
width: '100%'
},
headerTitleText: {
color: '#fff',
textAlign: 'center',
fontSize: 25,
fontWeight: 'bold'
},
backBtn: {
paddingLeft: 20,
width: 40,
color: '#fff'
},
addBtn: {
paddingRight: 20,
width: 40,
color: '#fff'
},
item: {
alignItems: 'center',
justifyContent: 'center',
padding: 10,
width: '95%',
borderWidth: 1,
borderRadius: 5,
borderColor: 'rgba(255,255,255,0.7)',
marginTop: 6,
marginBottom: 6,
marginLeft: '2.5%',
marginRight: '2.5%',
// flexDirection: 'row'
},
itemTitle: {
color: 'white',
fontSize: 20,
flex: 1,
textAlign: 'center',
padding: 5,
},
userIdIcon: {
padding: 5,
// borderWidth: 1,
// borderRadius: 60 / 2,
// borderColor: 'white',
marginLeft: 20,
marginRight: 20,
},
button: {
width: '90%',
padding: 10,
backgroundColor: 'white',
borderRadius: 5,
marginTop: 12,
marginBottom: 12
},
buttonText: {
color: '#32323d',
textAlign: 'center',
fontSize: 20,
},
linearGradientStyles: {
alignItems: 'center',
height: '35%',
width: '100%',
position: 'absolute',
borderTopLeftRadius: 10,
borderTopRightRadius: 10,
},
userIcon: {
backgroundColor: 'white',
width: 140,
height: 140,
borderRadius: 75,
justifyContent: 'center',
alignItems: 'center',
borderColor: '#ddd',
position: 'absolute',
borderBottomWidth: 0,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.30,
shadowRadius: 4.65,
elevation: 8,
},
overlayContentContainer: {
marginTop: '25%',
},
overlayContentStyle: {
backgroundColor: 'white',
width: '95%',
height: 'auto',
elevation: 1,
padding: 20,
borderRadius: 10,
margin: 10,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 6,
},
shadowOpacity: 0.37,
shadowRadius: 7.49,
elevation: 12,
},
overlayContentStyleTitle: {
textAlign: 'left',
fontWeight: 'bold',
fontSize: 18,
},
overlayContentStyleContent: {
textAlign: 'left',
},
});<file_sep>/images/index.js
const images = {
Student: require('./background/Student.jpg'),
Department: require('./background/Department.jpg'),
Events: require('./background/Events.jpg'),
Announcement: require('./background/Announcement.png'),
Library: require('./background/Programme.jpg'),
Timetable: require('./background/Timetable.jpg'),
};
export default images;<file_sep>/README.md
## Diploma-Software-Project-Complete-Version
The theme of this project is education system application this application there is a few functions. Which to help students get to
know more about the place where they study like college, univercity and so on. With this application everything will be as easy as
a single click. All the functions is simplify to the best condition where can bring students the best environment to enjoy their college
life.
## Function of this application
- Enroll subject
- Check timetable
- Check the posts
- Check the subjects
- Check the events
## Screen and design of Application
<p align="center">
This is the first screen of the application.
</p>
<p align="center">
<img src="https://github.com/Steve-Shar-9/Diploma-Software-Project-Complete-Version/blob/master/ss/Screenshot_20200304-220741.png" width="350" height="570" alt="accessibility text">
</p>
<p align="center">
This is when we want to log into the application.
</p>
<p align="center">
<img src="https://github.com/Steve-Shar-9/Diploma-Software-Project-Complete-Version/blob/master/ss/Screenshot_20200304-220358.png" width="350" height="570" alt="accessibility text">
</p>
<p align="center">
This is when we reach the home screen.
</p>
<p align="center">
<img src="https://github.com/Steve-Shar-9/Diploma-Software-Project-Complete-Version/blob/master/ss/Screenshot_20200304-220402.png" width="350" height="570" alt="accessibility text">
</p>
<p align="center">
This is when we scanning our fingerprint sensor to send the sensitive information.
</p>
<p align="center">
<img src="https://github.com/Steve-Shar-9/Diploma-Software-Project-Complete-Version/blob/master/ss/Screenshot_20200304-220411.png" width="350" height="570" alt="accessibility text">
</p>
<p align="center">
This is when we successfully verify.
</p>
<p align="center">
<img src="https://github.com/Steve-Shar-9/Diploma-Software-Project-Complete-Version/blob/master/ss/Screenshot_20200304-220415.png" width="350" height="570" alt="accessibility text">
</p>
<p align="center">
This is when we check the student at the admin screen.
</p>
<p align="center">
<img src="https://github.com/Steve-Shar-9/Diploma-Software-Project-Complete-Version/blob/master/ss/Screenshot_20200304-220529.png" width="350" height="570" alt="accessibility text">
</p>
<p align="center">
This is when we wanted to upload new photo the timetable screen.
</p>
<p align="center">
<img src="https://github.com/Steve-Shar-9/Diploma-Software-Project-Complete-Version/blob/master/ss/Screenshot_20200304-220534.png" width="350" height="570" alt="accessibility text">
</p>
<p align="center">
This is when we save the information.
</p>
<p align="center">
<img src="https://github.com/Steve-Shar-9/Diploma-Software-Project-Complete-Version/blob/master/ss/Screenshot_20200304-220425.png" width="350" height="570" alt="accessibility text">
</p>
<p align="center">
This is when we reach home screen of admin.
</p>
<p align="center">
<img src="https://github.com/Steve-Shar-9/Diploma-Software-Project-Complete-Version/blob/master/ss/Screenshot_20200304-220841.png" width="350" height="570" alt="accessibility text">
</p>
<file_sep>/screens/Admin/AdminAddDepartment.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, Alert, TouchableOpacity, TextInput, ImageBackground, ScrollView, KeyboardAvoidingView, BackHandler } from 'react-native';
import { StackActions, NavigationActions } from 'react-navigation';
import { Header } from 'react-native-elements';
import * as firebase from "firebase";
///////////////////// Setting up Firebase connection /////////////////////
// const config = {
// apiKey: "<KEY>",
// authDomain: "diploma-software-project.firebaseapp.com",
// databaseURL: "https://diploma-software-project.firebaseio.com",
// storageBucket: "diploma-software-project.appspot.com",
// messagingSenderId: "1092827450895"
// };
const config = {
apiKey: "<KEY>",
authDomain: "angelappfordatabase.firebaseapp.com",
databaseURL: "https://angelappfordatabase.firebaseio.com",
projectId: "angelappfordatabase",
storageBucket: "",
messagingSenderId: "758356549275"
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
///////////////////// Default class /////////////////////
export default class AdminAddDepartment extends Component {
static navigationOptions = {
// lock the drawer
drawerLockMode: "locked-closed"
};
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('AdminDepartment');
this.array = []
this.state.arrayHolder = []
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
state = {
// For entering new department data
departmentName: '',
departmentEmail: '',
departmentHp: '',
}
joinData = () => {
var departmentName = this.state.departmentName;
var departmentEmail = this.state.departmentEmail;
var departmentHp = this.state.departmentHp;
if (departmentName != '') {
if (departmentEmail != '') {
if (departmentHp != '') {
firebase.database().ref('Department/' + departmentName).set({
departmentEmail,
departmentHp,
})
Alert.alert('Department Registered Successfully !')
this.setState({
departmentName: '',
departmentEmail: '',
departmentHp: '',
})
// this.array = []
// this.state.arrayHolder = []
this.props.navigation.navigate('AdminDepartment');
} else {
Alert.alert("Please Enter Department Contact Number")
}
} else {
Alert.alert("Please Enter Department Email")
}
} else {
Alert.alert("Please Enter Department Name")
}
}
// Get the department information on selection
GetItem(item) {
Alert.alert(item);
}
render() {
return (
<KeyboardAvoidingView style={styles.departmentContainer} behavior='padding'>
<ImageBackground
source={require('../../images/background/Timetable1.jpg')}
style={styles.overallBackgroundImage}
blurRadius={50}
>
<Header
statusBarProps={{ barStyle: 'light-content' }}
placement="left"
centerComponent={<View style={styles.headerTitle}><Text style={styles.headerTitleText}>Register Department</Text></View>}
rightComponent={
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('AdminDepartment');
}}
>
<View style={[{ flexDirection: 'row' }]}>
<Text style={[{ color: '#fff', fontSize: 15 }]}>Cancel</Text>
</View>
</TouchableOpacity>}
containerStyle={{
backgroundColor: 'transparent',
justifyContent: 'space-around',
borderBottomColor: "transparent",
}}
/>
<ScrollView>
<View style={styles.newForm}>
<TextInput
defaultValue={this.state.departmentName}
placeholder="Name"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ departmentName: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.departmentEmail}
placeholder="Email"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ departmentEmail: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.departmentHp}
placeholder="Contact Number"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ departmentHp: data })}
style={styles.textInputStyle}
/>
<TouchableOpacity onPress={this.joinData} activeOpacity={0.7} style={styles.button} >
<Text style={styles.buttonText}> Add </Text>
</TouchableOpacity>
</View>
</ScrollView>
</ImageBackground>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
departmentContainer: {
flex: 1,
width: '100%',
height: '100%',
backgroundColor: '#32323d',
alignItems: 'center',
},
overallBackgroundImage: {
width: '100%',
height: '100%',
},
headerTitle: {
color: '#fff',
textAlign: 'center',
width: '100%'
},
headerTitleText: {
marginRight: -40,
color: '#fff',
textAlign: 'center',
fontSize: 25,
fontWeight: 'bold'
},
newForm: {
width: '100%',
alignItems: 'center',
},
textInputStyle: {
height: 55,
width: '90%',
borderBottomWidth: 1,
borderBottomColor: 'rgba(255,255,255,0.3)',
borderRadius: 5,
marginTop: 12,
fontSize: 20,
color: 'white'
},
button: {
width: '90%',
padding: 10,
backgroundColor: 'transparent',
borderWidth: 1,
borderColor: 'white',
borderRadius: 70 / 2,
marginTop: 15,
marginBottom: 12
},
buttonText: {
color: 'white',
textAlign: 'center',
fontSize: 20,
},
});<file_sep>/screens/Student/SideMenu.js
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { NavigationActions } from 'react-navigation';
import { ScrollView, StyleSheet, Text, View, TextInput, TouchableOpacity, AsyncStorage, ToastAndroid, ImageBackground, Image } from 'react-native';
import { Ionicons, SimpleLineIcons, Entypo, MaterialCommunityIcons, AntDesign } from '@expo/vector-icons';
import Icon from 'react-native-vector-icons/FontAwesome';
import { Overlay } from 'react-native-elements';
let interval;
import * as LocalAuthentication from 'expo-local-authentication'
class SideMenu extends Component {
componentDidMount() {
interval = setInterval(() => {
AsyncStorage.getItem('userName').then((value) => this.setState({ 'userName': value }))
}, 1000);
}
componentWillUnmount() {
clearInterval(interval);
}
navigateToScreen = (route) => () => {
const navigateAction = NavigationActions.navigate({
index: 0,
routeName: route
});
this.props.navigation.dispatch(navigateAction);
}
constructor(props) {
super(props)
this.state = {
color: 'rgba(255,255,255,0.2)',
color1: 'transparent',
color2: 'transparent',
color3: 'transparent',
colorEvent: 'transparent',
isVisible2: false,
userName: '',
}
AsyncStorage.getItem('userName').then((value) => this.setState({ 'userName': value }))
}
render() {
return (
<View style={{ backgroundColor: 'rgba(0,0,0,0.2)', height: '100%' }}>
<ImageBackground
style={styles.backgroundImage}
source={require('../../images/background/bg3.jpg')}
blurRadius={50}
>
<Overlay
isVisible={this.state.isVisible2}
onBackdropPress={() => this.setState({ isVisible2: false })}
windowBackgroundColor="rgba(0, 0, 0, 0.5)"
overlayBackgroundColor="transparent"
width="82%"
height="34%"
>
<View style={styles.container1}>
<View style={{ height: 45, width: '100%', backgroundColor: '#2e2e38', borderTopLeftRadius: 13, borderTopRightRadius: 13 }}>
<Text style={{ fontSize: 20, color: 'white', paddingLeft: 10, paddingTop: 9, textAlign: 'center' }}>Join Group / Class</Text>
</View>
<View style={styles.container2}>
<Text style={{ paddingBottom: 14 }}>Please ask for code if you don't have one.</Text>
<TextInput
style={{ height: 40, borderColor: '#2e2e38', borderWidth: 1, width: '100%', color: 'black', paddingLeft: 13, borderRadius: 13, }}
onChangeText={(text1) => this.setState({ text1 })}
value={this.state.text1}
placeholderTextColor='black'
placeholder='Code...'
/>
<View style={{ paddingTop: 13 }} />
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity style={styles.buttonForOverlay} onPress={this.submitCode}>
<Ionicons name="md-send" size={30} color="white" />
<Text style={{ color: 'black', textAlign: 'center', padding: 10 }}>Submit Code</Text>
</TouchableOpacity>
<View style={{ padding: 10 }}></View>
<TouchableOpacity
style={styles.buttonForOverlay}
onPress={this.QrScanner}
>
<AntDesign name="qrcode" size={30} color="white" />
<Text style={{ color: 'black', textAlign: 'center', padding: 10 }}>QR Scanner</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Overlay>
<ScrollView>
<View style={{ marginTop: 40, backgroundColor: 'transparent' }}>
<View style={styles.appsSection}>
<Image source={require('../../images/octo2.jpg')} style={{ height: 70, width: 70, borderRadius: 35, }} />
<Text style={styles.theIconTitles}>Turritopsis{'\n'}{this.state.userName}</Text>
</View>
{/* <View style={styles.userSection}>
<View style={styles.userIdIcon} >
<Icon name="user-circle" size={80} color='white' />
</View>
<Text style={styles.theTitles}>{this.state.userName}</Text>
</View> */}
<Text style={{ color: 'transparent', marginTop: 30, marginBottom: 8, color: 'white', fontSize: 20, marginLeft: 5 }}>
Main Section
</Text>
<TouchableOpacity style={{ width: '97%', backgroundColor: this.state.color, padding: 17, fontSize: 10, borderBottomRightRadius: 75, borderTopRightRadius: 75, flexDirection: 'row' }} onPress={() => { this.colourChangingFunction('color') }}>
<Entypo name="home" size={25} color="white" />
<Text style={{ color: 'white', fontSize: 15, marginLeft: 15 }}>
Home
</Text>
</TouchableOpacity>
<TouchableOpacity style={{ backgroundColor: this.state.colourGroup, padding: 17, fontSize: 10, borderBottomRightRadius: 75, borderTopRightRadius: 75, flexDirection: 'row' }} onPress={() => { this.popOutOrNot() }}>
<MaterialCommunityIcons name="account-group" size={25} color="white" />
<Text style={{ color: 'white', fontSize: 15, marginLeft: 15 }} >
Group / Class
</Text>
</TouchableOpacity>
</View>
<View style={{ backgroundColor: 'transparent' }}>
<Text style={{ color: 'transparent', marginTop: 20, marginBottom: 8, color: 'white', fontSize: 20, marginLeft: 5 }}>
Sub- Functions
</Text>
<TouchableOpacity style={{ width: '97%', backgroundColor: this.state.color1, padding: 17, fontSize: 10, borderBottomRightRadius: 75, borderTopRightRadius: 75, flexDirection: 'row' }} onPress={() => { this.colourChangingFunction('color1') }}>
<Entypo name="book" size={25} color="white" />
<Text style={{ color: 'white', fontSize: 15, marginLeft: 15 }}>
Subjects Enrollment
</Text>
</TouchableOpacity>
<TouchableOpacity style={{ width: '97%', backgroundColor: 'transparent', padding: 17, fontSize: 10, borderBottomRightRadius: 75, borderTopRightRadius: 75, flexDirection: 'row' }} onPress={() => { this.props.navigation.navigate('Timetable') }}>
<AntDesign name="calendar" size={25} color="white" />
<Text style={{ color: 'white', fontSize: 15, marginLeft: 15 }}>
Timetable Screen
</Text>
</TouchableOpacity>
<TouchableOpacity style={{ width: '97%', backgroundColor: this.state.colorEvent, padding: 17, fontSize: 10, borderBottomRightRadius: 75, borderTopRightRadius: 75, flexDirection: 'row' }} onPress={() => {
this.colourChangingFunction('eventScreen')
}}>
<MaterialCommunityIcons name="eventbrite" size={25} color="white" />
<Text style={{ color: 'white', fontSize: 15, marginLeft: 15 }}>
Events & Activities
</Text>
</TouchableOpacity>
{/* <TouchableOpacity style={{ width: '97%', backgroundColor: this.state.color2, padding: 17, fontSize: 10, borderBottomRightRadius: 75, borderTopRightRadius: 75, flexDirection: 'row' }} onPress={() => { this.colourChangingFunction('color2') }}>
<MaterialCommunityIcons name="google-controller" size={25} color="white" />
<Text style={{ color: 'white', fontSize: 15, marginLeft: 15 }}>
Testing Screen
</Text>
</TouchableOpacity> */}
<TouchableOpacity style={{ marginTop: 73, marginBottom: 10, marginLeft: 20, backgroundColor: 'transparent', flexDirection: 'row' }} onPress={() => {
async () => {
try {
await AsyncStorage.removeItem('userName');
console.log('userName deleted');
} catch (error) {
console.log(error);
}
try {
await AsyncStorage.removeItem('@SubEnroll:Sub');
console.log('SubEnroll deleted');
} catch (error) {
console.log(error);
}
try {
await AsyncStorage.removeItem('@GroupCode:key');
console.log('GroupCode deleted');
} catch (error) {
console.log(error);
}
}
AsyncStorage.setItem('userName', 'Logged Out');
this.colourChangingFunction('color')
this.props.navigation.navigate('Login');
}}>
<SimpleLineIcons name="logout" size={25} color="white" />
<Text style={{ color: 'white', fontSize: 20, marginLeft: 10 }}>
Logout</Text>
</TouchableOpacity>
</View>
</ScrollView>
</ImageBackground>
</View>
);
}
popOutOrNot = async () => {
this.colourChangingFunction('colorGroup');
try {
const value = await AsyncStorage.getItem('@GroupCode:key');
if (value !== null) {
this.props.navigation.navigate('InsideGroupOrClass', { data: value })
}
else {
this.setState({ isVisible2: true, colorGroup: 'transparent' })
}
} catch (error) {
}
}
QrScanner = () => {
this.setState({ isVisible2: false }, function () {
this.props.navigation.navigate('QRScanner');
});
}
//Submit and save the data to localStorage
submitCode = async () => {
if (this.state.text1 === '57212331') {
try {
await AsyncStorage.setItem('@GroupCode:key', this.state.text1);
console.log('saved to localStorage');
} catch (error) {
// Error saving data
console.log('error saving data to localStorage');
}
alert('Joined Successfully...');
this.props.navigation.navigate('InsideGroupOrClass', { data: this.state.text1 })
}
else {
alert('Failed to join...');
}
}
EnrollSubOrNot=async()=>{
const value = await AsyncStorage.getItem('@SubEnroll:Sub');
try {
if (value === null) {
this.props.navigation.navigate('SubEnrollment');
}
else {
// Adding for ios soon
// if (Platform.OS === 'ios') {
// alert(value);
// }
// else{
ToastAndroid.showWithGravityAndOffset(
value,
ToastAndroid.LONG,
ToastAndroid.CENTER,
25,
50,
);
// }
}
} catch (error) {
}
}
colourChangingFunction = (colouring) => {
if (colouring === 'color') {
this.setState({ color: 'rgba(255,255,255,0.2)', color1: 'transparent', color2: 'transparent', color3: 'transparent', colourGroup: 'transparent', colorEvent: 'transparent' }, () => { });
this.props.navigation.navigate('Home')
}
if (colouring === 'color1') {
this.setState({ color: 'transparent', color1: 'rgba(255,255,255,0.2)', color2: 'transparent', color3: 'transparent', colourGroup: 'transparent', colorEvent: 'transparent' }, () => { });
this.EnrollSubOrNot()
}
if (colouring === 'color2') {
this.setState({ color: 'transparent', color1: 'transparent', color2: 'rgba(255,255,255,0.2)', color3: 'transparent', colourGroup: 'transparent', colorEvent: 'transparent' }, () => { });
this.props.navigation.navigate('InputScreen')
}
if (colouring === 'color3') {
this.setState({ color: 'transparent', color1: 'transparent', color2: 'transparent', color3: 'rgba(255,255,255,0.2)', colourGroup: 'transparent', colorEvent: 'transparent' }, () => {
alert("Going to somewhere else");
});
}
if (colouring === 'colorGroup') {
this.setState({ color: 'transparent', color1: 'transparent', color2: 'transparent', color3: 'transparent', colourGroup: 'rgba(255,255,255,0.2)', colorEvent: 'transparent' }, () => {
});
}
if (colouring === 'eventScreen') {
this.setState({ color: 'transparent', color1: 'transparent', color2: 'transparent', color3: 'transparent', colourGroup: 'transparent', colorEvent: 'rgba(255,255,255,0.2)' }, () => {
this.props.navigation.navigate('EventScreen');
});
}
}
}
const styles = StyleSheet.create({
containerForSide: {
backgroundColor: 'transparent',
padding: 17,
fontSize: 10,
borderBottomRightRadius: 75,
borderTopRightRadius: 75,
},
container1: {
flex: 1,
backgroundColor: 'transparent',
alignItems: 'center',
justifyContent: 'center',
},
container2: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'white',
paddingTop: 8,
paddingLeft: 40,
paddingRight: 40,
paddingBottom: 40,
width: '100%',
height: '110%',
borderBottomLeftRadius: 13,
borderBottomRightRadius: 13,
},
buttonForOverlay: {
backgroundColor: '#2e2e38',
paddingTop: 3,
width: '35%',
height: 38,
textAlign: 'center',
alignItems: 'center',
borderRadius: 13,
},
backgroundImage: {
width: '100%',
height: '100%',
},
userSection: {
alignItems: 'center',
justifyContent: 'center',
},
appsSection: {
flexDirection: 'row',
justifyContent: 'center',
padding: 5,
paddingLeft: 20,
},
theIconTitles: {
color: 'white',
fontSize: 20,
fontStyle: 'italic',
flex: 1,
textAlign: 'auto',
padding: 15,
},
theTitles: {
color: 'white',
fontSize: 25,
flex: 1,
textAlign: 'auto',
padding: 20,
},
userIdIcon: {
alignItems: 'center',
justifyContent: 'center',
padding: 5,
width: 100,
height: 100,
borderWidth: 1,
borderRadius: 100 / 2,
borderColor: 'white',
},
appsIcon: {
alignItems: 'center',
justifyContent: 'center',
padding: 5,
width: 100,
height: 100,
borderWidth: 1,
borderRadius: 100 / 2,
borderColor: 'white',
},
});
SideMenu.propTypes = {
navigation: PropTypes.object
};
export default SideMenu;<file_sep>/screens/Admin/AdminAddStudent.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, Alert, TouchableOpacity, TextInput, ImageBackground, ScrollView, KeyboardAvoidingView, Picker, BackHandler } from 'react-native';
import { Header } from 'react-native-elements';
import * as firebase from "firebase";
const config = {
apiKey: "<KEY>",
authDomain: "angelappfordatabase.firebaseapp.com",
databaseURL: "https://angelappfordatabase.firebaseio.com",
projectId: "angelappfordatabase",
storageBucket: "",
messagingSenderId: "758356549275"
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
///////////////////// Password Base64 Encrytion /////////////////////
FormatFunctionAtob=(input)=>{
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = input;
let output = '';
for (let block = 0, charCode, i = 0, map = chars;
str.charAt(i | 0) || (map = '=', i % 1);
output += map.charAt(63 & block >> 8 - i % 1 * 8)) {
charCode = str.charCodeAt(i += 3 / 4);
if (charCode > 0xFF) {
throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
}
FormatFunctionBtoa=(input)=>{
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
}
///////////////////// Default class /////////////////////
export default class AdminAddStudent extends Component {
static navigationOptions = {
// lock the drawer
drawerLockMode: "locked-closed"
};
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('AdminStudent');
this.array = []
this.state.arrayHolder = []
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
constructor() {
super();
this.array = []
this.state = {
// Array for holding data from Firebase
arrayHolder: [],
StudentProgrammePickerSelectedVal: '',
// For entering new student data
studentId: '',
studentName: '',
studentIc: '',
studentPassword: '',
studentEmail: '',
studentGender: '',
studentNationality: '',
studentHp: '',
studentAdmissionDate: '',
studentProgramme: '',
studentAddress: '',
}
// Get the list of announcement from Firebase
firebase.database().ref('Programme/').on('value', (snapshot) => {
snapshot.forEach((child) => {
if (count === 0) {
this.setState({ studentProgramme: child.key })
}
this.array.push({ title: child.key });
this.setState({ arrayHolder: [...this.array] })
})
})
}
// Get the data from user's input from 'NEW' tab
joinData = () => {
var studentId = this.state.studentId;
var studentName = this.state.studentName;
var studentIc = this.state.studentIc;
var studentPassword = this.state.studentPassword;
var studentEmail = this.state.studentEmail;
var studentGender = this.state.studentGender;
var studentNationality = this.state.studentNationality;
var studentHp = this.state.studentHp;
var studentAdmissionDate = this.state.studentAdmissionDate;
var studentProgramme = this.state.studentProgramme;
var studentAddress = this.state.studentAddress;
if (studentId != '') {
if (studentName != '') {
if (studentIc != '') {
if (studentPassword != '') {
studentPassword = FormatFunctionAtob(studentPassword);
if (studentEmail != '') {
if (studentGender != '') {
if (studentNationality != '') {
if (studentHp != '') {
if (studentAdmissionDate != '') {
if (studentProgramme != '') {
if (studentAddress != '') {
firebase.database().ref('Student/' + studentId).set({
studentName,
studentIc,
studentPassword,
studentEmail,
studentGender,
studentNationality,
studentHp,
studentAdmissionDate,
studentProgramme,
studentAddress
})
Alert.alert('Student Registered Successfully !')
this.setState({
studentId: '',
studentName: '',
studentIc: '',
studentPassword: '',
studentEmail: '',
studentGender: '',
studentNationality: '',
studentHp: '',
studentAdmissionDate: '',
// studentProgramme: '',
studentAddress: '',})
// this.array = []
// this.state.arrayHolder = []
this.props.navigation.navigate('AdminStudent');
} else {
Alert.alert("Please Enter Address")
}
} else {
Alert.alert("Please Enter Programme")
}
} else {
Alert.alert("Please Enter Admission Date")
}
} else {
Alert.alert("Please Enter Contact Number")
}
} else {
Alert.alert("Please Enter Nationality")
}
} else {
Alert.alert("Please Enter Gender")
}
} else {
Alert.alert("Please Enter Email")
}
} else {
Alert.alert("Please Enter Password")
}
} else {
Alert.alert("Please Enter Identity Number")
}
} else {
Alert.alert("Please Enter Student Name")
}
} else {
Alert.alert("Please Enter Student ID")
}
}
// Get the student information on selection
GetItem(item) {
Alert.alert(item);
}
render() {
return (
<KeyboardAvoidingView style={styles.studentContainer} behavior='padding'>
<ImageBackground
source={require('../../images/background/Timetable1.jpg')}
style={styles.overallBackgroundImage}
blurRadius={50}
>
<Header
statusBarProps={{ barStyle: 'light-content' }}
placement="left"
centerComponent={<View style={styles.headerTitle}><Text style={styles.headerTitleText}>Register Student</Text></View>}
rightComponent={
<TouchableOpacity
onPress={() => {
// this.array = []
// this.state.arrayHolder = []
this.props.navigation.navigate('AdminStudent');
}}
>
<View style={[{ flexDirection: 'row' }]}>
<Text style={[{ color: '#fff', fontSize: 15 }]}>Cancel</Text>
</View>
</TouchableOpacity>}
containerStyle={{
backgroundColor: 'transparent',
justifyContent: 'space-around',
borderBottomColor: "transparent",
}}
/>
<ScrollView>
<View style={styles.newForm}>
<TextInput
defaultValue={this.state.studentId}
placeholder="Student ID"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentId: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.studentName}
placeholder="Name"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentName: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.studentIc}
placeholder="Identity Number"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentIc: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.studentPassword}
placeholder="<PASSWORD>"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentPassword: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.studentEmail}
placeholder="Email"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentEmail: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.studentGender}
placeholder="Gender"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentGender: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.studentNationality}
placeholder="Nationality"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentNationality: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.studentHp}
placeholder="Contact Number"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentHp: data })}
style={styles.textInputStyle}
/>
<TextInput
defaultValue={this.state.studentAdmissionDate}
placeholder="Admission Date"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentAdmissionDate: data })}
style={styles.textInputStyle}
/>
<Text style={styles.departmentTextStyle}>Select a Programme:</Text>
<Picker
selectedValue={this.state.studentProgramme}
style={styles.item}
itemStyle={{ backgroundColor: "transparent", color: "white", borderColor: 'rgba(255,255,255,0.3)', height: 50 }}
onValueChange={(itemValue, itemIndex) => this.setState({ studentProgramme: itemValue })} >
{this.array.map((item) => {
return (<Picker.Item label={item.title} value={item.title} />)
})}
</Picker>
<TextInput
defaultValue={this.state.studentAddress}
placeholder="Address"
placeholderTextColor={'rgba(255,255,255,0.3)'}
onChangeText={data => this.setState({ studentAddress: data })}
style={styles.textInputStyle}
/>
<TouchableOpacity onPress={this.joinData} activeOpacity={0.7} style={styles.button} >
<Text style={styles.buttonText}> Add </Text>
</TouchableOpacity>
</View>
</ScrollView>
</ImageBackground>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
studentContainer: {
flex: 1,
width: '100%',
height: '100%',
backgroundColor: '#32323d',
alignItems: 'center',
},
overallBackgroundImage: {
width: '100%',
height: '100%',
},
headerTitle: {
color: '#fff',
textAlign: 'center',
width: '100%'
},
headerTitleText: {
marginRight: -40,
color: '#fff',
textAlign: 'center',
fontSize: 25,
fontWeight: 'bold'
},
newForm: {
width: '100%',
alignItems: 'center',
},
textInputStyle: {
height: 55,
width: '90%',
borderBottomWidth: 1,
borderBottomColor: 'rgba(255,255,255,0.3)',
borderRadius: 5,
marginTop: 12,
fontSize: 20,
color: 'white'
},
departmentTextStyle: {
height: 55,
width: '90%',
marginTop: 12,
fontSize: 20,
color: 'white'
},
item: {
padding: 20,
fontSize: 18,
textAlign: 'center',
color: 'white',
width: '90%',
marginLeft: '5%',
marginBottom: 20
},
button: {
width: '90%',
padding: 10,
backgroundColor: 'transparent',
borderWidth: 1,
borderColor: 'white',
borderRadius: 70 / 2,
marginTop: 25,
marginBottom: 12
},
buttonText: {
color: 'white',
textAlign: 'center',
fontSize: 20,
},
});
|
62b85c0649714878dd5031169aabc25ae12bca95
|
[
"JavaScript",
"Markdown"
] | 13
|
JavaScript
|
Steve-Shar-9/Diploma-Software-Project-Complete-Version
|
2a9516b1f3ae92bb1be7b5014463177eb0a93637
|
2875bc4f1c80e477abcd2684d469032b1675fc54
|
refs/heads/master
|
<repo_name>laiiihz/android_demo_menu<file_sep>/app/src/main/java/tech/laihz/android_demo_menu/SettingsActivity.kt
package tech.laihz.android_demo_menu
import android.app.Activity
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_settings.*
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val mSharedPreferences=getSharedPreferences("setting", Context.MODE_PRIVATE)
val mEdit=mSharedPreferences.edit()
setTheme(mSharedPreferences.getInt("theme",R.style.AppTheme))
setContentView(R.layout.activity_settings)
val cbIsChecked=mSharedPreferences.getBoolean("checkboxCheck",false)
checkBox_night.isChecked=cbIsChecked
checkBox_night.setOnCheckedChangeListener { buttonView, isChecked ->
if(isChecked){
mEdit.putInt("theme",R.style.DarkTheme)
mEdit.putBoolean("checkboxCheck",true)
mEdit.apply()
}else {
mEdit.putInt("theme",R.style.AppTheme)
mEdit.putBoolean("checkboxCheck",false)
mEdit.apply()
}
}
button_recreate.setOnClickListener {
recreate()
}
}
}
<file_sep>/app/src/main/java/tech/laihz/android_demo_menu/MainActivity.kt
package tech.laihz.android_demo_menu
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.widget.PopupMenu
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var presentKey=0
var keyPressedCount=0
var isCheckedCB=false
val userSettings = getSharedPreferences("setting", Context.MODE_PRIVATE)
val editor = userSettings.edit()
editor.apply()
val themeMain=userSettings.getInt("theme",0)
setTheme(themeMain)
setContentView(R.layout.activity_main)
textViewContextMe.setOnLongClickListener {
textViewContextMe.showContextMenu()
}
textViewContextMe.setOnCreateContextMenuListener { menu, v, menuInfo ->
val popMenu=PopupMenu(this,v)
val menuGets=popMenu.menu
menuGets.add(Menu.NONE,0,0,"menu1")
var submenu=menuGets.addSubMenu("subMenu")
submenu.add(Menu.NONE,0,0,"sub1")
submenu.add(Menu.NONE,1,1,"sub2")
menuGets.add(Menu.NONE,1,1,"menu2")
popMenu.show()
}
button_dlg.setOnClickListener {
val ad:AlertDialog.Builder = AlertDialog.Builder(this)
ad.setTitle("Title")
ad.setMessage("this is a message")
ad.setNegativeButton("取消"){ _, _ ->}
ad.setPositiveButton("确定"){ _, _ ->}
ad.show()
}
textView_open.setOnLongClickListener {
textView_open.showContextMenu()
}
textView_open.setOnCreateContextMenuListener { _, v, _ ->
val popMenu=PopupMenu(this,v)
popMenu.inflate(R.menu.context_menu)
popMenu.show()
}
button_act_show.setOnClickListener {
supportActionBar?.show()
}
button_act_hide.setOnClickListener {
supportActionBar?.hide()
}
checkBox_ui.setOnCheckedChangeListener { _, isChecked ->
isCheckedCB = isChecked
}
et_input.setOnKeyListener { v, keyCode, event ->
if(!isCheckedCB){
if(event.action==KeyEvent.ACTION_DOWN){
tv_result.text=""
tv_result.append("keyCode:$keyCode\n")
tv_result.append("keyStatus:Down\n")
tv_result.append("keyPressedCount:$keyPressedCount\n")
}
if(event.action==KeyEvent.ACTION_UP){
if(keyCode!=presentKey){
presentKey=keyCode
keyPressedCount=0
}else{
keyPressedCount++
}
tv_result.text=""
tv_result.append("keyCode:$keyCode\n")
tv_result.append("keyStatus:UP\n")
tv_result.append("keyPressedCount:$keyPressedCount\n")
}
}
true
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu,menu)
// menu!!.add(0,0,0,"menuOne")
// menu.add(0,1,1,"menuTwo")
// menu.add(0,2,2,"menuThree")
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when(item?.itemId){
R.id.item_settings->{
val intent=Intent()
intent.setClass(this,SettingsActivity::class.java)
startActivity(intent)
true
}
else->super.onOptionsItemSelected(item)
}
}
}
|
ec78e9e1046bc28f391393ffef17e2ae0301fc91
|
[
"Kotlin"
] | 2
|
Kotlin
|
laiiihz/android_demo_menu
|
ee55bc77973c903a8b9279f69c40030209847273
|
f22acba01b0280c86b8a72ea2048c35f1dbcd008
|
refs/heads/master
|
<repo_name>ivokosir/language_poc<file_sep>/ivox/resolver.py
from typing import Dict, List
from error import error
from interpreter import Interpreter
from token import Token
import expr
import stmt
class Resolver:
def __init__(self, interpreter: Interpreter) -> None:
self.scopes: List[Dict[str, bool]] = []
self.in_function = False
self.interpreter = interpreter
def resolve(self, statements: List[stmt.Stmt]) -> None:
for statement in statements:
self.resolve_stmt(statement)
def resolve_stmt(self, statement: stmt.Stmt) -> None:
if isinstance(statement, stmt.Expression):
self.resolve_expression(statement)
if isinstance(statement, stmt.Print):
self.resolve_print(statement)
if isinstance(statement, stmt.Var):
self.resolve_var(statement)
if isinstance(statement, stmt.Block):
self.resolve_block(statement)
if isinstance(statement, stmt.If):
self.resolve_if(statement)
if isinstance(statement, stmt.While):
self.resolve_while(statement)
if isinstance(statement, stmt.Function):
self.resolve_function(statement)
if isinstance(statement, stmt.Return):
self.resolve_return(statement)
def resolve_expression(self, statement: stmt.Expression) -> None:
self.resolve_expr(statement.expr)
def resolve_print(self, statement: stmt.Print) -> None:
self.resolve_expr(statement.expr)
def resolve_var(self, statement: stmt.Var) -> None:
self.declare(statement.name)
self.resolve_expr(statement.initializer)
self.define(statement.name)
def resolve_block(self, statement: stmt.Block) -> None:
self.begin_scope()
self.resolve(statement.statements)
self.end_scope()
def resolve_if(self, statement: stmt.If) -> None:
self.resolve_expr(statement.condition)
self.resolve_stmt(statement.then_branch)
if statement.else_branch:
self.resolve_stmt(statement.else_branch)
def resolve_while(self, statement: stmt.While) -> None:
self.resolve_expr(statement.condition)
self.resolve_stmt(statement.body)
def resolve_function(self, statement: stmt.Function) -> None:
was_in_function = self.in_function
self.in_function = True
self.declare(statement.name)
self.define(statement.name)
self.begin_scope()
for param in statement.params:
self.declare(param)
self.define(param)
self.resolve(statement.body)
self.end_scope()
self.in_function = was_in_function
def resolve_return(self, statement: stmt.Return) -> None:
if self.in_function:
self.resolve_expr(statement.value)
else:
error(statement.keyword, "Cannot return from top-level code.")
def resolve_expr(self, expression: expr.Expr) -> None:
if isinstance(expression, expr.Binary):
self.resolve_binary(expression)
if isinstance(expression, expr.Unary):
self.resolve_unary(expression)
if isinstance(expression, expr.Grouping):
self.resolve_grouping(expression)
if isinstance(expression, expr.Logical):
self.resolve_logical(expression)
if isinstance(expression, expr.Literal):
self.resolve_literal(expression)
if isinstance(expression, expr.Variable):
self.resolve_variable(expression)
if isinstance(expression, expr.Assign):
self.resolve_assign(expression)
if isinstance(expression, expr.Call):
self.resolve_call(expression)
if isinstance(expression, expr.Object):
self.resolve_object(expression)
if isinstance(expression, expr.Get):
self.resolve_get(expression)
if isinstance(expression, expr.Set):
self.resolve_set(expression)
def resolve_binary(self, expression: expr.Binary) -> None:
self.resolve_expr(expression.left)
self.resolve_expr(expression.right)
def resolve_unary(self, expression: expr.Unary) -> None:
self.resolve_expr(expression.right)
def resolve_grouping(self, expression: expr.Grouping) -> None:
self.resolve_expr(expression.expression)
def resolve_logical(self, expression: expr.Logical) -> None:
self.resolve_expr(expression.left)
self.resolve_expr(expression.right)
def resolve_literal(self, expression: expr.Literal) -> None:
pass
def resolve_variable(self, expression: expr.Variable) -> None:
if self.scopes and self.scopes[-1].get(expression.name.lexeme) == False:
error(expression.name, "Cannot read local variable in its own initializer.")
self.resolve_local(expression, expression.name)
def resolve_assign(self, expression: expr.Assign) -> None:
self.resolve_expr(expression.value)
self.resolve_local(expression, expression.name)
def resolve_call(self, expression: expr.Call) -> None:
self.resolve_expr(expression.callee)
for argument in expression.arguments:
self.resolve_expr(argument)
def resolve_object(self, expression: expr.Object) -> None:
used_names: List[str] = []
for name, field in expression.fields.items():
if name.lexeme in used_names:
error(name, "Field with this name is already in object.")
used_names.append(name.lexeme)
self.resolve_expr(field)
def resolve_get(self, expression: expr.Get) -> None:
self.resolve_expr(expression.object)
def resolve_set(self, expression: expr.Set) -> None:
self.resolve_expr(expression.object)
self.resolve_expr(expression.value)
def begin_scope(self) -> None:
self.scopes.append(dict())
def end_scope(self) -> None:
self.scopes.pop()
def declare(self, name: Token) -> None:
if self.scopes:
scope = self.scopes[-1]
if name.lexeme in scope:
error(name, "Variable with this name already declared in this scope.")
scope[name.lexeme] = False
def define(self, name: Token) -> None:
if self.scopes:
scope = self.scopes[-1]
scope[name.lexeme] = True
def resolve_local(self, expression: expr.Expr, name: Token) -> None:
for i, scope in reversed(list(enumerate(self.scopes))):
if name.lexeme in scope:
self.interpreter.resolve(expression, i)
<file_sep>/ivox/parser.py
"""
program → declaration* EOF ;
declaration → funDecl
| varDecl
| statement ;
funDecl → "fun" function ;
function → IDENTIFIER "(" parameters? ")" block ;
parameters → IDENTIFIER ( "," IDENTIFIER )* ;
statement → exprStmt
| ifStmt
| returnStmt
| printStmt
| whileStmt
| forStmt
| block ;
varDecl → "var" IDENTIFIER ( "=" expression )? ";" ;
exprStmt → expression ";" ;
ifStmt → "if" "(" expression ")" statement ( "else" statement )? ;
returnStmt → "return" expression? ";" ;
printStmt → "print" expression ";" ;
whileStmt → "while" "(" expression ")" statement ;
forStmt → "for" "(" ( varDecl | exprStmt | ";" )
expression? ";"
expression? ")" statement ;
block → "{" declaration* "}" ;
expression → assignment ;
assignment → ( call "." )? IDENTIFIER "=" assignment
| logic_or ;
logic_or → logic_and ( "or" logic_and )* ;
logic_and → equality ( "and" equality )* ;
equality → comparison ( ( "!=" | "==" ) comparison )* ;
comparison → addition ( ( ">" | ">=" | "<" | "<=" ) addition )* ;
addition → multiplication ( ( "-" | "+" ) multiplication )* ;
multiplication → unary ( ( "/" | "*" ) unary )* ;
unary → ( "!" | "-" ) unary | call ;
call → primary ( "(" arguments? ")" | "." IDENTIFIER )* ;
arguments → expression ( "," expression )* ;
primary → "true" | "false" | "nil"
| NUMBER | STRING
| "(" expression ")"
| "object" "{" fields? "}"
| IDENTIFIER ;
fields → IDENTIFIER "=" expression ( "," IDENTIFIER "=" expression )* ;
"""
from typing import Dict, List, NoReturn
import sys
from token import Token
from literal import Literal
import expr
import stmt
import error
class Parser:
def __init__(self, tokens: List[Token]) -> None:
self.tokens = tokens
self.current = 0
def parse(self) -> List[stmt.Stmt]:
statements: List[stmt.Stmt] = []
while not self.is_at_end():
statements.append(self.declaration())
return statements
def declaration(self) -> stmt.Stmt:
if self.match(Token.Type.FUN):
return self.function()
if self.match(Token.Type.VAR):
return self.var_declaration()
else:
return self.statement()
def function(self) -> stmt.Stmt:
name = self.consume(Token.Type.IDENTIFIER, "Expect function name.")
self.consume(Token.Type.LEFT_PAREN, "Expect '(' after function name.")
parameters: List[Token] = []
if not self.check(Token.Type.RIGHT_PAREN):
while True:
if len(parameters) >= 255:
self.error(self.peek(), "Cannot have more than 255 parameters.")
parameter = self.consume(Token.Type.IDENTIFIER, "Expect parameter name.")
parameters.append(parameter)
if not self.match(Token.Type.COMMA):
break
self.consume(Token.Type.RIGHT_PAREN, "Expect ')' after parameters.")
self.consume(Token.Type.LEFT_BRACE, "Expect '{' before function body.");
body = self.block().statements
return stmt.Function(name, parameters, body)
def var_declaration(self) -> stmt.Stmt:
name = self.consume(Token.Type.IDENTIFIER, "Expect variable name.")
if self.match(Token.Type.EQUAL):
initializer = self.expression()
else:
initializer = expr.Literal(None)
self.consume(Token.Type.SEMICOLON, "Expect ';' after variable declaration.")
return stmt.Var(name, initializer)
def statement(self) -> stmt.Stmt:
if self.match(Token.Type.IF):
return self.if_statement()
if self.match(Token.Type.WHILE):
return self.while_statement()
if self.match(Token.Type.FOR):
return self.for_statement()
if self.match(Token.Type.RETURN):
return self.return_statement()
if self.match(Token.Type.PRINT):
return self.print_statement()
if self.match(Token.Type.LEFT_BRACE):
return self.block()
else:
return self.expression_statement()
def if_statement(self) -> stmt.Stmt:
self.consume(Token.Type.LEFT_PAREN, "Expect '(' after if statement.")
condition = self.expression()
self.consume(Token.Type.RIGHT_PAREN, "Expect ')' after if condition.")
then_branch = self.statement()
else_branch = None
if self.match(Token.Type.ELSE):
else_branch = self.statement()
return stmt.If(condition, then_branch, else_branch)
def while_statement(self) -> stmt.Stmt:
self.consume(Token.Type.LEFT_PAREN, "Expect '(' after while statement.")
condition = self.expression()
self.consume(Token.Type.RIGHT_PAREN, "Expect ')' after while condition.")
body = self.statement()
return stmt.While(condition, body)
def for_statement(self) -> stmt.Stmt:
self.consume(Token.Type.LEFT_PAREN, "Expect '(' after for statement.")
if self.match(Token.Type.SEMICOLON):
initializer = None
elif self.match(Token.Type.VAR):
initializer = self.var_declaration()
else:
initializer = self.expression_statement()
if self.check(Token.Type.SEMICOLON):
condition = None
else:
condition = self.expression()
self.consume(Token.Type.SEMICOLON, "Expect ';' after loop condition.")
if self.check(Token.Type.RIGHT_PAREN):
increment = None
else:
increment = self.expression()
self.consume(Token.Type.RIGHT_PAREN, "Expect ')' after for clauses.")
body = self.statement()
if increment:
body = stmt.Block([body, stmt.Expression(increment)])
if not condition:
condition = expr.Literal(True)
body = stmt.While(condition, body)
if initializer:
body = stmt.Block([initializer, body])
return body
def return_statement(self) -> stmt.Stmt:
keyword = self.previous()
value: expr.Expr = expr.Literal(None)
if not self.check(Token.Type.SEMICOLON):
value = self.expression()
self.consume(Token.Type.SEMICOLON, "Expect ';' after return statement.")
return stmt.Return(keyword, value)
def print_statement(self) -> stmt.Stmt:
expression = self.expression()
self.consume(Token.Type.SEMICOLON, "Expect ';' after print statement.")
return stmt.Print(expression)
def block(self) -> stmt.Block:
statements: List[stmt.Stmt] = []
while not self.check(Token.Type.RIGHT_BRACE) and not self.is_at_end():
statements.append(self.declaration())
self.consume(Token.Type.RIGHT_BRACE, "Expect '}' after block.")
return stmt.Block(statements)
def expression_statement(self) -> stmt.Stmt:
expression = self.expression()
self.consume(Token.Type.SEMICOLON, "Expect ';' after expression.")
return stmt.Expression(expression)
def error(self, token: Token, message: str) -> NoReturn:
error.error(token, message)
sys.exit(1)
def consume(self, type: Token.Type, message: str) -> Token:
if self.check(type):
return self.advance()
self.error(self.peek(), message)
def is_at_end(self) -> bool:
return self.peek().type == Token.Type.EOF
def peek(self) -> Token:
return self.tokens[self.current]
def previous(self) -> Token:
return self.tokens[self.current - 1]
def advance(self) -> Token:
if not self.is_at_end():
self.current += 1
return self.previous()
def check(self, type: Token.Type) -> bool:
if self.is_at_end():
return False
return self.peek().type == type
def match(self, *types: Token.Type) -> bool:
for type in types:
if self.check(type):
self.advance()
return True
return False
def object(self) -> expr.Expr:
self.consume(Token.Type.LEFT_BRACE, "Expect '{' after object keyword.")
fields: Dict[Token, expr.Expr] = dict()
if not self.check(Token.Type.RIGHT_BRACE):
while True:
name = self.consume(Token.Type.IDENTIFIER, "Expect field name.")
self.consume(Token.Type.EQUAL, "Expect '=' after field name.")
expression = self.expression()
fields[name] = expression
if not self.match(Token.Type.COMMA):
break
self.consume(Token.Type.RIGHT_BRACE, "Expect '}' after object fields.")
return expr.Object(fields)
def primary(self) -> expr.Expr:
if self.match(Token.Type.FALSE): return expr.Literal(False)
if self.match(Token.Type.TRUE): return expr.Literal(True)
if self.match(Token.Type.NIL): return expr.Literal(None)
if self.match(Token.Type.NUMBER, Token.Type.STRING):
return expr.Literal(self.previous().literal)
if self.match(Token.Type.LEFT_PAREN):
expression = self.expression()
self.consume(Token.Type.RIGHT_PAREN, "Expect ')' after expression.")
return expr.Grouping(expression)
if self.match(Token.Type.IDENTIFIER):
return expr.Variable(self.previous())
if self.match(Token.Type.OBJECT):
return self.object()
self.error(self.peek(), "Expect expression.")
def finish_call(self, callee: expr.Expr) -> expr.Expr:
arguments: List[expr.Expr] = []
if not self.check(Token.Type.RIGHT_PAREN):
while True:
if len(arguments) >= 255:
self.error(self.peek(), "Cannot have more than 255 arguments.")
arguments.append(self.expression())
if not self.match(Token.Type.COMMA):
break
paren = self.consume(Token.Type.RIGHT_PAREN, "Expect ')' after arguments.")
return expr.Call(callee, paren, arguments)
def call(self) -> expr.Expr:
expression = self.primary()
while True:
if self.match(Token.Type.LEFT_PAREN):
expression = self.finish_call(expression)
elif self.match(Token.Type.DOT):
name = self.consume(Token.Type.IDENTIFIER, "Expect property name after '.'.")
expression = expr.Get(expression, name)
else:
break;
return expression
def unary(self) -> expr.Expr:
if self.match(Token.Type.BANG, Token.Type.MINUS):
operator = self.previous()
right = self.unary()
return expr.Unary(operator, right)
return self.call()
def multiplication(self) -> expr.Expr:
expression = self.unary()
while self.match(Token.Type.SLASH, Token.Type.STAR):
operator = self.previous()
right = self.unary()
expression = expr.Binary(expression, operator, right)
return expression
def addition(self) -> expr.Expr:
expression = self.multiplication()
while self.match(Token.Type.MINUS, Token.Type.PLUS):
operator = self.previous()
right = self.multiplication()
expression = expr.Binary(expression, operator, right)
return expression
def comparison(self) -> expr.Expr:
expression = self.addition()
while self.match(Token.Type.GREATER, Token.Type.GREATER_EQUAL, Token.Type.LESS, Token.Type.LESS_EQUAL):
operator = self.previous()
right = self.addition()
expression = expr.Binary(expression, operator, right)
return expression
def equality(self) -> expr.Expr:
expression = self.comparison()
while self.match(Token.Type.BANG_EQUAL, Token.Type.EQUAL_EQUAL):
operator = self.previous()
right = self.comparison()
expression = expr.Binary(expression, operator, right)
return expression
def and_(self) -> expr.Expr:
expression = self.equality()
while self.match(Token.Type.AND):
operator = self.previous()
right = self.equality()
expression = expr.Logical(expression, operator, right)
return expression
def or_(self) -> expr.Expr:
expression = self.and_()
while self.match(Token.Type.OR):
operator = self.previous()
right = self.and_()
expression = expr.Logical(expression, operator, right)
return expression
def assignment(self) -> expr.Expr:
expression = self.or_()
if self.match(Token.Type.EQUAL):
equals = self.previous()
value = self.assignment()
if isinstance(expression, expr.Variable):
name = expression.name
return expr.Assign(name, value)
if isinstance(expression, expr.Get):
return expr.Set(expression.object, expression.name, value)
else:
self.error(equals, "Invalid assignment target.")
return expression
def expression(self) -> expr.Expr:
return self.assignment()
<file_sep>/ivox/error.py
from token import Token
hadError = False
def error(token: Token, message: str) -> None:
if token.type == Token.Type.EOF:
report(token.line, " at end", message)
else:
report(token.line, f" at '{token.lexeme}'", message)
def report(line: int, where: str, message: str) -> None:
print(f"[line {line}] Error{where}: {message}")
global hadError
hadError = True
<file_sep>/ivox/scanner.py
from typing import List, NoReturn, Optional, Tuple
import re
import sys
from error import report
from token import Token
OPERATORS = {
'(': Token.Type.LEFT_PAREN,
')': Token.Type.RIGHT_PAREN,
'{': Token.Type.LEFT_BRACE,
'}': Token.Type.RIGHT_BRACE,
',': Token.Type.COMMA,
'.': Token.Type.DOT,
'-': Token.Type.MINUS,
'+': Token.Type.PLUS,
';': Token.Type.SEMICOLON,
'/': Token.Type.SLASH,
'*': Token.Type.STAR,
'!=': Token.Type.BANG_EQUAL,
'!': Token.Type.BANG,
'==': Token.Type.EQUAL_EQUAL,
'=': Token.Type.EQUAL,
'>=': Token.Type.GREATER_EQUAL,
'>': Token.Type.GREATER,
'<=': Token.Type.LESS_EQUAL,
'<': Token.Type.LESS,
}
KEYWORDS = {
'and': Token.Type.AND,
'class': Token.Type.CLASS,
'else': Token.Type.ELSE,
'false': Token.Type.FALSE,
'fun': Token.Type.FUN,
'for': Token.Type.FOR,
'if': Token.Type.IF,
'nil': Token.Type.NIL,
'or': Token.Type.OR,
'print': Token.Type.PRINT,
'return': Token.Type.RETURN,
'super': Token.Type.SUPER,
'this': Token.Type.THIS,
'true': Token.Type.TRUE,
'var': Token.Type.VAR,
'while': Token.Type.WHILE,
'object': Token.Type.OBJECT,
}
def error(char: str, line: int) -> NoReturn:
report(line, '', f"Unexpected {char}.")
sys.exit(1)
def scan_regex(regex: str, chars: str) -> Tuple[Optional[str], str]:
m = re.match(regex, chars)
if m:
return (m.group(0), chars[m.end():])
else:
return (None, chars)
def scan_(chars: str, line: int) -> List[Token]:
if not chars:
return [Token(Token.Type.EOF, '', line)]
if chars[0] == '\n':
return scan_(chars[1:], line + 1)
empty, chars = scan_regex(r'\s', chars)
if empty:
return scan_(chars, line)
for operator, type in OPERATORS.items():
if chars.startswith(operator):
return [Token(type, operator, line)] + scan_(chars[len(operator):], line)
number, chars = scan_regex(r'-?\d+', chars)
if number:
return [Token(Token.Type.NUMBER, number, line, int(number))] + scan_(chars, line)
identifier, chars = scan_regex(r'[^\W\d]\w*', chars)
if identifier:
for keyword, type in KEYWORDS.items():
if keyword == identifier:
return [Token(type, keyword, line)] + scan_(chars, line)
return [Token(Token.Type.IDENTIFIER, identifier, line)] + scan_(chars, line)
string, chars = scan_regex(r'"[^"]*"', chars)
if string:
value = string[1:-1]
return [Token(Token.Type.STRING, string, line, value)] + scan_(chars, line)
error(chars[0], line)
def scan(source: str) -> List[Token]:
return scan_(source, 1)
<file_sep>/ivox/literal.py
from typing import Callable, Dict, List, Union
Literal = Union[int, str, None, 'Function', 'Object']
class Function:
def __init__(self, call: Callable[[List[Literal]], Literal], arity: int) -> None:
self.call = call
self.arity = arity
def __repr__(self) -> str:
return f"function({self.arity})"
class Object:
def __init__(self, fields: Dict[str, Literal]):
self.fields = fields
def __repr__(self) -> str:
field_strings = [f"{name} = {e}" for (name, e) in self.fields.items()]
return f"object {{ {' , '.join(field_strings)} }}"
<file_sep>/ivox/ivox.py
from interpreter import Interpreter
from parser import Parser
from resolver import Resolver
import error
import scanner
def compile(source: str) -> None:
tokens = scanner.scan(source)
parser = Parser(tokens)
statements = parser.parse()
interpreter = Interpreter()
resolver = Resolver(interpreter)
print(statements)
resolver.resolve(statements)
if not error.hadError:
interpreter.interpret(statements)
with open('tests/int.ivox') as f:
source = f.read()
compile(source)
<file_sep>/ivox/environment.py
from typing import Dict, Optional
from literal import Literal
from token import Token
class Environment:
def __init__(self, enclosing: Optional['Environment'] = None) -> None:
self.enclosing = enclosing
self.values: Dict[str, Literal] = dict()
def define(self, name: str, value: Literal) -> None:
self.values[name] = value
def get(self, name: Token) -> Literal:
if name.lexeme in self.values:
return self.values[name.lexeme]
if self.enclosing:
return self.enclosing.get(name)
raise ValueError(f"Undefined variable '{name.lexeme}'")
def assign(self, name: Token, value: Literal) -> None:
if name.lexeme in self.values:
self.values[name.lexeme] = value
elif self.enclosing:
self.enclosing.assign(name, value)
else:
raise ValueError(f"Undefined variable '{name.lexeme}'")
def getAt(self, distance: int, name: str) -> Literal:
return self.ancestor(distance).values[name]
def assignAt(self, distance: int, name: Token, value: Literal) -> None:
self.ancestor(distance).values[name.lexeme] = value
def ancestor(self, distance: int) -> 'Environment':
environment = self
for i in range(distance):
if environment.enclosing:
environment = environment.enclosing
return environment
<file_sep>/ivox/interpreter.py
from typing import Dict, List, NoReturn
import time
from environment import Environment
from literal import Literal, Function, Object
from token import Token
import expr
import stmt
class Return(Exception):
def __init__(self, value: Literal):
self.value = value
class Interpreter:
def __init__(self) -> None:
self.environment = Environment()
self.locals: Dict[expr.Expr, int] = dict()
self.globals = self.environment
def clock(args: List[Literal]) -> Literal:
return round(time.time())
self.environment.define('clock', Function(clock, 0))
def interpret(self, statements: List[stmt.Stmt]) -> None:
for stmt in statements:
self.execute(stmt)
def executeExpressionStmt(self, stmt: stmt.Expression) -> None:
self.evaluate(stmt.expr)
def executePrintStmt(self, stmt: stmt.Print) -> None:
value = self.evaluate(stmt.expr)
print(value)
def executeReturnStmt(self, stmt: stmt.Return) -> NoReturn:
value = self.evaluate(stmt.value)
raise Return(value)
def executeBlockStmt(self, stmt: stmt.Block) -> None:
previous = self.environment
self.environment = Environment(previous)
for statement in stmt.statements:
self.execute(statement)
self.environment = previous
def executeVarStmt(self, stmt: stmt.Var) -> None:
value = self.evaluate(stmt.initializer)
self.environment.define(stmt.name.lexeme, value)
def executeFunctionStmt(self, stmt: stmt.Function) -> None:
parent = self.environment
def call(args: List[Literal]) -> Literal:
previous = self.environment
self.environment = parent
for param, arg in zip(stmt.params, args):
self.environment.define(param.lexeme, arg)
value: Literal = None
try:
for statement in stmt.body:
self.execute(statement)
except Return as r:
value = r.value
self.environment = previous
return value
function = Function(call, len(stmt.params))
self.environment.define(stmt.name.lexeme, function)
def executeIfStmt(self, stmt: stmt.If) -> None:
if self.isTruthy(self.evaluate(stmt.condition)):
self.execute(stmt.then_branch);
elif stmt.else_branch:
self.execute(stmt.else_branch)
def executeWhileStmt(self, stmt: stmt.While) -> None:
while self.isTruthy(self.evaluate(stmt.condition)):
self.execute(stmt.body);
def isEqual(self, left: Literal, right: Literal) -> bool:
return left == right
def isTruthy(self, literal: Literal) -> bool:
if literal == None or literal == False:
return False
else:
return True
def evaluateBinary(self, expr: expr.Binary) -> Literal:
left = self.evaluate(expr.left)
right = self.evaluate(expr.right)
if expr.operator.type == Token.Type.MINUS:
if isinstance(left, int) and isinstance(right, int):
return left - right
elif expr.operator.type == Token.Type.SLASH:
if isinstance(left, int) and isinstance(right, int):
return left // right
elif expr.operator.type == Token.Type.STAR:
if isinstance(left, int) and isinstance(right, int):
return left * right
elif expr.operator.type == Token.Type.PLUS:
if isinstance(left, int) and isinstance(right, int):
return left + right
if isinstance(left, str) and isinstance(right, str):
return left + right
elif expr.operator.type == Token.Type.GREATER:
if isinstance(left, int) and isinstance(right, int):
return left > right
elif expr.operator.type == Token.Type.GREATER_EQUAL:
if isinstance(left, int) and isinstance(right, int):
return left >= right
elif expr.operator.type == Token.Type.LESS:
if isinstance(left, int) and isinstance(right, int):
return left < right
elif expr.operator.type == Token.Type.LESS_EQUAL:
if isinstance(left, int) and isinstance(right, int):
return left <= right
elif expr.operator.type == Token.Type.EQUAL_EQUAL:
return self.isEqual(left, right)
elif expr.operator.type == Token.Type.BANG_EQUAL:
return not self.isEqual(left, right)
raise ValueError("Unexpected types")
def evaluateLogical(self, expr: expr.Logical) -> Literal:
left = self.evaluate(expr.left)
if expr.operator.type == Token.Type.OR:
if self.isTruthy(left):
return left
else:
if not self.isTruthy(left):
return left
return self.evaluate(expr.right)
def evaluateUnary(self, expr: expr.Unary) -> Literal:
right = self.evaluate(expr.right)
if expr.operator.type == Token.Type.MINUS:
if isinstance(right, int):
return -right
elif expr.operator.type == Token.Type.BANG:
return not self.isTruthy(right)
raise ValueError("Unexpected type")
def evaluateGrouping(self, expr: expr.Grouping) -> Literal:
return self.evaluate(expr.expression)
def evaluateLiteral(self, expr: expr.Literal) -> Literal:
return expr.value
def evaluateVariable(self, expr: expr.Variable) -> Literal:
return self.lookUpVariable(expr.name, expr)
def evaluateAssign(self, expr: expr.Assign) -> Literal:
value = self.evaluate(expr.value)
distance = self.locals.get(expr)
if distance:
self.environment.assignAt(distance, expr.name, value)
else:
self.globals.assign(expr.name, value)
return value
def evaluateCall(self, expr: expr.Call) -> Literal:
callee = self.evaluate(expr.callee)
arguments = [self.evaluate(argument) for argument in expr.arguments]
if isinstance(callee, Function):
if len(arguments) == callee.arity:
return callee.call(arguments)
else:
raise ValueError(f"Expected {callee.arity} arguments, but got {len(arguments)}.")
else:
raise ValueError("Can only call functions.")
def evaluateObject(self, expr: expr.Object) -> Literal:
fields = {name.lexeme: self.evaluate(expression) for name, expression in expr.fields.items()}
return Object(fields)
def evaluateGet(self, expr: expr.Get) -> Literal:
object = self.evaluate(expr.object)
name = expr.name.lexeme
if isinstance(object, Object):
if name in object.fields:
return object.fields[name]
else:
raise ValueError(f"Object does not have property {name}.")
else:
raise ValueError(f"Cannot get property of an non object value.")
def evaluateSet(self, expr: expr.Set) -> Literal:
object = self.evaluate(expr.object)
name = expr.name.lexeme
if isinstance(object, Object):
value = self.evaluate(expr.value)
object.fields[name] = value
return value
else:
raise ValueError(f"Cannot set property of an non object value.")
def evaluate(self, expression: expr.Expr) -> Literal:
if isinstance(expression, expr.Binary):
return self.evaluateBinary(expression)
if isinstance(expression, expr.Logical):
return self.evaluateLogical(expression)
if isinstance(expression, expr.Grouping):
return self.evaluateGrouping(expression)
if isinstance(expression, expr.Literal):
return self.evaluateLiteral(expression)
if isinstance(expression, expr.Unary):
return self.evaluateUnary(expression)
if isinstance(expression, expr.Variable):
return self.evaluateVariable(expression)
if isinstance(expression, expr.Assign):
return self.evaluateAssign(expression)
if isinstance(expression, expr.Call):
return self.evaluateCall(expression)
if isinstance(expression, expr.Object):
return self.evaluateObject(expression)
if isinstance(expression, expr.Get):
return self.evaluateGet(expression)
if isinstance(expression, expr.Set):
return self.evaluateSet(expression)
def execute(self, statement: stmt.Stmt) -> None:
if isinstance(statement, stmt.Expression):
self.executeExpressionStmt(statement)
if isinstance(statement, stmt.Print):
self.executePrintStmt(statement)
if isinstance(statement, stmt.Return):
self.executeReturnStmt(statement)
if isinstance(statement, stmt.Block):
self.executeBlockStmt(statement)
if isinstance(statement, stmt.Var):
self.executeVarStmt(statement)
if isinstance(statement, stmt.Function):
self.executeFunctionStmt(statement)
if isinstance(statement, stmt.If):
self.executeIfStmt(statement)
if isinstance(statement, stmt.While):
self.executeWhileStmt(statement)
def resolve(self, expression: expr.Expr, depth: int) -> None:
self.locals[expression] = depth
def lookUpVariable(self, name: Token, expression: expr.Expr) -> Literal:
if expression in self.locals:
distance = self.locals[expression]
return self.environment.getAt(distance, name.lexeme)
else:
return self.globals.get(name)
<file_sep>/ivox/stmt.py
from typing import List, Optional, Union
from expr import Expr
from token import Token
Stmt = Union['Expression', 'Print', 'Var', 'Block', 'If', 'While', 'Function', 'Return']
class Expression:
def __init__(self, expr: Expr):
self.expr = expr
def __repr__(self) -> str:
return f"Expression {self.expr}"
class Print:
def __init__(self, expr: Expr):
self.expr = expr
def __repr__(self) -> str:
return f"Print {self.expr}"
class Var:
def __init__(self, name: Token, initializer: Expr):
self.name = name
self.initializer = initializer
def __repr__(self) -> str:
return f"Var {self.name} = {self.initializer}"
class Block:
def __init__(self, statements: List[Stmt]):
self.statements = statements
def __repr__(self) -> str:
statement_strings = [repr(statement) for statement in self.statements]
return f"{{ {' ; '.join(statement_strings)} }}"
class If:
def __init__(self, condition: Expr, then_branch: Stmt, else_branch: Optional[Stmt]):
self.condition = condition
self.then_branch = then_branch
self.else_branch = else_branch
def __repr__(self) -> str:
return f"if {self.condition} then {self.then_branch} else {self.else_branch}"
class While:
def __init__(self, condition: Expr, body: Stmt):
self.condition = condition
self.body = body
def __repr__(self) -> str:
return f"while {self.condition} do {self.body}"
class Function:
def __init__(self, name: Token, params: List[Token], body: List[Stmt]):
self.name = name
self.params = params
self.body = body
def __repr__(self) -> str:
param_strings = [repr(param) for param in self.params]
body_strings = [repr(statement) for statement in self.body]
return f"fun {self.name} ( {' , '.join(param_strings)} ) {{ {' ; '.join(body_strings)} }}"
class Return:
def __init__(self, keyword: Token, value: Expr):
self.keyword = keyword
self.value = value
def __repr__(self) -> str:
return f"return {self.value}"
<file_sep>/ivox/token.py
from enum import Enum
from literal import Literal
from typing import Optional, Union
class Token:
Type = Enum('TokenType', [
'LEFT_PAREN', 'RIGHT_PAREN', 'LEFT_BRACE', 'RIGHT_BRACE', 'COMMA', 'DOT', 'MINUS', 'PLUS', 'SEMICOLON', 'SLASH',
'STAR', 'BANG', 'BANG_EQUAL', 'EQUAL', 'EQUAL_EQUAL', 'GREATER', 'GREATER_EQUAL', 'LESS', 'LESS_EQUAL',
'IDENTIFIER', 'STRING', 'NUMBER',
'AND', 'CLASS', 'ELSE', 'FALSE', 'FUN', 'FOR', 'IF', 'NIL', 'OR', 'PRINT', 'RETURN', 'SUPER', 'THIS', 'TRUE',
'VAR', 'WHILE', 'OBJECT',
'EOF',
])
def __init__(self, type: Type, lexeme: str, line: int, literal: Optional[Literal] = None) -> None:
self.type = type
self.lexeme = lexeme
self.line = line
self.literal = literal
def __repr__(self) -> str:
if self.literal:
return f'{self.type.name}: {str(self.lexeme)}'
else:
return f'{self.lexeme}'
<file_sep>/README.md
3 projects on which I learned programming language design.
- **clox** - https://craftinginterpreters.com/ implementation
- **ivox** - clox but python
- **inj** - I almost managed to create types, LLVM and Haskell
<file_sep>/ivox/expr.py
from token import Token
from typing import Dict, List, Union
import literal
Expr = Union['Binary', 'Unary', 'Grouping', 'Logical', 'Literal', 'Variable', 'Assign', 'Call', 'Object', 'Get', 'Set']
class Binary:
def __init__(self, left: Expr, operator: Token, right: Expr):
self.left = left
self.operator = operator
self.right = right
def __repr__(self) -> str:
return f"({self.left} {self.operator} {self.right})"
class Unary:
def __init__(self, operator: Token, right: Expr):
self.operator = operator
self.right = right
def __repr__(self) -> str:
return f"({self.operator} {self.right})"
class Grouping:
def __init__(self, expression: Expr):
self.expression = expression
def __repr__(self) -> str:
return f"(group {self.expression})"
class Logical:
def __init__(self, left: Expr, operator: Token, right: Expr):
self.left = left
self.operator = operator
self.right = right
def __repr__(self) -> str:
return f"({self.left} {self.operator} {self.right})"
class Literal:
def __init__(self, value: literal.Literal):
self.value = value
def __repr__(self) -> str:
return repr(self.value)
class Variable:
def __init__(self, name: Token):
self.name = name
def __repr__(self) -> str:
return str(self.name)
class Assign:
def __init__(self, name: Token, value: Expr):
self.name = name
self.value = value
def __repr__(self) -> str:
return f"({self.name} = {self.value})"
class Call:
def __init__(self, callee: Expr, paren: Token, arguments: List[Expr]):
self.callee = callee
self.paren = paren
self.arguments = arguments
def __repr__(self) -> str:
argument_strings = [repr(argument) for argument in self.arguments]
return f"call {self.callee} ( {' , '.join(argument_strings)} )"
class Object:
def __init__(self, fields: Dict[Token, Expr]):
self.fields = fields
def __repr__(self) -> str:
field_strings = [f"{name} = {e}" for (name, e) in self.fields.items()]
return f"object {{ {' , '.join(field_strings)} }}"
class Get:
def __init__(self, object: Expr, name: Token):
self.object = object
self.name = name
def __repr__(self) -> str:
return f"{self.object} . {self.name}"
class Set:
def __init__(self, object: Expr, name: Token, value: Expr):
self.object = object
self.name = name
self.value = value
def __repr__(self) -> str:
return f"{self.object} set {self.name} = {self.value}"
|
2f526182462ebeb50fa1301f0a592957ed6fb4e2
|
[
"Markdown",
"Python"
] | 12
|
Python
|
ivokosir/language_poc
|
3d5de3fe61c066b0668d15f7946a4f130b364077
|
86b0330d256c02fd0b85552c59882f48e008c8cb
|
refs/heads/master
|
<repo_name>diasflack/simplemvc<file_sep>/README.md
# strongJS
Simple MVC framework with strong typization. Development in process...
<file_sep>/spec/MVCSpec.js
describe("MVC", function() {
var MVC = window.MVC;
it("contains MVC model in global var", function(){
expect(MVC).toBeDefined();
});
describe("PubSub module", function(){
it("can subscribe and publish", function() {
var info, result;
var subscription = MVC.PubSub.subscribe('test', function(obj) {
result = obj;
});
MVC.PubSub.publish('test', {
message: "test succesful"
});
expect(result.message).toBe("test succesful");
});
});
describe("Model", function() {
var properties, ItemModel;
beforeAll(function() {
properties = {string:"string", number:0, array:[1,2,3], object:{a:1}, func: function(){return "This is function"} };
ItemModel = new MVC.Model(properties);
});
describe("Basic model characteristic", function() {
it("can create Models with specified properties", function() {
var model = new ItemModel();
expect(model.string).toEqual("string");
expect(model.number).toEqual(0);
expect(model.array).toEqual([1,2,3]);
expect(model.object.a).toEqual(1);
expect(model.func()).toEqual("This is function");
});
it("properties are strong typed", function (){
var item = new ItemModel();
expect(function(){item.string = 0}).toThrowError("Wrong type! Must be string - but got number");
expect(function(){item.number = [1,2,3]}).toThrowError("Wrong type! Must be number - but got Array");
expect(function(){item.array = {a:1,b:2,c:3}}).toThrowError("Wrong type! Must be Array - but got object");
expect(function(){item.object = [1,2,3]}).toThrowError("Wrong type! Must be object - but got Array");
expect(function(){item.func = [1,2,3]}).toThrowError("Wrong type! Must be function - but got Array");
});
it("properties not deletable", function (){
var item1 = new ItemModel();
expect(delete item1.string).toBe(false);
});
it("can't extense, add new properties", function() {
var nonExtenseItem = new ItemModel();
nonExtenseItem.newProperty = "newValue";
expect(nonExtenseItem.newProperty).not.toBeDefined();
});
it("various model constructors creates various instances", function() {
var NewItemModel = new MVC.Model({name:"notItemModel"});
var item1 = new ItemModel();
var item2 = new NewItemModel();
expect(item1 instanceof ItemModel).toBeTruthy();
expect(item1 instanceof NewItemModel).toBeFalsy();
expect(item2 instanceof NewItemModel).toBeTruthy();
expect(item2 instanceof ItemModel).toBeFalsy();
});
});
describe("Model Lists", function() {
it("Model list update through model creation", function(){
var itemModelsList = new MVC.ModelList(ItemModel);
var item2 = new ItemModel({
name:"item2",
gramms: 50
});
expect(itemModelsList.models[0]).toEqual(item2);
});
});
});
describe("View", function(){
var settings, model, template, element;
beforeAll(function() {
var properties, ItemModel, div;
properties = {string:"string", number:0, array:[1,2,3], object:{a:1}, func: function(){return "This is function"} };
ItemModel = new MVC.Model(properties);
model = new ItemModel();
div = document.createElement("div");
div.setAttribute("id","someid");
div.innerHTML = "<p>%%number%%</p>";
document.body.appendChild(div);
element = document.getElementById("someid");
template = "<h1>%% string %%</h1>";
settings = {
model: model,
element: "someid",
template: template
}
});
it("must create view with basic settings", function(){
var itemView = new MVC.View(settings);
expect(itemView).toBeDefined();
expect(itemView.model).toEqual(model);
expect(itemView.element).toEqual(element);
expect(itemView.template).toEqual(template);
});
it("must use innerHTML if template is not defined", function() {
var itemView = new MVC.View({model:model,element:"someid"});
expect(itemView.template).toEqual("<p>%%number%%</p>");
});
describe("View initialize errors", function(){
it("must throw model error", function() {
expect(function() {new MVC.View({element: "someid"})}).toThrow();
});
it("must throw element error", function() {
expect(function() {new MVC.View({model:model})}).toThrow();
});
});
describe("View render functions", function() {
var itemView;
beforeEach(function() {
itemView = new MVC.View(settings);
});
it("must have render function", function() {
expect(itemView.render).toBeDefined();
});
it("must represent model values", function(){
});
it("must react on model changes", function(){
});
});
});
});
|
6a61cd9197c5ff3cf003d06e5b24dd77c354d1bb
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
diasflack/simplemvc
|
2f633a0e2dc768821b05dd426b2200dab3d68d46
|
18cbed0f0d07f77dde7137fae1c690d0c8413cff
|
refs/heads/main
|
<repo_name>miggiu89/php-snacks-b1<file_sep>/snack1/index.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.0">
<title>snack1</title>
</head>
<body>
<!-- Creiamo un array contenente le partite di basket di un’ipotetica tappa del calendario.
Ogni array avrà una squadra di casa e una squadra ospite, punti fatti dalla squadra di casa e punti fatti dalla squadra ospite.
Stampiamo a schermo tutte le partite con questo schema.
<NAME> - Cantù | 55-60 -->
<?php
$partite = [
[
'squadraCasa' => 'Los Angeles Lakers',
'squadraOspite' => 'Miami Heat',
'puntiCasa' => '60',
'puntiOspite' => '45'
],
[
'squadraCasa' => 'Orlando Magic',
'squadraOspite' => 'Toronto Raptors',
'puntiCasa' => '89',
'puntiOspite' => '78'
],
[
'squadraCasa' => 'Indiana Pacers',
'squadraOspite' => '<NAME>',
'puntiCasa' => '92',
'puntiOspite' => '105'
],
];
?>
<?php
for ( $i = 0; $i < count($partite); $i++ ) {
$casa = $partite[$i]['squadraCasa'];
$ospite = $partite[$i]['squadraOspite'];
$puntiCasa = $partite[$i]['puntiCasa'];
$puntiOspite = $partite[$i]['puntiOspite'];
?>
<div> <?php echo $casa . ' - ' . $ospite . ' | ' . $puntiCasa . ' - ' . $puntiOspite ?></div>
<?php } ?>
</body>
</html><file_sep>/snack2/index.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.0">
<title>Snack-2</title>
</head>
<body>
<!-- Passare come parametri GET name, mail e age e verificare (cercando i metodi che non conosciamo nella documentazione) che:
1. name sia più lungo di 3 caratteri,
2. mail contenga un punto e una chiocciola
3. age sia un numero.
Se tutto è ok stampare “Accesso riuscito”, altrimenti “Accesso negato”. -->
<?php
$nome = $_GET['nome'];
$mail = $_GET['mail'];
$eta = $_GET['eta'];
$accesso = '';
$suggerimento = '';
if ( empty($nome) && empty($mail) && empty($eta) ) {
$accesso = 'Accesso negato';
$suggerimento = 'Inserisci nome, mail e età';
} elseif ( strlen($nome) < 3 ){
$accesso = 'Accesso negato';
$suggerimento = 'Inserisci un nome più lungo di tre caratteri';
} elseif ( !strpos($mail, '@') || !strpos($mail, '.') ) {
$accesso = 'Accesso negato';
$suggerimento = 'Inserisci un\'email corretta. Che contenga un "@" e un punto "."';
} elseif ( !is_numeric($eta) ) {
$accesso = 'Accesso negato';
$suggerimento = 'Inserisci la tua età';
} else {
$accesso = 'Accesso consentito';
}
?>
<div><?php echo $accesso ?></div>
<div><?php echo $suggerimento ?></div>
</body>
</html>
|
19e1a9e8b8a3be842c1f59a41bcc51c223f6b3a4
|
[
"PHP"
] | 2
|
PHP
|
miggiu89/php-snacks-b1
|
74c7d283317937528362c18dc73410d3bee1e693
|
4f5cc53f3b4eeb894aa6eb10e109216672bf2134
|
refs/heads/master
|
<repo_name>PaolaBaldo/RestaurantsApp<file_sep>/README.md
# RestaurantsApp
1) Extract files
2)Change your current directory to RestaurantReviewsApp directory:
cd RestaurantReviewsApp
3)install Node.js
4)npm install
5)npm start
6)localhost:8000/app
<file_sep>/RestaurantReviewsApp/app/js/app.js
'use strict';
/* App Module */
var restaurantReviewsApp = angular.module('restaurantReviewsApp', [
'ngRoute',
'restaurantReviewsControllers'
]);
restaurantReviewsApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/restaurants', {
templateUrl: 'partials/restaurant-list.html',
controller: 'RestaurantListCtrl'
}).
when('/restaurants.restaurants/:restaurantId/:resName', {
templateUrl: 'partials/restaurant-detail.html',
controller: 'RestaurantDetailCtrl'
}).
when('/home/:search', {
templateUrl: 'partials/restaurant-list.html',
controller: 'LocationCtrl'
}).
when('/home', {
templateUrl: 'partials/home.html',
controller: 'LocationCtrl'
}).
otherwise({
redirectTo: '/home'
});
}])
.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['Access-Control-Allow-Origin'];
});
|
3b3cb665ceb27f97c1b2015d1b042ef6ed7bd33a
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
PaolaBaldo/RestaurantsApp
|
a5555e9ff3e6807bfcdf4edeff956ba616ea16be
|
a5b897a4b76754df26bd169e951cbecfb0fac183
|
refs/heads/main
|
<repo_name>AlineLGo/Projeto_Etec_PHP<file_sep>/conect1.php
<?php
$banco = new mysqli('localhost','root','','dados');
//echo " deu certo";
?>
<file_sep>/script.php
<?php
include 'conect1.php';
$nome = $_POST['nome'];
$sobrenome = $_POST['sobre'];
$nasc = $_POST['nasc'];
$rg = $_POST['rg'];
$cpf = $_POST['cpf'];
$sexo = $_POST['sexo'];
$rua = $_POST['rua'];
$numero = $_POST['numero'];
$bairro = $_POST['bairro'];
$estado = $_POST['estado'];
$cidade = $_POST['cidade'];
$cep = $_POST['cep'];
$email = $_POST['email'];
$foto = $_FILES["imagem"]["name"];
$login = $_POST['usuario'];
$senha = $_POST['pass'];
$pasta = "img/";
$separa = explode(".", $foto); // retira o ponto da extensão da foto.
$separa = array_reverse($separa); // inverte a posição dos vetores, não precisa saber o tamanho do vetor.
$tipo = $separa[0];
$foto = $cpf . '.' . $tipo;
$fotov = $pasta . $foto;
$testar = $banco->query("SELECT * FROM alunos WHERE cpf = '$cpf' ");
$check = mysqli_num_rows($testar);
if($check == 1){
echo "<h1>CPF já cadastrado!</h1>";
echo "<h1>$cpf</h1>";
}else {
$banco->query("INSERT INTO alunos(nome, sobrenome, nasc, rg, cpf, sexo, rua, numero, bairro, estado, cidade, cep, email, foto, login, senha) VALUES('$nome','$sobrenome','$nasc','$rg','$cpf','$sexo','$rua','$numero','$bairro','$estado','$cidade','$cep','$email','$fotov','$login','$senha')");
echo "<h1> Dados Cadastrados com SUCESSO!!!</h1>";
move_uploaded_file($_FILES['imagem']['tmp_name'],$pasta . $foto); //esse parametro faz com que a foto enviada pelo usuario seja salva na pasta selecionada. O parametro ['temp_name'] não muda.
};
echo"$nome<br>$sobrenome<br>$nasc<br>$rg<br>$cpf<br>$sexo<br>$rua<br>$numero<br>$bairro<br>$estado<br>$cidade<br>$cep<br>$email<br>$fotov<br>$login<br>$senha<br>";
echo "<a href=form.html> Voltar ao Cadastro</a>";
?><file_sep>/excluir.php
<?php
include 'conect1.php';
$cpf = $_GET["cpf"];
$buscar = $banco->query("SELECT * FROM alunos WHERE cpf = '$cpf'");
while ($linha = mysqli_fetch_array($buscar)) {
$foto = $linha["foto"];
}
unlink("$foto"); // deleta a foto da pasta
mysqli_query($banco, "DELETE FROM alunos WHERE cpf = '$cpf' ");
echo"Dados excluidos com sucesso!";
header("refresh:4;listar.php");
?><file_sep>/listar.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.0">
<title>Document</title>
</head>
<body>
<table border = "1">
<tr>
<td colspan="20">
<h1 align="center">Listagem de novos alunos</h1>
</td>
</tr>
<tr>
<td>CPF</td>
<td>Nome</td>
<td>Sobrenome</td>
<td>Nascimento</td>
<td>RG</td>
<td>Sexo</td>
<td>Rua</td>
<td>Número</td>
<td>Bairro</td>
<td>Estado</td>
<td>Cidade</td>
<td>CEP</td>
<td>Email</td>
<td>Foto</td>
<td>Login</td>
<td>Senha</td>
<td colspan="10" align="center">Ação</td>
</tr>
<?php
include 'conect1.php';
$buscar = $banco->query("SELECT * FROM alunos");
while ($linha = mysqli_fetch_array($buscar)) {
$cpf = $linha['cpf'];
$nome = $linha['nome'];
$sobrenome = $linha['sobrenome'];
$nasc = $linha['nasc'];
$rg = $linha['rg'];
$sexo = $linha['sexo'];
$rua = $linha['rua'];
$numero = $linha['numero'];
$bairro = $linha['bairro'];
$estado = $linha['estado'];
$cidade = $linha['cidade'];
$cep = $linha['cep'];
$email = $linha['email'];
$foto = $linha["foto"];
$login = $linha['login'];
$senha = $linha['senha'];
$pasta = "img/";
//$separa = explode(".", $foto); // retira o ponto da extensão da foto.
//$separa = array_reverse($separa); // inverte a posição dos vetores, não precisa saber o tamanho do vetor.
//$tipo = $separa[0];
//$foto = $cpf . '.' . $tipo;
//$fotov = $pasta . $foto;
echo "
<tr>
<td>$cpf</td>
<td>$nome</td>
<td>$sobrenome</td>
<td>$nasc</td>
<td>$rg</td>
<td>$sexo</td>
<td>$rua</td>
<td>$numero</td>
<td>$bairro</td>
<td>$estado</td>
<td>$cidade</td>
<td>$cep</td>
<td>$email</td>
<td><img src='$foto' width=100px></td>
<td>$login</td>
<td>$senha</td>
<td><a href='excluir.php?cpf=$cpf' onclick=\"return confirm('Tem certeza que deseja excluir?');\">Excluir</td>
<td>Alterar</td>
</tr>";
}
echo"</table>";
?>
</body>
</html>
<file_sep>/dados.sql
-- --------------------------------------------------------
-- Servidor: 127.0.0.1
-- Versão do servidor: 5.7.33 - MySQL Community Server (GPL)
-- OS do Servidor: Win64
-- HeidiSQL Versão: 11.3.0.6295
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!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 */;
-- Copiando estrutura do banco de dados para dados
CREATE DATABASE IF NOT EXISTS `dados` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `dados`;
-- Copiando estrutura para tabela dados.alunos
CREATE TABLE IF NOT EXISTS `alunos` (
`nome` varchar(50) DEFAULT NULL,
`sobrenome` varchar(50) DEFAULT NULL,
`nasc` date DEFAULT NULL,
`rg` int(11) DEFAULT NULL,
`cpf` int(11) DEFAULT NULL,
`sexo` varchar(50) DEFAULT NULL,
`rua` varchar(50) DEFAULT NULL,
`numero` int(11) unsigned DEFAULT NULL,
`bairro` varchar(50) DEFAULT NULL,
`estado` varchar(50) DEFAULT NULL,
`cidade` varchar(50) DEFAULT NULL,
`cep` int(11) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`foto` varchar(50) DEFAULT NULL,
`login` varchar(50) DEFAULT NULL,
`senha` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Exportação de dados foi desmarcado.
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */;
|
79677f05d27032e3b9aff3fd794d1f0fe203d691
|
[
"SQL",
"PHP"
] | 5
|
PHP
|
AlineLGo/Projeto_Etec_PHP
|
b68a161210adbb16dd500f5543c32ea65b9785c4
|
c685010ffd832f83a1fa0790b857cd9b13640de0
|
refs/heads/master
|
<repo_name>yuanlanda/TESTOpenGL<file_sep>/Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'TESTOpenGL' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for TESTOpenGL
pod 'Cocoa'
pod 'GLUT'
end
|
a3f87f462196c7a576f5e42bc8ac452e45892e36
|
[
"Ruby"
] | 1
|
Ruby
|
yuanlanda/TESTOpenGL
|
adee0d5e95cd61f24985ab7943e0d9d86839a842
|
0b3423d98d54e696ebe7138e11f6231fc7b6dd95
|
refs/heads/master
|
<repo_name>joskov/productivity-calendar<file_sep>/app/assets/javascripts/components/app.js
// components/app.js
var React = require('react');
var Router = require('react-router');
var RouteHandler = Router.RouteHandler;
var $ = require('jquery');
var App = React.createClass({
componentWillMount: function() {
$.ajax({
method: "GET",
url: "/auth/is_signed_in.json"
})
.done(function(data) {
this.setState({ signedIn: data.signed_in });
}.bind(this));
},
getInitialState: function() {
return { signedIn: null };
},
render:function(){
return <RouteHandler signedIn={this.state.signedIn}/>;
}
});
module.exports = App;
<file_sep>/app/assets/javascripts/components/auth/sign_up_form.js
var React = require('react');
var _ = require('lodash');
var Functions = require('../../utils/functions.js');
var SignUpForm = React.createClass({
_handleInputChange: function(ev) {
// Get a deep clone of the component's state before the input change.
var nextState = _.cloneDeep(this.state);
//Update the state of the component
nextState[ev.target.name] = ev.target.value;
// Update the component's state with the new state
this.setState(nextState);
},
getInitialState: function() {
return {
email: '',
password: '',
password_confirmation: '',
name: ''
};
},
_handleRegistrationClick: function(e) {
$.ajax({
method: "POST",
url: "/users.json",
data: {
user: {
email: this.state.email,
uid: this.state.email,
password: <PASSWORD>,
password_confirmation: <PASSWORD>,
name: this.state.name,
provider: "email"
},
authenticity_token: Functions.getMetaContent("csrf-token")
}
})
.done(function(data){
location.reload();
}.bind(this));
},
render: function(){
return (
<form>
<div>
<input type='text'
name='name'
placeholder='name'
value={this.state.name}
onChange={this._handleInputChange} />
<input type='email'
name='email'
placeholder='email'
value={this.state.email}
onChange={this._handleInputChange} />
<input type='password'
name='password'
placeholder='<PASSWORD>'
value={this.state.password}
onChange={this._handleInputChange} />
<input type='password'
name='password_confirmation'
placeholder='re-type password'
value={this.state.password_confirmation}
onChange={this.handleInputChange} />
</div>
<input onClick={this._handleRegistrationClick} defaultValue="sign up"/>
</form>
)
}
});
module.exports = SignUpForm;
<file_sep>/app/controllers/home_controller.rb
class HomeController < ApplicationController
layout 'empty', only: [:app]
def index
end
def app
end
end
<file_sep>/README.md
# productivity-calendar
Productivity Calendar App
<file_sep>/spec/factories.rb
# Factories
FactoryGirl.define do
factory :activity do
goal nil
started_at '2016-05-03 11:15:01'
ended_at '2016-05-03 11:15:01'
end
factory :goal do
user
title 'MyString'
end
factory :user do
end
end
<file_sep>/app/assets/javascripts/components/auth/sign_out_link.js
var React = require('react');
var $ = require('jquery');
var Functions = require('../../utils/functions.js');
var SignOutLink = React.createClass({
render:function(){
return (
<a href="#" onClick={this._signOut}>Sign out</a>
)
},
_signOut: function(){
$.ajax({
method: "DELETE",
url: "/users/sign_out.json",
data: {
authenticity_token: Functions.getMetaContent("csrf-token")
}
}).done(function(){
location.reload();
});
}
});
module.exports = SignOutLink;
|
9987e2ec7e4a07d353d39e16c9fe18c32ba95718
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 6
|
JavaScript
|
joskov/productivity-calendar
|
ae12efb969aad34383b17ecf83a325d415cfafbe
|
4960bbd9287ce3a38bc1219d3f8c98df7836cd01
|
refs/heads/master
|
<repo_name>yunzhique/sunflower<file_sep>/src/utils/getNormalizedImage/index.js
import * as r from "ramda"
import * as ra from "ramda-adjunct"
import {
normalizedImageCategory,
supportedFormat,
supportedSize,
ignoredFormat,
} from "./config"
import notEquals from "~/utils/notEquals"
const areImageAndSizeAllSupported = (src, size) =>
supportedSize.includes(size) && supportedFormat.test(src)
const removeMultiplySizeSuffix = src => src.replace(normalizedImageCategory, "")
const getFileExtension = r.takeLastWhile(notEquals("."))
const getNormalizedImage = r.curry((size, src) => {
// 历史原因,这几种图片没有生成多尺寸图片
if (ignoredFormat.test(src)) {
// 即使传入的是带有多尺寸样式的图片地址,也能返回 原始的正确地址
return removeMultiplySizeSuffix(src)
}
const matched = normalizedImageCategory.exec(src)
if (ra.isFalsy(matched)) {
if (areImageAndSizeAllSupported(src, size)) {
const extension = getFileExtension(src)
return `${src}${size}.${extension}`
}
return src
}
const { extension, size: sizeInSrc } = r.propOr({}, "groups", matched)
if (r.equals(size, sizeInSrc)) {
return src
}
const re = new RegExp(sizeInSrc + "\\." + extension + "$")
return src.replace(re, `${size}.${extension}`)
})
export default getNormalizedImage
export const getAvatar = getNormalizedImage(32)
<file_sep>/src/utils/storage/config.js
import localforage from "localforage"
import { app } from "~/configs"
export const { name } = app
export const driver = localforage.INDEXEDDB
<file_sep>/src/hooks/useNodeInfo/index.js
import * as r from "ramda"
import * as ra from "ramda-adjunct"
import { useState, useEffect } from "react"
import fromElectron from "~/utils/fromElectron"
import storage from "~/utils/storage"
const NODE_INFO = "NODE_INFO"
export default function() {
const [info, setInfo] = useState({})
const [whileRemoving, setWhileRemoving] = useState(false)
function set(info) {
if (info) setInfo(info)
return info
}
function saveToStorage(value) {
return storage.setItem(NODE_INFO, value)
}
async function removePkgs(pkg, clientName) {
setWhileRemoving(true)
const nodeInfo = await storage.getItem(NODE_INFO)
const clientInfo = r.prop(clientName, nodeInfo)
clientInfo.libs = r.without(ra.ensureArray(pkg), clientInfo.libs)
setInfo(nodeInfo)
return saveToStorage(nodeInfo).then(() => setWhileRemoving(false))
}
useEffect(() => {
storage.getItem(NODE_INFO).then(set)
fromElectron
.getNodeInfo()
.then(set)
.then(saveToStorage)
}, [])
return info // [info, { whileRemoving, removePkgs }]
}
<file_sep>/src/utils/getNormalizedImage/spec.js
import * as r from "ramda"
import * as ra from "ramda-adjunct"
import getNormalizedImage from "./index"
describe("getNormalizedImage", () => {
it("能够正确返回 png 图片文件的多尺寸版本", () => {
const imgSrc = "http://image.png"
expect(getNormalizedImage(32, imgSrc)).toBe(`${imgSrc}32.png`)
expect(getNormalizedImage(64, imgSrc)).toBe(`${imgSrc}64.png`)
expect(getNormalizedImage(120, imgSrc)).toBe(`${imgSrc}120.png`)
expect(getNormalizedImage(200, imgSrc)).toBe(`${imgSrc}200.png`)
})
it("能够正确返回 jpg 图片文件的多尺寸版本", () => {
const imgSrc = "http://image.jpg"
expect(getNormalizedImage(32, imgSrc)).toBe(`${imgSrc}32.jpg`)
expect(getNormalizedImage(64, imgSrc)).toBe(`${imgSrc}64.jpg`)
expect(getNormalizedImage(120, imgSrc)).toBe(`${imgSrc}120.jpg`)
expect(getNormalizedImage(200, imgSrc)).toBe(`${imgSrc}200.jpg`)
})
it("能够正确返回 jpeg 图片文件的多尺寸版本", () => {
const imgSrc = "http://image.jpeg"
expect(getNormalizedImage(32, imgSrc)).toBe(`${imgSrc}32.jpeg`)
expect(getNormalizedImage(64, imgSrc)).toBe(`${imgSrc}64.jpeg`)
expect(getNormalizedImage(120, imgSrc)).toBe(`${imgSrc}120.jpeg`)
expect(getNormalizedImage(200, imgSrc)).toBe(`${imgSrc}200.jpeg`)
})
it("除了 png,jpg,jpeg 类型的图片,其它类型 应该返回原图片地址", () => {
const imgSrc = "http://image.gif"
expect(getNormalizedImage(32, imgSrc)).toBe(imgSrc)
expect(getNormalizedImage(64, imgSrc)).toBe(imgSrc)
expect(getNormalizedImage(120, imgSrc)).toBe(imgSrc)
expect(getNormalizedImage(200, imgSrc)).toBe(imgSrc)
})
it("正确的图片类型,如果指定的 size 不被支持,应该返回原图片地址", () => {
const jpgImgSrc = "http://image.jpg"
const pngImgSrc = "http://image.png"
const jpegImgSrc = "http://image.jpeg"
expect(getNormalizedImage(42, jpgImgSrc)).toBe(jpgImgSrc)
expect(getNormalizedImage(999, pngImgSrc)).toBe(pngImgSrc)
expect(getNormalizedImage(-128, jpegImgSrc)).toBe(jpegImgSrc)
})
it("明确标识是 big, small, teamlogo 类型的图片,不应该生成指定的尺寸,返回原图片地址", () => {
const jpgImgSrc = "http://image.big.jpg"
const pngImgSrc = "http://image.small.png"
const jpegImgSrc = "http://image.teamlogo.jpeg"
expect(getNormalizedImage(42, jpgImgSrc)).toBe(jpgImgSrc)
expect(getNormalizedImage(999, pngImgSrc)).toBe(pngImgSrc)
expect(getNormalizedImage(-128, jpegImgSrc)).toBe(jpegImgSrc)
})
it("明确标识是 big, small, teamlogo 类型的图片,如果传入的是固定的尺寸,也应该返回原图片地址(不带尺寸)", () => {
const jpgImgSrc = "http://image.big.jpg32.jpg"
const pngImgSrc = "http://image.small.png64.png"
const jpegImgSrc = "http://image.teamlogo.jpeg120.jpeg"
expect(getNormalizedImage(32, jpgImgSrc)).toBe("http://image.big.jpg")
expect(getNormalizedImage(999, pngImgSrc)).toBe("http://image.small.png")
expect(getNormalizedImage(-128, jpegImgSrc)).toBe(
"http://image.teamlogo.jpeg",
)
})
it("正确类型的图片,请求指定的size,但传入的已经是正确尺寸的图片,能正确返回", () => {
const imgSrc = "http://image.png32.png"
expect(getNormalizedImage(32, imgSrc)).toBe(imgSrc)
})
it("正确类型的图片,请求指定的size,但传入的已经是其它尺寸的图片,能正确返回", () => {
const imgSrc = "http://image.png32.png"
expect(getNormalizedImage(64, imgSrc)).toBe(imgSrc.replace("32", "64"))
})
it("图片地址中含有size和类型,能正确返回", () => {
const imgSrc = "http://image.png32.png.jpg"
expect(getNormalizedImage(64, imgSrc)).toBe(imgSrc + "64.jpg")
expect(getNormalizedImage(42, imgSrc)).toBe(imgSrc)
})
})
<file_sep>/src/utils/userOrgInfoStorage/index.js
import * as r from "ramda"
import storage from "~/utils/storage"
import { USER_ORG_INFO, actions } from "./config"
export default r.reduce(transform, {}, actions)
function transform(accu, key) {
return {
...accu,
[key]: r.partial(storage[key], [USER_ORG_INFO]),
}
}
<file_sep>/src/utils/env/spec.js
import env from "./index"
describe("env", () => {
it("能够获取当前的所处的 env 环境", () => {
const { current } = env
expect(current).toBe("test")
})
it("能够判断当前是否处于设置的环境", () => {
expect(env.isTest).toBeTruthy()
expect(env.isDev).toBeFalsy()
expect(env.isProd).toBeFalsy()
})
})
<file_sep>/index.js
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require("electron-squirrel-startup")) app.quit()
const { app, BrowserWindow, globalShortcut } = require("electron")
const r = require("ramda")
const ra = require("ramda-adjunct")
const path = require("path")
const isDev = require("electron-is-dev")
const initPlugins = require("./plugins")
const isDarwinEnv = r.propEq("platform", "darwin")(process)
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = true
let mainWindow = null
function createWindow() {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
},
width: 1024,
height: 600,
})
mainWindow.on("closed", () => (mainWindow = null))
}
app.on("ready", init)
app.on("window-all-closed", () => isDarwinEnv && app.quit())
app.on("activate", () => ra.isNull(mainWindow) && init())
/*
* In this file you can include the rest of your app's specific main process
* code. You can also put them in separate files and require them here.
*/
function init() {
createWindow()
initPlugins()
load()
openDevtools()
register()
}
function quit() {
globalShortcut.unregisterAll()
app.quit()
}
function register() {
const ret = globalShortcut.register("CommandOrControl+Q", quit)
if (!ret) {
console.log("registration failed")
}
}
function load() {
const url = isDev
? "http://localhost:3000/"
: `file://${path.resolve(__dirname, "..", "dist")}/index.html`
mainWindow.loadURL(url)
}
function openDevtools() {
mainWindow.webContents.on("did-frame-finish-load", () => {
if (isDev) {
mainWindow.webContents.on("devtools-opened", mainWindow.focus)
mainWindow.webContents.openDevTools({
// mode: "detach",
})
}
})
}
<file_sep>/src/components/ImageWithText/index.js
import React, { memo } from "react"
import * as r from "ramda"
import pt from "prop-types"
import Image from "~/components/Image"
ImageWithText.propTypes = {
src: pt.string.isRequired,
text: pt.string.isRequired,
style: pt.object,
imageStyle: pt.object,
textStyle: pt.object,
}
function ImageWithText(props) {
return (
<div style={props.style}>
<Image src={props.src} style={createImageStyle(props)} />
<span style={createTextStyle(props)}>{props.text}</span>
</div>
)
}
export default memo(ImageWithText)
const createImageStyle = props => ({
width: "32px",
borderRadius: "50%",
verticalAlign: "middle",
...props.imageStyle,
})
const createTextStyle = props => ({
paddingLeft: "8px",
...props.textStyle,
})
<file_sep>/src/apps/Header/index.js
import React from "react"
import pt from "prop-types"
import { Navbar, Colors, Alignment } from "@blueprintjs/core"
import config from "./config"
import ImageWithText from "~/components/ImageWithText"
const Header = () => {
return (
<Navbar style={style}>
<Navbar.Group align={Alignment.LEFT} style={style}>
<ImageWithText src={config.logo} text={config.title} />
</Navbar.Group>
</Navbar>
)
}
export default Header
const style = {
height: "60px",
color: "white",
backgroundColor: Colors.BLUE3,
}
<file_sep>/src/init.js
import { setConfig } from "react-hot-loader"
import "@blueprintjs/core/lib/css/blueprint.css"
import "~/assets/iconfont/iconfont.css"
import { FocusStyleManager } from "@blueprintjs/core"
FocusStyleManager.onlyShowFocusOnTabs()
setConfig({
ignoreSFC: true,
pureRender: true,
})
<file_sep>/src/utils/fromElectron/index.js
import { ipcRenderer } from "electron"
import * as r from "ramda"
import * as ra from "ramda-adjunct"
const pluginList = require(`${__PLUGINS__}/list`)
export default new Proxy({}, { get })
function get(target, key) {
if (!pluginList.includes(key)) {
throw new Error(`Doesn't exist that plugin [${key}] !`)
}
if (ra.isTruthy(target[key])) {
return target[key]
}
target[key] = (...args) =>
new Promise(resolve =>
ipcRenderer.on(key, (_, resp) => resolve(resp)).send(key, ...args),
)
return target[key]
}
<file_sep>/plugins/getUser.js
const r = require("ramda")
module.exports = async function() {
return r.pathOr("", ["env", "USER"], process)
}
<file_sep>/plugins/getSubDirsOf.js
const ra = require("ramda-adjunct")
const execCommand = require("./internal/execCommand")
module.exports = async function(parent) {
try {
if (ra.isTruthy(parent)) {
return (await execCommand(`ls ${parent}`)).split("\n")
}
throw new Error("路径不能为空!")
} catch (e) {
return Promise.reject(e.message)
}
}
<file_sep>/src/components/Avatar/index.js
import React, { memo, useState } from "react"
import * as r from "ramda"
import ImageWithText from "~/components/ImageWithText"
import addPropTypesTo_ from "~/utils/addPropTypesTo_"
import getAvatar from "~/utils/getAvatar"
import config from "./config"
const Avatar = props => {
const imgSrc = getAvatar(props.avatar)
return (
<ImageWithText
style={style}
src={imgSrc}
imageStyle={imageStyle}
text={props.name}
textStyle={textStyle}
/>
)
}
export default r.pipe(
memo,
addPropTypesTo_(createPropTypes()),
)(Avatar)
function createPropTypes() {
return {
avatar: "string.",
name: "string.",
}
}
const style = {
color: "white",
}
const imageStyle = {
borderRadius: "25%",
verticalAlign: "middle",
}
const textStyle = {
paddingLeft: "10px",
}
const iconStyle = {
paddingLeft: "2px",
}
<file_sep>/src/utils/getAvatar/spec.js
import getAvatar from "./index"
import { AVATAR_SIZE } from "./config"
describe("getAvatar", () => {
it("能够返回正确的 avatar 图片地址", () => {
const imgSrc = "http://image.png"
expect(getAvatar(imgSrc)).toBe(`${imgSrc}${AVATAR_SIZE}.png`)
})
it("不支持的图片类型,返回原图片地址", () => {
const imgSrc = "http://image.bmp"
expect(getAvatar(imgSrc)).toBe(imgSrc)
})
})
<file_sep>/src/utils/dataSource/index.js
export { default } from "./axios"
export { default as jsonp } from "./jsonp"
<file_sep>/src/components/Popconfirm/index.jsx
import { Popover } from "@blueprintjs/core"
import Content from "./Content"
export default function Component({ children, ...rest }) {
return (
<Popover minimal content={<Content {...rest} />}>
{children}
</Popover>
)
}
<file_sep>/plugins/internal/pickStdoutAndTrim.js
const r = require("ramda")
module.exports = r.pipe(
r.propOr("", "stdout"),
r.trim,
)
<file_sep>/src/hooks/useNodeClientInfoOf/index.js
import * as r from "ramda"
import * as ra from "ramda-adjunct"
import { useState, useEffect } from "react"
import fromElectron from "~/utils/fromElectron"
import storage from "~/utils/storage"
export default function(client) {
const STORAGE_KEY = getStorageKey(client)
const [info, setInfo] = useState({})
const [whileRemoving, setWhileRemoving] = useState(false)
function set(info) {
if (info) setInfo(info)
return info
}
function saveToStorage(value) {
return storage.setItem(STORAGE_KEY, value)
}
async function removePkgs(pkg) {
setWhileRemoving(true)
const clientInfo = await storage.getItem(STORAGE_KEY)
clientInfo.pkgs = r.without(ra.ensureArray(pkg), clientInfo.pkgs)
setInfo(clientInfo)
return saveToStorage(clientInfo).then(() => setWhileRemoving(false))
}
useEffect(
() => {
storage.getItem(STORAGE_KEY).then(set)
fromElectron
.getNodeClientInfoOf(client)
.then(set)
.then(saveToStorage)
},
[client],
)
return [info, whileRemoving, removePkgs]
}
const getStorageKey = r.pipe(
r.toUpper(),
r.concat(r.__, "_INFO"),
)
<file_sep>/src/apps/entry.js
import { hot } from "react-hot-loader/root"
import React from "react"
import { useTitle } from "react-use"
import { Flex, Box } from "reflexbox"
import { Button } from "@blueprintjs/core"
import useUsername from "~/hooks/useUsername"
import Header from "~/apps/Header"
import Sidebar from "~/apps/Sidebar"
import { app } from "~/configs"
const Entry = () => {
const username = useUsername()
useTitle(`Hi, ${username}`)
return (
<>
<Header />
<Flex align="center" mt={1}>
<Box w={app.sidebarWidth}>
<Sidebar />
</Box>
<Box auto>Box B</Box>
</Flex>
</>
)
}
export default hot(Entry)
<file_sep>/plugins/getNodeClientInfoOf.js
const r = require("ramda")
const ra = require("ramda-adjunct")
const execCommand = require("./internal/execCommand")
const isFile = require("./isFile")
const getSubDirsOf = require("./getSubDirsOf")
module.exports = async function(command) {
try {
const basicInfo = await getBasicInfo(command)
if (r.isEmpty(basicInfo)) return basicInfo
const libraries = await getLibraries(command)
const [scoped, plain] = r.partition(r.startsWith("@"), libraries)
const { root } = basicInfo
const getScopedSubDirsIfNeeded = r.isEmpty(scoped)
? r.always([])
: getScopedSubDirs
const pkgs = await getScopedSubDirsIfNeeded(root, scoped)
const allPkgs = r.concat(pkgs, plain)
const purePkgs = await rejectFiles(root, allPkgs)
return {
...basicInfo,
name: command,
pkgs: purePkgs,
}
} catch (e) {
return {}
}
}
function getRootDirDirectiveOf(command) {
const directives = {
yarn: "yarn global dir",
npm: "npm root -g",
}
return directives[command]
}
async function getBasicInfo(command) {
try {
const rootDirDirective = getRootDirDirectiveOf(command)
const [path, version, root] = await Promise.all([
execCommand(`which ${command}`),
execCommand(`${command} --version`),
execCommand(rootDirDirective),
])
return { path, version, root }
} catch (e) {
return {}
}
}
async function getLibraries(command) {
try {
const rootDirDirective = getRootDirDirectiveOf(command)
const libraries = await execCommand(`ls $(${rootDirDirective})`)
return r.pipe(
r.split("\n"),
ra.compact,
)(libraries)
} catch (e) {
return []
}
}
async function getScopedSubDirs(parent, pkgs) {
const subDirs = await r.pipe(
r.map(r.concat(`${parent}/`)),
r.map(getSubDirsOf),
subDirs => Promise.all(subDirs),
)(pkgs)
const zipped = r.zipWith((parent, subDirs) =>
r.map(r.concat(`${parent}/`))(subDirs),
)(pkgs, subDirs)
return r.flatten(zipped)
}
async function rejectFiles(parent, pkgs) {
const result = []
for await (let pkg of pkgs) {
if (await isFile(`${parent}/${pkg}`)) {
continue
}
result.push(pkg)
}
return result
}
<file_sep>/src/utils/propTypes/impl.js
/*
* <NAME>
* 2017/11/08
* <EMAIL>
*/
/*
* import propTypes from "..."
* const MyComponent = props => <div {...props}>{props.children}</div>
*
* MyComponent.propTypes = propTypes({
* id: "string",
* isChild: "bool",
* isParent: "bool.",
* })
*
* =>
*
* MyComponent.propTypes = {
* id: PropTypes.string,
* isChild: PropTypes.bool,
* isParent: PropTypes.bool.isRequired,
* }
*/
import PropTypes from "prop-types"
import * as r from "ramda"
import * as ra from "ramda-adjunct"
import _ from "lodash/fp"
import addUnitTestTo_ from "../addUnitTestTo_"
const isRequired = r.invoker(1, "endsWith")(".")
const getRequired = r.prop("isRequired")
const { isArray, isFunction, isString } = ra
const iteratee = value => {
return r.cond([
[isOneOfType, oneOfType],
[isArrayOf, arrayOf],
[isObjectOf, objectOf],
[isInstanceOf, instanceOf],
[isShape, shape],
[isOneOf, oneOf],
[isArrayOfShorthand, arrayOfShorthand],
[isObjectOfShorthand, objectOfShorthand],
[isFunction, customProp],
[isString, defaults],
[r.T, exception],
])(value)
}
export default r.map(iteratee)
const is = type =>
r.allPass([
isArray,
r.compose(
r.invoker(1, "startsWith")(type),
r.nth(0),
),
])
const isOneOfType = is("oneOfType")
const isOneOf = is("oneOf")
const isObjectOf = is("objectOf")
const isArrayOf = is("arrayOf")
const isInstanceOf = is("instanceOf")
const isShape = is("shape")
const arrayOfPattern = /\[\s*(['"]?)(\w+)\1\s*\]/
const objectOfPattern = /\{\s*(['"]?)(\w+)\1\s*\}/
const isShorthand = pattern => ::pattern.test
const isArrayOfShorthand = isShorthand(arrayOfPattern)
const isObjectOfShorthand = isShorthand(objectOfPattern)
const parse = value => {
const isRequired_ = isRequired(value)
const type = isRequired_ ? r.init(value) : value
return { isRequired_, type }
}
/* if rule is [isRequired], then return [object.isRequired] */
const polyfillRequired = isRequired => object =>
isRequired ? getRequired(object) : object
/* for UNIT TEST only! */
const buildFieldsForUnitTest = (fn_, args_, isRequired_) => ({
fn_,
args_,
isRequired_,
})
const buildResult = (fn_, args_, isRequired_) => {
return r.compose(
addUnitTestTo_(buildFieldsForUnitTest(fn_, args_, isRequired_)),
polyfillRequired(isRequired_),
fn_,
)(args_)
}
function exception(value) {
throw `Invalid type [${value}]`
}
function oneOf([name, ...args_]) {
const { isRequired_, type } = parse(name)
const fn_ = PropTypes[type]
return buildResult(fn_, args_, isRequired_)
}
function arrayOf([name, elementType]) {
const { isRequired_, type } = parse(name)
const fn_ = PropTypes[type]
const args_ = isFunction(elementType) ? elementType : PropTypes[elementType]
return buildResult(fn_, args_, isRequired_)
}
function objectOf([name, elementType]) {
const { isRequired_, type } = parse(name)
const fn_ = PropTypes[type]
const args_ = PropTypes[elementType]
return buildResult(fn_, args_, isRequired_)
}
function xOfShorthand(value, pattern, type) {
const isRequired_ = isRequired(value)
const elementType = value.match(pattern)[2]
const fn_ = PropTypes[type]
const args_ = PropTypes[elementType]
return buildResult(fn_, args_, isRequired_)
}
function arrayOfShorthand(value) {
return xOfShorthand(value, arrayOfPattern, "arrayOf")
}
function objectOfShorthand(value) {
return xOfShorthand(value, objectOfPattern, "objectOf")
}
function instanceOf([name, Class]) {
const { isRequired_, type } = parse(name)
const fn_ = PropTypes[type]
const args_ = Class
return buildResult(fn_, args_, isRequired_)
}
function oneOfType([name, ...args]) {
const { isRequired_, type } = parse(name)
const fn_ = PropTypes[type]
const args_ = args.map(arg =>
isArray(arg) ? iteratee(arg) : PropTypes[_.trimChars(".")(arg)],
)
const result = fn_(args_)
return addUnitTestTo_(buildFieldsForUnitTest(fn_, args_, isRequired_))(result)
}
function shape([name, args_]) {
const { isRequired_, type } = parse(name)
const fn_ = PropTypes[type]
const unitTestFields = buildFieldsForUnitTest(fn_, args_, isRequired_)
return r.compose(
addUnitTestTo_(unitTestFields),
r.map(iteratee),
)(args_)
}
function customProp(value) {
return value
}
function defaults(value) {
const replaceLastPeriodWithIsRequired = r.replace(/\.$/)(".isRequired")
const result = r.compose(
r.path(r.__, PropTypes),
r.split("."),
replaceLastPeriodWithIsRequired,
)(value)
if (!result) {
throw new Error("Not invalid!")
}
return result
}
<file_sep>/plugins/isFile.js
const ra = require("ramda-adjunct")
const fs = require("fs")
module.exports = async function(path) {
try {
if (ra.isTruthy(path)) {
return await fs.statSync(path).isFile()
}
throw new Error("路径不能为空!")
} catch (e) {
return Promise.reject(e.message)
}
}
<file_sep>/src/utils/auth/config.js
export const captchaUrl = "/account/web/user/getKaptchaImage?uuid="
export const loginStateUrl =
"https://cia.chanapp.chanjet.com/internal_api/authorizeByJsonp"
export const webLoginUrl = "https://passport.chanjet.com/loginV2/webLogin"
export const gzqLoginUrl = "/web/sso/authForWeb"
export const gzqLogoutUrl = "/account/web/user/logout"
export const errorCodes = {
LOGIN_GZQ_FAILED: "9908",
}
<file_sep>/src/utils/getFormFieldValue/index.js
import * as r from "ramda"
export default function getFormFieldValue({ target = {} } = {}) {
const field = target.getAttribute(DATA_FIELD)
const value = getInputValue(target)
return r.objOf(field, value)
}
const getInputValue = target => {
const { value, checked, type } = target
return isSwitchable(type) ? checked : value
}
const DATA_FIELD = "data-field"
const isRadio = r.equals("radio")
const isCheckbox = r.equals("checkbox")
const isSwitchable = r.anyPass([isRadio, isCheckbox])
<file_sep>/src/utils/auth/index.js
import * as r from "ramda"
import dataSource, { jsonp } from "~/utils/dataSource"
import {
loginStateUrl,
gzqLoginUrl,
gzqLogoutUrl,
webLoginUrl,
errorCodes,
} from "./config"
import userOrgInfoStorage from "~/utils/userOrgInfoStorage"
import normalizeUserOrgInfo from "./normalizeUserOrgInfo"
export default { login, logout }
async function login(loginInfo) {
// Has logged into GZQ
if (isLoggedIntoGZQ()) return userOrgInfoStorage.getItem()
const { code, auth_code } = await getCiaLoginState()
if (code) {
// Has logged into CIA, but not GZQ
try {
await loginIntoGZQ(code)
return userOrgInfoStorage.getItem()
} catch (e) {
return Promise.reject({
message: "登录 GZQ 失败!",
code: errorCodes.LOGIN_GZQ_FAILED,
})
}
}
// Hasn't logged into CIA
const ciaOptions = buildCiaOptions(loginInfo, auth_code)
let writeToStoragePromise = null
try {
const userOrgInfo = await loginIntoCia(ciaOptions)
// 异步写
writeToStoragePromise = userOrgInfoStorage.setItem(
normalizeUserOrgInfo(userOrgInfo),
)
} catch (e) {
return Promise.reject({
message: e.errorMessage,
code: e.errorCode,
})
}
const ciaLoginState = await getCiaLoginState({
client_id: "da6e3f87-bb6f-4cdc-ac78-64b0ed4237c7",
status: "gzq",
})
try {
await loginIntoGZQ(ciaLoginState.code)
} catch (e) {
return Promise.reject({
message: "登录 GZQ 失败!",
code: errorCodes.LOGIN_GZQ_FAILED,
})
}
// 异步写完之后,再返回
return writeToStoragePromise.then(() => userOrgInfoStorage.getItem())
}
async function getCiaLoginState(options) {
return jsonp.get(loginStateUrl, {
params: {
_: Date.now(),
client_id: "4cb832be-e503-4075-9903-6aa8d9e29104",
jsonp: true,
...options,
},
})
}
async function loginIntoCia(options) {
return jsonp.get(webLoginUrl, {
params: {
_: Date.now(),
jsonp: 1,
...options,
},
})
}
async function loginIntoGZQ(code) {
// 这个接口 直接 重定向到了 GZQ 的首页,我们不需要它重定向
// 只要 它能帮我们 写上 cookie 即可
return dataSource.get(gzqLoginUrl, {
params: {
deviceType: "WEB",
deviceId: "WEB",
code,
},
})
}
function buildCiaOptions(loginInfo, auth_code) {
return {
auth_username: loginInfo.user,
password: <PASSWORD>,
auth_code,
}
}
export const isLoggedIntoGZQ = () => {
const GZQ_COOKIE = "gongzuoquan.info="
return r.pipe(
r.split(";"),
r.map(r.trim),
r.any(r.startsWith(GZQ_COOKIE)),
)(document.cookie)
}
async function logout() {
return dataSource
.post(gzqLogoutUrl)
.then(removeCachedUserOrgInfo)
.then(_ => ({
message: "退出成功!",
}))
}
const removeCachedUserOrgInfo = () => userOrgInfoStorage.removeItem()
<file_sep>/src/containers/PkgsManagement/Settings/RemoveAction.jsx
import { Button } from "@blueprintjs/core"
import * as ra from "ramda-adjunct"
import Popconfirm from "~/components/Popconfirm"
import mapPropTypes_ from "~/utils/mapPropTypes_"
function RemoveAction({ action = ra.noop }) {
return (
<Popconfirm
title="确认删除?"
cancelButtonText="我再想想"
confirmButtonText="删除吧!"
onConfirm={action}
>
<Button icon="trash" text="Remove" />
</Popconfirm>
)
}
RemoveAction.propTypes = {
action: "func",
}
export default mapPropTypes_(RemoveAction)
<file_sep>/src/utils/propTypes/index.js
import createPropTypes from "./impl"
export default createPropTypes
<file_sep>/plugins/index.js
const { ipcMain } = require("electron")
const pluginList = require("./list")
module.exports = function() {
pluginList.forEach(pluginName =>
ipcMain.on(pluginName, (event, ...args) => {
const plugin = require(`./${pluginName}`)
plugin(...args)
.then(resp => event.reply(pluginName, resp))
.catch(error => event.reply(pluginName, error))
}),
)
}
<file_sep>/src/components/Image/Simple.js
import React, { memo } from "react"
import pt from "prop-types"
import * as r from "ramda"
Image.propTypes = {
src: pt.string.isRequired,
}
function Image(props) {
return <img {...props} />
}
export default memo(Image)
<file_sep>/src/containers/PkgsManagement/Settings/config.js
import * as r from "ramda"
import * as ra from "ramda-adjunct"
import _ from "lodash/fp"
export const sources = [
{ name: "taobao", url: "https://registry.npm.taobao.org/" },
{ name: "npm", url: "https://registry.npmjs.org/" },
{ name: "cnpm", url: "http://r.cnpmjs.org/" },
{ name: "nj", url: "https://registry.nodejitsu.com/" },
{ name: "rednpm", url: "http://registry.mirror.cqupt.edu.cn/" },
{ name: "npmMirror", url: "https://skimdb.npmjs.com/registry/" },
{ name: "edunpm", url: "http://registry.enpmjs.org/" },
{ name: "chanjet", url: "https://registry-npm.rd.chanjet.com/" },
]
export const clients = [
{ icon: "drag-handle-horizontal", text: "npm" },
{ icon: "drag-handle-vertical", text: "yarn" },
]
const STORAGE_KEYS = [
"SETTING",
"SETTING_SOURCES",
"SETTING_ACTIVE_CLIENT_INDEX",
"SETTING_ACTIVE_SOURCE_INDEXES",
]
export const storageKeys = r.pipe(
ra.renameKeys(STORAGE_KEYS),
ra.renameKeysWith(_.camelCase),
)(STORAGE_KEYS)
<file_sep>/src/utils/getAvatar/config.js
export const AVATAR_SIZE = 32
<file_sep>/src/components/Switch/index.jsx
import { Button, ButtonGroup } from "@blueprintjs/core"
function Switch({ items, activeIndex, setActiveIndex = ra.noop }) {
return (
<ButtonGroup css={switchStyle}>
{items.map((item, index) => (
<Button
key={index}
{...item}
active={activeIndex === index}
onClick={() => setActiveIndex(index)}
/>
))}
</ButtonGroup>
)
}
|
be17ac9780b8fe5f4d63345064e7e759d3e722d7
|
[
"JavaScript"
] | 33
|
JavaScript
|
yunzhique/sunflower
|
177e9ccea5aa370a60d27c2404aebab9082cde45
|
b8f9cb629fe2b56595ac16eb103b0941b96207df
|
refs/heads/master
|
<file_sep># Formula1
A simple formula1 leaderboard, written in python 3, in linux
# Usage and Installation
Usage
```
usage: main.py [-h] dataType [country]
positional arguments:
dataType selects data to view Driver Standings: 0 Race Data: 1
country selects country (only applies if option 1 used)
```
Install required dependencies with
`pip3 install -r requirements.txt`
<file_sep>import argparse
import time
import requests
import lxml.html as lh
from datetime import datetime
from prettytable import PrettyTable
from os import system
countries = ["australia", "bahrain", "china", "azerbaijan", "spain", "monaco",
"canada", "france", "austria", "great_britain", "germany", "hungary",
"belgium", "italy", "singapore", "russia", "japan", "mexico",
"united_states", "brazil", "abu_dhabi"]
def main(dataType, country, raceID):
if dataType == 0:
url = "https://www.formula1.com/en/results.html/2020/drivers.html"
headers = ["Position", "First Name", "Last Name", "Nationality", "Car", "Points"]
waitTime = 30
elif dataType == 1:
if country == None:
print("no country specified")
exit()
url = "https://www.formula1.com/en/results.html/2020/races/{id}/{country}/race-result.html".format(id = raceID, country=country)
headers = ["Position", "Number", "First Name", "Last Name", "Car", "Laps", "Time", "Points"]
waitTime = 10
else:
print("Invalid flags")
try:
data = getdata(url)
except IndexError:
print("An error occured, are you sure this race has happened yet?")
exit()
display(data, headers, waitTime)
def getRaceID(country):
raceID = 1000
found = False
if country == None:
return None
else:
for i in range(len(countries)):
if countries[i] == country:
found = True
raceID += i
if found:
return str(raceID)
else:
print("invalid country (for countries with multiple words, use an _, ie great_britain)")
exit()
def getdata(url):
page = requests.get(url)
doc = lh.fromstring(page.content)
tbody = doc.xpath("//tbody")
dataraw = []
print(tbody)
for t in tbody[0]:
name = t.text_content()
dataraw.append(name)
data = []
for j in range(20):
data.append([])
popped = 0
row = dataraw[j].split("\n")
for i in range(len(row)):
row[i - popped] = row[i - popped].strip()
if row[i - popped] == "":
row.pop(i - popped)
popped += 1
if "race-result" in url:
row.pop(4)
else:
row.pop(3)
data[j] = row
return data
def display(data, headings, waitTime):
while True:
system("clear")
t = PrettyTable(headings)
for i in data:
t.add_row(i)
print(t)
print("local time:")
print(datetime.now().strftime('%H:%M'))
time.sleep(waitTime)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("dataType", help="selects data to view\nDriver Standings: 0\nRace Data: 1", type=int)
parser.add_argument("country", help="selects country (only applies if option 1 used)", type=str, nargs="?")
args = parser.parse_args()
country = args.country
dataType = args.dataType
raceID = getRaceID(country)
try:
main(dataType, country, raceID)
except KeyboardInterrupt:
print("Exiting")
|
cebc48f24f3434a455794477085f4f9cfb6238cb
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
bakullama/Formula1
|
062576688a4622c9349df4d09780bb9ebec3c130
|
1708e5769dd894c93f92428c16045f799c7131ca
|
refs/heads/master
|
<repo_name>ssimba/crudboy<file_sep>/main.py
import os
import sys
import argparse
import pymysql
parser = argparse.ArgumentParser(description='Generate Insert or Update Sql script from connected database.')
parser.add_argument("-t", "--table", help="Table name which you want to generate sql")
parser.add_argument("-m", "--model", help="update or insert")
create_time_fields= ['created', 'create_time']
update_time_fields= ['modified', 'last_modify_time']
def connect_db():
return pymysql.connect(host="localhost", port=3306,
user="user", password="<PASSWORD>", database="instance")
def run_sql(sql):
conn = connect_db()
cur = conn.cursor()
cur.execute(sql)
rows = cur.fetchall()
cur.close()
conn.close()
return rows
def get_tables():
sql_str = "SHOW TABLES;"
return run_sql(sql_str)
def get_table_columns(table: str) -> list:
sql_str = """SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'pm'
AND TABLE_NAME = '{0}';""".format(table)
columns = run_sql(sql_str)
return [col[0] for col in list(columns)]
def generate(tableName: str, columns: list, argModel: str):
def insert_sql(tableName, columns):
expr = lambda x: x != "id" and x not in update_time_fields
sql = f"""INSERT INTO {tableName}({', '.join([col for col in columns if expr(col)])})
VALUES({', '.join(['now()' if col in create_time_fields else '@'+col for col in columns if expr(col)])});"""
output = os.path.join(os.getcwd(), "output", "{}-insert.txt".format(tableName))
with open(output.format(tableName), 'w') as f:
f.write(sql)
def update_sql(tableName, columns):
sql = f"""UPDATE {tableName} SET
{', '.join([str(col)+"=@"+str(col) for col in columns if col!="id"])} WHERE id=@id;"""
sql = f"UPDATE {tableName} SET\r".format(tableName)
for col in columns:
if col == "id" or col in create_time_fields:
continue
tmp = f"{col}=@{col},\r"
if col in update_time_fields:
tmp = f"{col}=now(),\r"
sql += tmp
sql = sql.rstrip(",\r")+" \rWHERE id=@id;"
output = os.path.join(os.getcwd(), "output", "{}-update.txt".format(tableName))
with open(output.format(tableName), 'w') as f:
f.write(sql)
global create_time_fields
global update_time_fields
if argModel:
if argModel.lower() == "insert":
insert_sql(tableName, columns)
elif argModel.lower() == "update":
update_sql(tableName, columns)
else:
insert_sql(tableName, columns)
update_sql(tableName, columns)
if __name__ == "__main__":
args = parser.parse_args()
tables = get_tables()
for table in tables:
table_name = table[0]
if args.table != None and args.table != table_name:
continue
columns = get_table_columns(table_name)
generate(table_name, columns, args.model)
<file_sep>/README.md
# python 3
# usage
`pytho main.py -h`
|
c57b77e94d04569fff98d2f07adfaad12034865f
|
[
"Markdown",
"Python"
] | 2
|
Python
|
ssimba/crudboy
|
8bb2490445806888928c369df004b5bd12b45c40
|
56e880f4e3d86d1d9991f1051b84d41bd34da7c4
|
refs/heads/master
|
<file_sep># music-album
My first experiment with html
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<style>
h2.dil{
text-align: center;
font-size: 120;
color:
}
div{
text-align: center;
}
h2{
text-align: center;
color: green;
}
</style>
<title>Hangman</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<?php
// define variables and set to empty values
@error_reporting(2);
$user_array = array("<EMAIL>"=>"<PASSWORD>");
//$firstnameErr,$lastnameErr, $emailErr,$genderErr, $pwdErr;
global $firstname,$lastname, $email , $gender ,$pwd;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "Name is required";
} else {
$firstname = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Name is required";
} else {
$lastname = test_input($_POST["lastname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["pwd"])) {
$pwdErr = "password is required";
} else {
$pwd = test_input($_POST["pwd"]);
}
$gender = test_input($_POST["gender"]);
}
/*if (!isset($user_array[$email])) {
$user_array[$email]=$pwd;
header('location:login.html')
}
else {
$emailErr="email already exists";
header('location:reg.html');
}*/
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header col-lg-3">
<a class="navbar-brand" href="#"><span style="color:red">HANGMAN</span></a>
</div>
<ul class="nav navbar-nav">
<li ><a href="home.html">Home</a></li>
<li class="active"><a href="register.html">Signup</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="instr.html">Instructions</a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h2 style="color:green"> Registration</h2><br><br>
<form method="POST" action="register.php" >
First Name:
<input type="text" name="firstname" autofocus><br><br>
<span class="error">* <?php echo $firstnameErr;?></span>
Last Name:
<input type="text" name="lastname"><br><br>
<span class="error">* <?php echo $lastnameErr;?></span>
Email:
<input type="email" name="email"><br><br>
<span class="error">* <?php echo $emailErr;?></span>
Password:
<input type="<PASSWORD>" name="pwd"><br>
<br>
<span class="error">* <?php echo $pwdErr;?></span>
Gender:
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female">Female<br><br>
<input type="submit"></input>
</form>
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<style>
h2.dil{
text-align: center;
font-size: 120;
color:
}
</style>
<title>Hangman</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<?php
@error_reporting(2);
$user_array = array("<EMAIL>"=>"abcxyz");
//echo $user_array['<EMAIL>'];
global $firstname, $lastname, $email, $gender, $pwd;
$abc = $_POST['email'];
$xyz = $_POST['pwd'];
echo $abc;
echo $xyz;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = $_POST["email"];
}
if (empty($_POST["pwd"])) {
$pwdErr = "password is required";
} else {
$pwd = $_POST["pwd"];
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($user_array[$email])){
if (strcmp($pwd, $user_array[$email]) == 0) { //log user in if password is correct
session_start(); //create a session
$_SESSION['email'] = $email; //add details to the session
header('Location:cate.html');
}
else {
$passerr='<PASSWORD>';
}
}
else{
$namerr='incorrect email';
}
?>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header col-lg-3">
<a class="navbar-brand" href="#"><span style="color:red">HANGMAN</span></a>
</div>
<ul class="nav navbar-nav">
<li ><a href="home.html">Home</a></li>
<li ><a href="register.html">Signup</a></li>
<li class="active"><a href="login.html">Login</a></li>
<li ><a href="instr.html">Instructions</a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h2 class="dil">WELCOME TO HANGMAN</h2>
#<form class="form-inline" role="form" method="POST" action="login.php">
<div class="form-group">
<label for="email" autofocus>Email: </label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div><br><br>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="<PASSWORD>" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div><br><br>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div><br><br>
<input type="submit" ></input>
</form>
</body>
</html>
|
ffc4904977d513f5330c0a6bbd6302d53a374b51
|
[
"Markdown",
"PHP"
] | 3
|
Markdown
|
Ha-ckoder/music-album
|
f79f860bed60bac3d9d1a5dbcf77e2ef3c6456a0
|
f16cbd12126fd33229bd5481e74363d36f2ac25c
|
refs/heads/master
|
<repo_name>Point-SimoSiren/e-kauppa-Redux-NetCore<file_sep>/src/store.js
import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import tuoteReducer from './reducers/tuoteReducer'
import notificationReducer from './reducers/notificationReducer'
import koriReducer from './reducers/koriReducer'
const reducer = combineReducers({
tuotteet: tuoteReducer,
notification: notificationReducer,
korituotteet: koriReducer
})
const persistedState = localStorage.getItem('reduxState') ? JSON.parse(localStorage.getItem('reduxState')) : {}
const store = createStore(
reducer, persistedState,
composeWithDevTools(
applyMiddleware(thunk)
)
)
store.subscribe(() => {
localStorage.setItem('reduxState', JSON.stringify(store.getState()))
})
export default store<file_sep>/src/components/TuoteLista.js
import React from 'react'
import { connect } from 'react-redux'
import { addKori } from '../reducers/koriReducer'
import { notificationAction } from '../reducers/notificationReducer'
import '../style.css'
const arduinoKuva = require('./test.jpeg')
const TuoteLista = (props) => {
const pick = (tuote) => {
props.addKori(tuote)
console.log('valittu', tuote)
props.notificationAction(`${tuote.tuotenimi}" lisättiin ostoskoriin!`, 5)
}
return (
<div style={{ paddingTop: 70 }}>
<h4>Tuotteet</h4>
{props.tuotteet.map(tuote =>
<div key={tuote.tuoteId} className="card">
<div className="card-header">
<h4>{tuote.tuotenimi}</h4>
</div>
<div className="card-body">
<img style={{ width: 250, height: 150 }} src={arduinoKuva}
alt='kuva' />
<h5>{tuote.kuvaus}</h5>
<h4>Hinta {tuote.hinta} €</h4>
<h4>Tuotetta jäljellä: {tuote.varastosaldo} kpl</h4>
<button className="myButton" onClick={() => pick(tuote)} >osta</button>
</div>
<br />
</div>
)}
</div>
)
}
const mapStateToProps = (state) => {
return {
tuotteet: state.tuotteet,
notification: state.notification
}
}
const mapDispatchToProps = {
addKori, notificationAction
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(TuoteLista)
<file_sep>/src/App.js
import React, { useEffect } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import TuoteLista from './components/TuoteLista'
import AppNavbar from './components/AppNavbar'
import { initTuotteet } from './reducers/tuoteReducer'
import { connect } from 'react-redux'
import Ostoskori from './components/Ostoskori'
const App = (props) => {
useEffect(() => {
props.initTuotteet()
})
return (
<Router>
<div className="App">
<AppNavbar />
<div className="container">
<Switch>
<Route exact path="/" component={TuoteLista} />
<Route exact path="/ostoskori" component={Ostoskori} />
</Switch>
</div>
</div>
</Router>
)
}
export default connect(null, { initTuotteet })(App)<file_sep>/src/components/AppNavbar.js
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import Notification from './Notification'
class AppNavbar extends Component {
render() {
return (
<nav className="navbar navbar-expand-md fixed-top navbar-dark bg-primary mb-3">
<div className="container">
<Link to="/" className="navbar-brand">
Tuotteet
</Link>
<div className="navbar-brand">
<ul className="navbar-nav mr-auto">
<li><Notification /></li>
<li className="nav-item">
<Link to="/ostoskori" className="navbar-brand">
<i className="fas fa-shopping-cart"></i> Ostoskori
</Link>
</li>
</ul>
</div>
</div>
</nav>
)
}
}
export default AppNavbar
|
e199101993687dfbc00e8cf6049637d545ff71fd
|
[
"JavaScript"
] | 4
|
JavaScript
|
Point-SimoSiren/e-kauppa-Redux-NetCore
|
7a28a12d93111bccb01a46839cb770e599dcce85
|
8836ec5c87da08d3b85c7c4c3fdfd0bc63d0a484
|
refs/heads/master
|
<repo_name>wm-ytakano/slack_exporter<file_sep>/slack_exporter.py
# -*- coding: utf-8 -*-
import datetime
import json
import os
import sys
import argparse
import requests
def abort(msg):
print('Error!: {0}'.format(msg))
sys.exit(1)
def print_response(r, title=''):
c = r.status_code
h = r.headers
print('{0} Response={1}, Detail={2}'.format(title, c, h))
#d = r.json()
# if 'response_metadata' in d:
# print('response_metadata: {0}'.format(d['response_metadata']))
def assert_response(r, title=''):
c = r.status_code
h = r.headers
if title:
print('Asserting response of {0}...'.format(title))
if c < 200 or c > 299:
abort('{0} Response={1}, Detail={2}'.format(title, c, h))
d = r.json()
if not d['ok']:
abort('Not ok from slack, detail:{0}'.format(d['error']))
class Message:
def __init__(self, d):
self._ts = d['ts']
self._type = d['type']
self._text = ''
# channels.history で取得したメッセージの text(本文) には
# 値が入っていないことがある.
# 例: IFTTT Twitter 連携で流し込まれたメッセージ.
# その場合はどうしようもないので空値として扱う.
if ('text' in d) and (d['text'] is not None):
self._text = d['text'].encode('utf-8')
self._dtobj = datetime.datetime.fromtimestamp(float(self._ts))
self._dtstr = self._dtobj.strftime("%Y/%m/%d %H:%M:%S")
@property
def ts(self):
return self._ts
def __str__(self):
return """# {0}
{1}
ts:{2}, type:{3}
""".format(self._dtstr, self._text, self._ts, self._type)
class Channel:
def __init__(self, d):
self.id = d['id']
self.name = d['name']
self.purpose = ''
try:
self.purpose = d['purpose']['value'].encode('utf-8')
except KeyError:
pass
def __str__(self):
return "{0}({1}): {2}".format(self.name, self.id, self.purpose)
class ChannelDictionary:
def __init__(self, d):
self.d = {}
for limited_ch_obj in d:
ch = Channel(limited_ch_obj)
key = ch.id
value = ch
self.d[key] = value
class SlackAPI:
def __init__(self):
self._urlbase = 'https://slack.com/api'
self._proxies = {
"http": os.getenv('HTTP_PROXY'),
"https": os.getenv('HTTPS_PROXY'),
}
token = os.getenv('SLACKAPI_TOKEN')
if not token:
print("Error: Environment Variable 'SLACKAPI_TOKEN' is None")
sys.exit(1)
self._headers = {
"content-type": "application/json; charset=UTF-8",
"Authorization": f"Bearer {token}"
}
def _post(self, apiname, data):
return requests.post(f"{self._urlbase}/{apiname}",
data=json.dumps(data),
headers=self._headers,
proxies=self._proxies)
def _get(self, apiname, data):
return requests.get(f"{self._urlbase}/{apiname}",
data=json.dumps(data),
headers=self._headers,
proxies=self._proxies)
def test(self):
r = self._post("api.test", {})
assert_response(r, title='Test API')
resbody = r.json()
ok = resbody['ok']
return ok
def get_users_list(self):
r = self._get("users.list", {})
assert_response(r, title='Get all users list')
resbody = r.json()
members = resbody['members']
return members
def get_channels_list(self):
r = self._get("conversations.list", {})
assert_response(r, title='Get all channel list')
resbody = r.json()
channels = resbody['channels']
return channels
def get_number_of_history(self, chname):
data = {
'query': 'in:{0}'.format(chname),
'count': 1,
}
url = self._urlbase + '/search.messages'
r = self._post(url, data)
assert_response(
r, title='Get the number of history of channel "{0}"'.format(chname))
print_response(r)
resbody = r.json()
messages_root = resbody['messages']
total = messages_root['total']
return total
def get_messages(self, channel_id, count=1000, start_ts=None, end_ts=None):
""" @retrun A Message instances. """
url = self._urlbase + '/channels.history'
data = {
'channel': channel_id,
'count': count,
'unreads': 'true',
}
# - latest の timestamp を持つメッセージ自体は取得対象にならない.
# - oldest の timestamp を持つメッセージ自体は取得対象になる.
if start_ts:
data['latest'] = float(start_ts)
if end_ts:
data['oldest'] = float(end_ts)
r = self._post(url, data)
assert_response(r, title='Get Channel History.')
print_response(r)
resbody = r.json()
messages = resbody['messages']
return messages
def io_save_messages(self, channel_id, start_ts, end_ts, dstdir):
# 最初にチャンネル名を取得しておく.
#
# チャンネル名の使いみち
# - 保存先ファイル名に含める.
# - メッセージ総数取得(検索クエリにチャンネル名が必要).
chlist = self.get_channels_list()
chdict = ChannelDictionary(chlist).d
chname = chdict[channel_id].name
# メッセージが大量に存在する場合は
# progress を出さないと精神衛生上よろしくないので
# 総数を先にゲットしておく.
total = self.get_number_of_history(chname)
print('Message total {0} items'.format(total))
out = ''
trycount = 1
totalcount = (total/1000)
if total % 1000 != 0:
totalcount += 1
while True:
start_ts_text = start_ts
if start_ts is not None:
start_ts_text = 'Latest'
print(
'Getting {:}/{:} from {:} to next 1000.'
.format(trycount, totalcount, start_ts_text))
messages = self.get_messages(channel_id, 1000, start_ts, end_ts)
messageinst_list = []
for message in messages:
msg = Message(message)
messageinst_list.append(msg)
out += str(msg) + '\n'
# 1リクエスト最大件数まで取れてない = もう全部取れた
if len(messages) < 1000:
break
# 次の取得開始位置となる timestamp を取る.
# Slack API が順番を保証してくれてると信じて tail を見ちゃうよ.
start_ts = messageinst_list[-1].ts
trycount += 1
outpath = os.path.join(dstdir, 'log_{0}.md'.format(chname))
with open(outpath, 'w') as f:
f.write(out)
def parse_arguments():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument('--test', default=False,
action='store_true', help="Test API")
list_all_users_help = 'Lists all users in a Slack team'
parser.add_argument('--list-all-users', default=False,
action='store_true', help=list_all_users_help)
list_all_channels_help = 'Lists all channels in a Slack team'
parser.add_argument('-l', '--list-all-channels', default=False,
action='store_true', help=list_all_channels_help)
channel_id_help = 'A channel id you want to get all messages from.'
parser.add_argument('-c', '--channel-id', default='', help=channel_id_help)
start_help = '[DEBUG] Timestamp. End of time range of messages to include in results.'
parser.add_argument('--start', default=None, help=start_help)
end_help = '[DEBUG] Timestamp. Start of time range of messages to include in results.'
parser.add_argument('--end', default=None, help=end_help)
parsed_args = parser.parse_args()
return parsed_args
def main():
MYDIR = os.path.abspath(os.path.dirname(__file__))
DATADIR = f"{MYDIR}/data"
slackapi = SlackAPI()
args = parse_arguments()
if args.test:
print(slackapi.test())
return
if args.list_all_users:
users_list = slackapi.get_users_list()
with open(f"{DATADIR}/users.json", "w") as fo:
fo.write(json.dumps(users_list))
return
if args.list_all_channels:
channels_list = slackapi.get_channels_list()
with open(f"{DATADIR}/channels.json", "w") as fo:
fo.write(json.dumps(channels_list))
return
# print(slackapi.get_users_list())
# if use_channnelget:
# channels = slackapi.get_channel_list()
# out = ''
# for channel in channels:
# ch = Channel(channel)
# out += str(ch) + '\n'
# print(out)
# sys.exit(0)
# MYDIR = os.path.abspath(os.path.dirname(__file__))
# slackapi.io_save_messages(channel_id, start_ts, end_ts, MYDIR)
if __name__ == "__main__":
main()
<file_sep>/README.md
# slack_exporter
Slack の指定チャンネル内の全メッセージを取得する Python スクリプト。
<!-- toc -->
- [slack_exporter](#slack_exporter)
- [Overview](#overview)
- [Requirement](#requirement)
- [Usage](#usage)
- [Sample](#sample)
- [取得したいチャンネルの ID を得る](#取得したいチャンネルの-id-を得る)
- [指定チャンネルのメッセージ一覧を得る](#指定チャンネルのメッセージ一覧を得る)
- [FAQ](#faq)
- [Q: 取得対象メッセージ総数と実際に取得した数が合ってないようなのですが?](#q-取得対象メッセージ総数と実際に取得した数が合ってないようなのですが)
- [Q: IFTTT を使って Twitter のツイートを流してるチャンネルに対して実行すると本文が空になってますが?](#q-ifttt-を使って-twitter-のツイートを流してるチャンネルに対して実行すると本文が空になってますが)
- [License](#license)
- [Author](#author)
## Overview
指定チャンネル内の全メッセージを取得します。
前提:
- 私はひとりで Slack を使っています
- 私は [Legacy Token](https://api.slack.com/custom-integrations/legacy-tokens) を使用できます
- 指定チャンネル内の全メッセージをローカルにダンプしたいだけなんです
- とりあえず自分用に作ったので(特に標準出力内容とか)あまり整えてません
エクスポートの仕様:
- 取得するのはメッセージ本文のみ
- :x: メッセージに付いてるリアクションや投稿者名
- :x: アップロードしたファイル
- ただしシステムメッセージも取得される&そこにアップロード先URL等も書いてあるので **ポインタレベルなら漏れなく取得できてる** と思う
- **オレオレフォーマットの Markdown ファイルで出力します**
## Requirement
以下環境で動作確認しています。
- Windows7(x86 Professional), Windows10(x86_64 Home)
- Python2.7
- requests
## Usage
- Slack にログインして Legacy Token を入手する
- 環境変数 `SLACKAPI_TOKEN` に Legacy Token をセットする
- `python slack_exporter.py -l` でチャンネル名とチャンネルIDの対応を得る
- `python slack_exporter.py -c (取得したいチャンネルのID)`
## Sample
### 取得したいチャンネルの ID を得る
チャンネルID は `CXXXXXXXX` の 9文字の文字列です。メッセージ取得にはこの ID が必要なので、まず最初にこのやり方で把握しておきます。
```
$ python slack_exporter.py -l
Asserting response of Get all channel list...
170626_tweet_slack(CXXXXXXXX):
170812_macos_custom(CXXXXXXXX):
170924_emptyroom(CXXXXXXXX):
general(CXXXXXXXX): This channel is for team-wide communication and announcements. All team members are in this channel.
hatena_hotentries(CXXXXXXXX):
tokyo_weathers(CXXXXXXXX):
links(CXXXXXXXX):
onlinesoft_mado(CXXXXXXXX):
onlinesoft_vector(CXXXXXXXX):
twitter_github(CXXXXXXXX):
...
```
### 指定チャンネルのメッセージ一覧を得る
`-c CXXXXXXXX` を指定して実行します。
```
$ python slack_exporter.py -c CXXXXXXXX
Asserting response of Get all channel list...
Asserting response of Get the number of history of channel "170626_tweet_slack"...
Message total 3652 items
Getting 1/4 from Latest to next 1000.
Asserting response of Get Channel History....
Getting 2/4 from 1491193787.769016 to next 1000.
Asserting response of Get Channel History....
$ dir log_170626_tweet_slack.md
2017/09/24 08:02 405,962 log_170626_tweet_slack.md
```
すると `log_(チャンネル名).md` というファイル名が作られます。ここにメッセージ一覧がオレオレフォーマットで書き込まれています。
以下はファイル内容のサンプルです。
```markdown
# 2017/08/12 14:07:05
<@UXXXXXXXX> has renamed the channel from "tweet" to "170626_tweet_slack"
ts:1502514425.163748, type:message
# 2017/06/26 09:33:21
つぶやきは slack から github に移行したのでもうここは使わないよー
ts:1498437201.045524, type:message
# 2017/06/26 09:11:56
今ふと思ったけど、TwDD ってローカルで HTML ファイルに吐かせさえすれば見やすさ的にも解決ではないかとふと思ったり。URL については投稿前に URL を正規表現で探して、そこを a タグでくるむとかすればいいわけだし。
ts:1498435916.943443, type:message
...(中略)...
# 2017/02/11 21:26:19
slot script から投稿 :smile:.
ts:1486815979.000008, type:message
# 2017/02/11 21:21:30
日本語ツイートテスト
ts:1486815690.000004, type:message
# 2017/02/11 21:21:23
Test tweet
ts:1486815683.000003, type:message
```
## FAQ
### Q: 取得対象メッセージ総数と実際に取得した数が合ってないようなのですが?
A: 原因不明です
まず「数が合っていない」例については以下をご覧ください。
```
$ slack_exporter.py -c (Channel-ID)
Asserting response of Get all channel list...
Asserting response of Get the number of history of channel "(Channel-Name)"...
Message total 3652 items ★全部で3652件あると言っている
Getting 1/4 from Latest to next 1000.
Asserting response of Get Channel History....
Getting 2/4 from 1491193601.746383 to next 1000. ★実際取得したのは2000件以内(実際は1828件)
Asserting response of Get Channel History....
```
この例では 2000件 くらいの差が開いています。もし Message total が正しかったとすると 2000 件分をロストしていることになりますし、逆に 1828 件の方が正しかったとすると Message total は何やねん、という話になりますが……。
このような現象の原因はわかっていません。
一応技術的な手段の違いを述べておくと、
- Message total
- [search.messages method | Slack](https://api.slack.com/methods/search.messages) で `in:(指定したチャンネルID)` をクエリにしてリクエストを行い、レスポンスの中に入ってる `response['messages']['paging']['total']` を表示している
- 実際の取得
- [channels.history method | Slack](https://api.slack.com/methods/channels.history) で1リクエスト1000件取得、を繰り返すことで全件を取得している
という使用APIの違いはあります。(ちなみになぜ Message Total を使っているかというと、これを表示しないと「いつ終わるの?」と進捗がわからず精神衛生上よろしくないからです)
### Q: IFTTT を使って Twitter のツイートを流してるチャンネルに対して実行すると本文が空になってますが?
A: Slack の仕様だと思われます。
内部的には Slack API の [channels.history method](https://api.slack.com/methods/channels.history) の `text` フィールドの値を本文として保存してます。が、IFTTT で Twitter ツイートを取得するレシピを使って Slack に流し込んでいる場合、この text 値が空になるみたいです。
詳しいことはわかりません。IFTTT を使ったらアウトなのか。Twitter だからアウトなのか。はてさて……?
## License
[MIT License](LICENSE)
## Author
[stakiran](https://github.com/stakiran)
<file_sep>/token.sh.sample
#!/bin/bash
export SLACKAPI_TOKEN=(YOUR-BOT-TOKEN)
|
44b56b9846b1fd3b85a9809f3d64c99778afdaec
|
[
"Markdown",
"Python",
"Shell"
] | 3
|
Python
|
wm-ytakano/slack_exporter
|
a514e717afb69d71480ede5d0efd43d76182b642
|
0cefa474fea12b44cb9535dacc597b8a60f4c82d
|
refs/heads/master
|
<file_sep>import React from 'react';
import './App.css';
import Admin from './Admin';
import User from './User';
import Button from './Button';
import pic from "./pic.jpg"
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
function App() {
return (
<div>
<img src={pic} alt="mypic" />
<Router>
<div>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/admin" component={Admin} />
<Route path="/user" component={User} />
</Switch>
</div>
</Router>
</div>
);
}
const Home = () =>(
<div>
<Button/>
</div>
);
export default App;
<file_sep>import React from 'react';
import './App.css';
import { Link } from 'react-router-dom';
function Button() {
return (
<div className="links">
<ul className="link">
<Link to="/admin">
<li className="button">ADMIN / OFFICER LOGIN</li>
</Link>
<Link to="/user">
<li className="button">USER LOGIN / REGISTRATION</li>
</Link>
</ul>
</div>
);
}
export default Button;
|
83c04d844341650b2d6a55d06dc0617bb9d82cfc
|
[
"JavaScript"
] | 2
|
JavaScript
|
sahininayanthara/react_route
|
a5184f7473309a1eff02f33c6d594cf4b0e2a83d
|
0682fc5d6d6698f2c0a3ed6d5b43e65307dacaa4
|
refs/heads/master
|
<file_sep># cs215 project
Project for the 3<sup>rd</sup> semester course Data Analysis and Interpretation (CS215) [[Problem Statement](https://docs.google.com/presentation/d/1iuJXNmtnoYyk7o2rjPo0A9Bl4Vmgr2P1_mocr5taUEs/edit#slide=id.g47ad605e5_2_52)] [[Report](https://github.com/AnandDhoot/cs215/blob/master/project-report.pdf)]
<file_sep>#include <bits/stdc++.h>
#include <sstream>
using namespace std;
map < string , map < string,vector<double> > > know_base;
map < string , string > country_id_map;
map < string,vector<string> > keywords;
vector<string> tokenize(string input)
{
vector<string> result;
string str = input;
int start = 0, end = 0;
for(int i=0; i<str.length(); i++)
{
if(str[i] == '\t')
{
end = i;
string wrd = str.substr(start, end - start);
result.push_back(wrd);
start = i+1;
}
}
string wrd = str.substr(start, end - start);
result.push_back(wrd);
return result;
}
vector<string> tokenizeCountries(string input)
{
vector<string> result;
set<string> unique;
string str = input;
str.erase(remove(str.begin(), str.end(), ' '), str.end());
while(str.find(',') != string::npos)
{
size_t pos = str.find(',');
unique.insert(str.substr(0,pos));
str = str.substr(pos+1, str.length() - pos - 1);
}
unique.insert(str);
for(set<string>::iterator it = unique.begin(); it != unique.end(); it++)
result.push_back(*it);
return result;
}
vector<double> tokenizeNumbers(string input)
{
vector<double> result;
set<double> unique;
string str = input;
str.erase(remove(str.begin(), str.end(), ' '), str.end());
while(str.find(',') != string::npos)
{
size_t pos = str.find(',');
stringstream ss;
ss << str.substr(0,pos);
double val;
ss >> val;
unique.insert(val);
str = str.substr(pos+1, str.length() - pos - 1);
}
stringstream ss1(str);
double val1;
ss1 >> val1;
unique.insert(val1);
for(set<double>::iterator it = unique.begin(); it != unique.end(); it++)
result.push_back(*it);
return result;
}
void findResults(string Sid, vector<string> countries, vector<double> numbers,vector<string> words)
{
int c_score;
bool do_keywords=true;
for(int i=0;i<countries.size();i++)
{
for(int j=0;j<numbers.size();j++)
{
map< string,vector<double> > temp = know_base[country_id_map[countries[i]]];
for(map< string,vector<double> >::iterator p= temp.begin(); p != temp.end(); p++)
{
double max_conf=0;
int max_k;
double max_x,max_x1,max_diff;
for(int k=0; k<((*p).second.size()); k++)
{
double x1=numbers[j];
double x=(*p).second[k];
double diff;
double xm=max(x,x1);
if(xm==0)
diff= abs((x1-x)/(xm + 1));
else
diff= abs((x1-x)/(xm));
double conf = exp(-1*pow(diff*30,2)/2) * 100;
if(conf>max_conf)
{
max_k=k;
max_conf=conf;
max_x=x;
max_diff=diff;
max_x1=x1;
}
}
if(max_conf>=20)
{
int match=0;
vector<string> temp1=keywords[(*p).first];
for(int i1=0;i1<temp1.size();i1++)
{
if(words[1].find(temp1[i1]) != string::npos)
{
match++;
}
}
double conf1=max_conf+(100-max_conf)/3;
double conf2=conf1+(100-conf1)/3;
if(match==0 && max_conf>=50)
cout<<Sid<<", "<<countries[i]<<", "<<(*p).first<<", "<<max_conf<< "%,\n";
else if(match==1 && conf1>=50)
cout<<Sid<<", "<<countries[i]<<", "<<(*p).first<<", "<<conf1<< "%,\n";
else if(match>1)
{
for(int i1=3;i1<=match;i1++)
conf2=conf2+(100-conf2)/3;
if(conf2>=50)
cout<<Sid<<", "<<countries[i]<<", "<<(*p).first<<", "<<conf1<< "%,\n";
}
}
}
}
}
}
int main()
{
ifstream kb("knowledgebase/kb-facts-train_SI.tsv");
if(!kb)
{
cout<<"File not found.\n";
return 0;
}
string line;
while(getline(kb,line))
{
stringstream lineStream(line);
string country_id;
lineStream>>country_id;
double info;
lineStream>>info;
string relation;
lineStream>>relation;
know_base[country_id][relation].push_back(info);
}
kb.close();
ifstream c_id_file("knowledgebase/countries_id_map.txt");
if(!c_id_file)
{
cout<<"File not found.\n";
return 0;
}
while(getline(c_id_file,line))
{
stringstream lineStream(line);
string country_id;
string country_name;
lineStream>>country_id;
lineStream>>country_name;
country_id_map[country_name] = country_id;
}
c_id_file.close();
ifstream kw("keywords.txt");
while(getline(kw, line))
{
vector<string> words = tokenize(line);
for(int i=1;i<words.size();i++)
keywords[words[0]].push_back(words[i]);
}
kw.close();
ifstream in;
cout<<"SentenceID, Country, Relation, Confidence Score\n";
in.open("sentences.tsv");
if(!in)
{
cout<<"File not found\n";
return 0;
}
while(getline(in, line))
{
vector<string> words = tokenize(line);
vector<string> countries = tokenizeCountries(words[3]);
vector<double> numbers = tokenizeNumbers(words[2]);
string Sid=words[0];
findResults(Sid,countries, numbers, words);
}
in.close();
return 0;
}
|
6cabf3b97a41c3a51fc5a11cb48b81b854e815ce
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
AnandDhoot/cs215
|
bfa0833fb12ed5b48fe679b0e51b81f4373f8ccb
|
1239d3f0acbf7867de514314e03fc19f0d53d0e3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.