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><?php
// Check for empty fields
if(empty($_POST['name']) || empty($_POST['email']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$data = $name.','.$email_address.PHP_EOL;
$fp = fopen('registrations.txt', 'a');
fwrite($fp, $data);
return true;
?>
| ec906f0df8559264d422aa818b81eb3d645ee141 | [
"PHP"
] | 1 | PHP | woutwoot/startbootstrap-freelancer | 3763bb2e165bc450ea90e3a13d8955d9b781ba6f | f4d2939bd47360bebe514b5503476a388c5bb265 |
refs/heads/master | <repo_name>syslabcomarchive/slc.loginmsg<file_sep>/src/slc/loginmsg/controlpanel.py
from plone.app.registry.browser.controlpanel import RegistryEditForm
from plone.app.registry.browser.controlpanel import ControlPanelFormWrapper
from slc.loginmsg.interfaces import ILoginMsgSettings
from plone.z3cform import layout
from z3c.form import form
class LoginMsgControlPanelForm(RegistryEditForm):
form.extends(RegistryEditForm)
schema = ILoginMsgSettings
schema_prefix = "slc.loginmsg"
LoginMsgControlPanelView = layout.wrap_form(
LoginMsgControlPanelForm, ControlPanelFormWrapper)
LoginMsgControlPanelView.label = u"Login message settings"
<file_sep>/src/slc/loginmsg/tests/test_set_message.py
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import unittest2 as unittest
from Products.PlonePAS.events import UserLoggedInEvent
from Testing.makerequest import makerequest
from plone import api
from plone.registry.interfaces import IRegistry
from zope.event import notify
from slc.loginmsg.testing import IntegrationTestCase
class TestSetMessage(IntegrationTestCase):
def setUp(self):
mt = api.portal.get_tool('portal_membership')
self.user = mt.getAuthenticatedMember()
self.request = makerequest(self.layer['app']).REQUEST
self.status_messages = api.portal.IStatusMessage(self.request)
self.registry = api.portal.getUtility(IRegistry)
def test_no_message(self):
notify(UserLoggedInEvent(self.user))
messages = self.status_messages.show()
self.assertEqual(len(messages), 0)
def test_static_message(self):
self.registry['slc.loginmsg.static_message'] = u'Welcome!'
notify(UserLoggedInEvent(self.user))
messages = self.status_messages.show()
self.assertEqual(len(messages), 1)
self.assertEqual(messages[0].message, u'Welcome!')
def test_news_item(self):
self.registry['slc.loginmsg.show_news_item'] = True
api.content.create(
container=self.layer['portal'],
id='test-news',
title='Test News',
type='News Item',
text=u'Neuigkeiten für bärtige Flößer'
)
notify(UserLoggedInEvent(self.user))
messages = self.status_messages.show()
self.assertEqual(len(messages), 1)
self.assertEqual(messages[0].message,
u'Neuigkeiten für bärtige Flößer')
<file_sep>/src/slc/loginmsg/interfaces.py
# -*- coding: utf-8 -*-
"""Module where all interfaces, events and exceptions live."""
from zope.interface import Interface
from zope import schema
class ILoginMsgSettings(Interface):
static_message = schema.TextLine(
title=u"A static login message",
default=u"",
required=False,
)
show_news_item = schema.Bool(
title=u"Show latest News Item",
default=False,
required=False,
)
<file_sep>/docs/api.rst
===
API
===
Miscellaneous
=============
.. automodule:: slc.loginmsg
:members:
----
.. automodule:: slc.loginmsg.interfaces
:members:
Tests
=====
.. automodule:: slc.loginmsg.testing
:members:
----
.. automodule:: slc.loginmsg.tests.test_setup
:members:
<file_sep>/src/slc/loginmsg/subscribers.py
from Products.CMFPlone.utils import safe_unicode
from Products.PluggableAuthService.interfaces.events import IUserLoggedInEvent
from plone import api
from plone.registry.interfaces import IRegistry
from five import grok
@grok.subscribe(IUserLoggedInEvent)
def show_login_message(ev):
request = api.portal.getRequest()
registry = api.portal.getUtility(IRegistry)
message = registry.get('slc.loginmsg.static_message')
if message:
api.portal.show_message(message, request=request)
show_news_item = registry.get('slc.loginmsg.show_news_item')
if show_news_item:
cat = api.portal.get_tool('portal_catalog')
items = cat(portal_type='News Item',
sort_on='created',
sort_order='reverse',
)
if items:
text = items[0].getObject().getText()
pt = api.portal.get_tool('portal_transforms')
message = pt.convertTo('text/plain', text).getData().strip()[:255]
api.portal.show_message(safe_unicode(message), request=request)
<file_sep>/README.rst
====================
slc.loginmsg
====================
Display a message on login
* `Source code @ GitHub <https://github.com/syslabcom/slc.loginmsg>`_
* `Releases @ PyPI <http://pypi.python.org/pypi/slc.loginmsg>`_
* `Documentation @ ReadTheDocs <http://slcloginmsg.readthedocs.org>`_
* `Continuous Integration @ Travis-CI <http://travis-ci.org/syslabcom/slc.loginmsg>`_
How it works
============
...
Installation
============
To install `slc.loginmsg` you simply add ``slc.loginmsg``
to the list of eggs in your buildout, run buildout and restart Plone.
Then, install `slc.loginmsg` using the Add-ons control panel.
Configuration
=============
...
| a8604209a2f9a9d5dfaf215436459ffa06dd30bb | [
"Python",
"reStructuredText"
] | 6 | Python | syslabcomarchive/slc.loginmsg | db43ae7af041f6ec349a67a9a6e35c21799ebc3c | 80e163ad4c3c23c738a5097e6eeb94ad7f2a2444 |
refs/heads/master | <repo_name>qjie7/cg4002-dashboard<file_sep>/backend/data_generator.js
exports.getRandomData = function (json, player) {
const keys = Object.keys(json)
const randIndex = Math.floor(Math.random() * keys.length)
const randKey = keys[randIndex]
return {
time: new Date().toLocaleTimeString(),
xAxis: json[randKey].X,
yAxis: json[randKey].Y,
zAxis: json[randKey].Z,
danceMove: getDanceMove(),
position: getPosition(),
accuracy: getAccuracy(),
sync: getSync(),
}
}
function getSync() {
let random = Math.floor(Math.random() * 10)
if (random === 1) {
return 10
} else if (random === 2) {
return 20
} else if (random === 3) {
return 30
} else if (random === 4) {
return 40
} else if (random === 5) {
return 50
} else if (random === 6) {
return 60
} else if (random === 7) {
return 70
} else if (random === 8) {
return 80
} else if (random === 9) {
return 90
} else if (random === 10) {
return 100
} else {
return 0
}
}
function getAccuracy() {
let random = Math.floor(Math.random() * 8)
if (random === 1) {
return 10
} else if (random === 2) {
return 20
} else if (random === 3) {
return 30
} else if (random === 4) {
return 40
} else if (random === 5) {
return 50
} else if (random === 6) {
return 60
} else if (random === 7) {
return 70
} else if (random === 8) {
return 80
} else if (random === 9) {
return 90
} else if (random === 10) {
return 100
} else {
return 0
}
}
function getDanceMove() {
let random = Math.floor(Math.random() * 8)
if (random === 1) {
return 'Dab'
} else if (random === 2) {
return 'Elbow-Kick'
} else if (random === 3) {
return 'Gun'
} else if (random === 4) {
return 'Hair'
} else if (random === 5) {
return 'Listen'
} else if (random === 6) {
return 'Point-High'
} else if (random === 7) {
return 'Side-Pump'
} else if (random === 8) {
return 'Wipe-Table'
} else {
return 'Neutral'
}
}
function shuffle(o) {
for (
let j, x, i = o.length;
i;
j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x
);
return o
}
function getPosition() {
let numbers = [1, 2, 3]
let random = shuffle(numbers)
return random
}
exports.getTestLogData = function (json) {
const keys = Object.keys(json)
const randIndex = Math.floor(Math.random() * keys.length)
const randKey = keys[randIndex]
return json[randKey]
}
<file_sep>/frontend/src/components/InputAdornments/InputAdornments.js
import React from 'react'
import clsx from 'clsx'
import { makeStyles } from '@material-ui/core/styles'
import IconButton from '@material-ui/core/IconButton'
import OutlinedInput from '@material-ui/core/OutlinedInput'
import InputLabel from '@material-ui/core/InputLabel'
import InputAdornment from '@material-ui/core/InputAdornment'
import FormControl from '@material-ui/core/FormControl'
import Visibility from '@material-ui/icons/Visibility'
import VisibilityOff from '@material-ui/icons/VisibilityOff'
import Button from '@material-ui/core/Button'
import axios from 'axios'
import Snackbar from '@material-ui/core/Snackbar'
import MuiAlert from '@material-ui/lab/Alert'
function Alert(props) {
return <MuiAlert elevation={6} variant='filled' {...props} />
}
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'center',
marginTop: '10px',
},
margin: {
margin: theme.spacing(1),
paddingRight: 33,
},
withoutLabel: {
marginTop: theme.spacing(3),
},
textField: {
width: '70ch',
marginLeft: '60px',
},
button: {
width: '100%',
'& > * + *': {
marginTop: theme.spacing(2),
},
},
alert: {
width: '100%',
marginLeft: '120px',
},
}))
export default function InputAdornments(props) {
const classes = useStyles()
const { access } = props
const [values, setValues] = React.useState({
password: '',
showPassword: false,
})
const [accessStatus, setAccessStatus] = React.useState(true)
const handleChange = (prop) => (event) => {
setValues({ ...values, [prop]: event.target.value })
}
const handleClickShowPassword = () => {
setValues({ ...values, showPassword: !values.showPassword })
}
const handleMouseDownPassword = (event) => {
event.preventDefault()
}
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return
}
setAccessStatus(true)
}
function handleSubmit(event) {
axios
.post('/api/login', values)
.then((response) => {
access(response.data)
setAccessStatus(response.data)
console.log(response.data)
})
.catch((error) => {
console.log(error)
})
}
return (
<>
<div className={classes.root}>
<div>
<FormControl
className={clsx(classes.margin, classes.textField)}
variant='outlined'
>
<InputLabel htmlFor='outlined-adornment-password'>
Enter your developer password here
</InputLabel>
<OutlinedInput
fullWidth
id='outlined-adornment-password'
type={values.showPassword ? 'text' : 'password'}
value={values.password}
onChange={handleChange('password')}
endAdornment={
<InputAdornment position='end'>
<IconButton
aria-label='toggle password visibility'
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
edge='end'
>
{values.showPassword ? <Visibility /> : <VisibilityOff />}
</IconButton>
</InputAdornment>
}
labelWidth={260}
/>
</FormControl>
</div>
</div>
<div style={{ textAlign: 'center' }} className={classes.button}>
<Button
variant='contained'
color='secondary'
className={classes.margin}
onClick={handleSubmit}
type='submit'
>
Request For Access
</Button>
<Snackbar
open={!accessStatus}
autoHideDuration={3000}
onClose={handleClose}
>
<Alert
onClose={handleClose}
severity='error'
className={classes.alert}
>
Wrong Password!
</Alert>
</Snackbar>
</div>
</>
)
}
<file_sep>/frontend/src/pages/Authenticate.js
import React from 'react'
import Grid from '@material-ui/core/Grid'
import Typography from '@material-ui/core/Typography'
import { makeStyles } from '@material-ui/core/styles'
import Container from '@material-ui/core/Container'
import InputAdornments from '../components/InputAdornments/InputAdornments'
import logo from '../images/logo_dev_transparent.png'
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(2),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
width: '100%',
},
heading: {
fontSize: '4.5em',
letterSpacing: '-1px',
backgroundColor: '#503e9d',
color: 'white',
},
}))
export default function Authenticate(props) {
const classes = useStyles()
const { access } = props
return (
<>
<Grid container justify='center' style={{ marginTop: '-10px' }}>
<Grid item xs={12}>
<Typography variant='h3' align='center' className={classes.heading}>
{' '}
Developer Mode
</Typography>
</Grid>
</Grid>
<Container component='main' maxWidth='xs'>
<div className={classes.paper}>
<img
src={logo}
style={{ width: '100%', height: 'auto' }}
alt='team logo'
/>
<Typography variant='h6'>
Please Sign In To Access Developer Mode
</Typography>
<InputAdornments access={access} />
</div>
</Container>
</>
)
}
<file_sep>/frontend/src/pages/Playground.js
import React from 'react'
import { useEffect, useState } from 'react'
import { Grid, Typography } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import CircularProgress from '@material-ui/core/CircularProgress'
import Button from '@material-ui/core/Button'
import Backdrop from '@material-ui/core/Backdrop'
import { motion } from 'framer-motion'
import io from 'socket.io-client'
import styled from 'styled-components'
import { Modal } from '../components/Modal/Modal'
import FormDialog from '../components/FormDialog/FormDialog'
import DancerCard from '../components/DancerCard/DancerCard'
import DancerCard2 from '../components/DancerCard/DancerCard2'
const useStyles = makeStyles((theme) => ({
margin: {
margin: theme.spacing(1),
paddingRight: 33,
},
backdrop: {
zIndex: theme.zIndex.drawer + 1,
color: '#fff',
},
heading: {
fontSize: '4.5em',
letterSpacing: '-1px',
backgroundColor: '#503e9d',
top: '0px',
color: 'white',
},
}))
const Container = styled.div`
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 50px;
bottom: 50px;
`
const socket = io('http://localhost:3000', {
transports: ['websocket', 'polling'],
})
function Playground() {
const classes = useStyles()
const [danceMove, setDanceMove] = useState('Nothing')
const [danceMove2, setDanceMove2] = useState('Nothing')
const [danceMove3, setDanceMove3] = useState('Nothing')
const [finalDanceMove, setFinalDanceMove] = useState('nothing')
const [finalPosition, setFinalPosition] = useState('1 2 3')
const [accuracy, setAccuracy] = useState(0)
const [accuracy2, setAccuracy2] = useState(0)
const [accuracy3, setAccuracy3] = useState(0)
const [overallAccuracy, setOverallAccuracy] = useState(0)
const [posAccuracy, setPosAccuracy] = useState(0)
const [finalSync, setFinalSync] = useState('0')
const [syncAvg, setSyncAvg] = useState(0)
const [showModal, setShowModal] = useState(false)
const openModal = () => {
setShowModal((prev) => !prev)
}
const [connection, setConnection] = useState(false)
const handleConnection = () => {
if (connection) {
const syncSum = syncListFloat.reduce((a, b) => a + b, 0)
const syncAvg = syncSum / syncList.length || 0
setSyncAvg(syncAvg)
}
connection ? setConnection(false) : setConnection(true)
connection ? setShowModal(true) : setShowModal(false)
}
const [open, setOpen] = React.useState(false)
const handleClickOpen = () => {
setOpen(true)
}
const handleClose = () => {
setOpen(false)
}
const [open2, setOpen2] = React.useState(false)
const handleClickOpen2 = () => {
setOpen2(true)
}
const handleClose2 = () => {
setOpen2(false)
}
const [open3, setOpen3] = React.useState(false)
const handleClickOpen3 = () => {
setOpen3(true)
}
const handleClose3 = () => {
setOpen3(false)
}
function handleLeaderNameChange(e) {
console.log(e.target.value)
localStorage.setItem('leaderName', e.target.value)
}
function handleMember1NameChange(e) {
console.log(e.target.value)
localStorage.setItem('member1Name', e.target.value)
}
function handleMember2NameChange(e) {
console.log(e.target.value)
localStorage.setItem('member2Name', e.target.value)
}
const [groupName, setGroupName] = useState('Group Name')
const [leaderName, setLeaderName] = useState('Leader Name')
const [member1Name, setMember1Name] = useState('Member 1 Name')
const [member2Name, setMember2Name] = useState('Member 2 Name')
useEffect(() => {
setGroupName(localStorage.getItem('groupName'))
setLeaderName(localStorage.getItem('leaderName'))
setMember1Name(localStorage.getItem('member1Name'))
setMember2Name(localStorage.getItem('member2Name'))
})
const [score, setScore] = useState(0)
const [maxScore, setMaxScore] = useState(0)
const [score2, setScore2] = useState(0)
const [maxScore2, setMaxScore2] = useState(0)
const [score3, setScore3] = useState(0)
const [maxScore3, setMaxScore3] = useState(0)
const [scorePos, setScorePos] = useState(0)
const [maxScorePos, setMaxScorePos] = useState(0)
const [correctness, setCorrectness] = useState(false)
const [syncList, setSyncList] = useState([])
useEffect(() => {
if (connection) {
setAccuracy(0)
setScore(0)
setScore2(0)
setScore3(0)
setScorePos(0)
setMaxScore(0)
setMaxScore2(0)
setMaxScore3(0)
setMaxScorePos(0)
socket.on('new_data', (newData) => {
setDanceMove(newData.danceMove)
})
socket.on('new_data2', (newData) => {
setDanceMove2(newData.danceMove)
})
socket.on('new_data3', (newData) => {
setDanceMove3(newData.danceMove)
})
socket.on('new_data4', (newData) => {
setFinalDanceMove(newData.finalDanceMove)
setFinalPosition(newData.finalPosition)
setFinalSync(newData.finalSync)
setSyncList((oldList) => [...oldList, newData.finalSync])
})
} else {
socket.off('new_data')
socket.off('new_data2')
socket.off('new_data3')
socket.off('new_data4')
}
}, [connection])
useEffect(() => {
const handleKey = (event) => {
if (event.keyCode === 81 && connection) {
setCorrectness(true)
setScore((prevScore) => prevScore + 1)
setMaxScore((prevScore) => prevScore + 1)
} else if (event.keyCode === 87 && connection) {
setCorrectness(true)
setScore2((prevScore) => prevScore + 1)
setMaxScore2((prevScore) => prevScore + 1)
} else if (event.keyCode === 69 && connection) {
setCorrectness(true)
setScore3((prevScore) => prevScore + 1)
setMaxScore3((prevScore) => prevScore + 1)
} else if (event.keyCode === 82 && connection) {
setCorrectness(true)
setScorePos((prevScore) => prevScore + 1)
setMaxScorePos((prevScore) => prevScore + 1)
} else if (event.keyCode === 65 && connection) {
setCorrectness(false)
setMaxScore((prevScore) => prevScore + 1)
} else if (event.keyCode === 83 && connection) {
setCorrectness(false)
setMaxScore2((prevScore) => prevScore + 1)
} else if (event.keyCode === 68 && connection) {
setCorrectness(false)
setMaxScore3((prevScore) => prevScore + 1)
} else if (event.keyCode === 70 && connection) {
setCorrectness(false)
setMaxScorePos((prevScore) => prevScore + 1)
}
}
window.addEventListener('keydown', handleKey)
return () => {
window.removeEventListener('keydown', handleKey)
}
})
useEffect(() => {
setAccuracy(maxScore === 0 ? 0 : (score * 100) / maxScore)
setAccuracy2(maxScore2 === 0 ? 0 : (score2 * 100) / maxScore2)
setAccuracy3(maxScore3 === 0 ? 0 : (score3 * 100) / maxScore3)
setOverallAccuracy((accuracy + accuracy2 + accuracy3) / 3)
setPosAccuracy(maxScorePos === 0 ? 0 : (scorePos * 100) / maxScorePos)
})
let syncListFloat = syncList.map(function (x) {
return parseFloat(x, 10)
})
console.log(syncAvg)
return (
<>
<FormDialog
handleClickOpen={handleClickOpen}
handleClose={handleClose}
open={open}
setOpen={setOpen}
handleNameChange={handleMember1NameChange}
/>
<FormDialog
handleClickOpen={handleClickOpen2}
handleClose={handleClose2}
open={open2}
setOpen={setOpen2}
handleNameChange={handleLeaderNameChange}
/>
<FormDialog
handleClickOpen={handleClickOpen3}
handleClose={handleClose3}
open={open3}
setOpen={setOpen3}
handleNameChange={handleMember2NameChange}
/>
<Grid container justify='center' style={{ marginTop: '-10px' }}>
<Grid item xs={12}>
<Typography variant='h3' align='center' className={classes.heading}>
{groupName}
</Typography>
</Grid>
</Grid>
<Grid container justify='center'>
{/* Display Dancer Cards start here */}
{/* 1 2 3 */}
{finalPosition === '1 2 3' && (
<>
{/* #1 */}
<Grid item>
<motion.span>
<DancerCard
name={leaderName}
position={finalPosition.substring(0, 1)}
userImage='NRfYKuSKs_o'
danceMove={danceMove}
role='Leader'
handleClickOpen={handleClickOpen2}
accuracy={accuracy.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
{/* #2 */}
<Grid item>
<motion.span>
<DancerCard2
name={member1Name}
position={finalPosition.substring(2, 3)}
userImage='OqQi3nCt4CA'
danceMove={danceMove2}
handleClickOpen={handleClickOpen}
accuracy={accuracy2.toFixed(1)}
sync={finalSync}
posAccuracy={posAccuracy.toFixed(1)}
/>
</motion.span>
</Grid>
{/* #3 */}
<Grid item>
<motion.span>
<DancerCard
name={member2Name}
position={finalPosition.substring(4)}
userImage='SFJz9q9EAZc'
danceMove={danceMove3}
role='Member 2'
handleClickOpen={handleClickOpen3}
accuracy={accuracy3.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
</>
)}
{/* 1 3 2 */}
{finalPosition === '1 3 2' && (
<>
{/* #1 */}
<Grid item>
<motion.span layout>
<DancerCard
name={leaderName}
position={finalPosition.substring(0, 1)}
userImage='NRfYKuSKs_o'
danceMove={danceMove}
role='Leader'
handleClickOpen={handleClickOpen2}
accuracy={accuracy.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
{/* #3 */}
<Grid item>
<motion.span layout>
<DancerCard
name={member2Name}
position={finalPosition.substring(4)}
userImage='SFJz9q9EAZc'
danceMove={danceMove3}
role='Member 2'
handleClickOpen={handleClickOpen3}
accuracy={accuracy3.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
{/* #2 */}
<Grid item>
<motion.span layout>
<DancerCard2
name={member1Name}
position={finalPosition.substring(2, 3)}
userImage='OqQi3nCt4CA'
danceMove={danceMove2}
handleClickOpen={handleClickOpen}
accuracy={accuracy2.toFixed(1)}
sync={finalSync}
posAccuracy={posAccuracy.toFixed(1)}
/>
</motion.span>
</Grid>
</>
)}
{/* 2 1 3 */}
{finalPosition === '2 1 3' && (
<>
{/* #2 */}
<Grid item>
<motion.span layout>
<DancerCard2
name={member1Name}
position={finalPosition.substring(2, 3)}
userImage='OqQi3nCt4CA'
danceMove={danceMove2}
handleClickOpen={handleClickOpen}
accuracy={accuracy2.toFixed(1)}
sync={finalSync}
posAccuracy={posAccuracy.toFixed(1)}
/>
</motion.span>
</Grid>
{/* #1 */}
<Grid item>
<motion.span layout>
<DancerCard
name={leaderName}
position={finalPosition.substring(0, 1)}
userImage='NRfYKuSKs_o'
danceMove={danceMove}
role='Leader'
handleClickOpen={handleClickOpen2}
accuracy={accuracy.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
{/* #3 */}
<Grid item>
<motion.span layout>
<DancerCard
name={member2Name}
position={finalPosition.substring(4)}
userImage='SFJz9q9EAZc'
danceMove={danceMove3}
role='Member 2'
handleClickOpen={handleClickOpen3}
accuracy={accuracy3.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
</>
)}
{/* 2 3 1 */}
{finalPosition === '2 3 1' && (
<>
{/* #2 */}
<Grid item>
<motion.span layout>
<DancerCard2
name={member1Name}
position={finalPosition.substring(2, 3)}
userImage='OqQi3nCt4CA'
danceMove={danceMove2}
handleClickOpen={handleClickOpen}
accuracy={accuracy2.toFixed(1)}
sync={finalSync}
posAccuracy={posAccuracy.toFixed(1)}
/>
</motion.span>
</Grid>
{/* #3 */}
<Grid item>
<motion.span layout>
<DancerCard
name={member2Name}
position={finalPosition.substring(4)}
userImage='SFJz9q9EAZc'
danceMove={danceMove3}
role='Member 2'
handleClickOpen={handleClickOpen3}
accuracy={accuracy3.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
{/* #1 */}
<Grid item>
<motion.span layout>
<DancerCard
name={leaderName}
position={finalPosition.substring(0, 1)}
userImage='NRfYKuSKs_o'
danceMove={danceMove}
role='Leader'
handleClickOpen={handleClickOpen2}
accuracy={accuracy.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
</>
)}
{/* 3 1 2 */}
{finalPosition === '3 1 2' && (
<>
{/* #3 */}
<Grid item>
<motion.span layout>
<DancerCard
name={member2Name}
position={finalPosition.substring(4)}
userImage='SFJz9q9EAZc'
danceMove={danceMove3}
role='Member 2'
handleClickOpen={handleClickOpen3}
accuracy={accuracy3.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
{/* #1 */}
<Grid item>
<motion.span layout>
<DancerCard
name={leaderName}
position={finalPosition.substring(0, 1)}
userImage='NRfYKuSKs_o'
danceMove={danceMove}
role='Leader'
handleClickOpen={handleClickOpen2}
accuracy={accuracy.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
{/* #2 */}
<Grid item>
<motion.span layout>
<DancerCard2
name={member1Name}
position={finalPosition.substring(2, 3)}
userImage='OqQi3nCt4CA'
danceMove={danceMove2}
handleClickOpen={handleClickOpen}
accuracy={accuracy2.toFixed(1)}
sync={finalSync}
posAccuracy={posAccuracy.toFixed(1)}
/>
</motion.span>
</Grid>
</>
)}
{/* 3 2 1 */}
{finalPosition === '3 2 1' && (
<>
{/* #3 */}
<Grid item>
<motion.span layout>
<DancerCard
name={member2Name}
position={finalPosition.substring(4)}
userImage='SFJz9q9EAZc'
danceMove={danceMove3}
role='Member 2'
handleClickOpen={handleClickOpen3}
accuracy={accuracy3.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
{/* #2 */}
<Grid item>
<motion.span layout>
<DancerCard2
name={member1Name}
position={finalPosition.substring(2, 3)}
userImage='OqQi3nCt4CA'
danceMove={danceMove2}
handleClickOpen={handleClickOpen}
accuracy={accuracy2.toFixed(1)}
sync={finalSync}
posAccuracy={posAccuracy.toFixed(1)}
/>
</motion.span>
</Grid>
{/* #1 */}
<Grid item>
<motion.span layout>
<DancerCard
name={leaderName}
position='1 2 3'
userImage='NRfYKuSKs_o'
danceMove={danceMove}
role='Leader'
handleClickOpen={handleClickOpen2}
accuracy={accuracy.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
</>
)}
{/* Completed */}
{finalPosition === '' && (
<>
{/* #1 */}
<Grid item>
<motion.span>
<DancerCard
name={leaderName}
position='1 2 3'
userImage='NRfYKuSKs_o'
danceMove='Completed'
role='Leader'
handleClickOpen={handleClickOpen2}
accuracy={accuracy.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
{/* #2 */}
<Grid item>
<motion.span>
<DancerCard2
name={member1Name}
position='1 2 3'
userImage='OqQi3nCt4CA'
danceMove='Completed'
handleClickOpen={handleClickOpen}
accuracy={accuracy2.toFixed(1)}
sync={finalSync}
posAccuracy={posAccuracy.toFixed(1)}
/>
</motion.span>
</Grid>
{/* #3 */}
<Grid item>
<motion.span>
<DancerCard
name={member2Name}
position='1 2 3'
userImage='SFJz9q9EAZc'
danceMove='Completed'
role='Member 2'
handleClickOpen={handleClickOpen3}
accuracy={accuracy3.toFixed(1)}
sync={finalSync}
/>
</motion.span>
</Grid>
</>
)}
</Grid>
<Grid container justify='center'>
<Grid item>
<Button
variant='contained'
color='secondary'
onClick={handleConnection}
className={classes.margin}
>
{connection ? <p>END</p> : <p>START</p>}
</Button>
<Container>
<Modal
showModal={showModal}
setShowModal={setShowModal}
score={score}
setScore={setScore}
maxScore={maxScore}
setMaxScore={setMaxScore}
accuracy={overallAccuracy}
setSyncList={setSyncList}
syncList={syncList}
syncAvg={syncAvg}
posAccuracy={posAccuracy}
/>
</Container>
<Backdrop
className={classes.backdrop}
open={connection ? !socket.connected : false}
>
<CircularProgress color='inherit' />
</Backdrop>
</Grid>
</Grid>
</>
)
}
export default Playground
<file_sep>/frontend/src/pages/Developer.js
import React from 'react'
import PropTypes from 'prop-types'
import { makeStyles } from '@material-ui/core/styles'
import AppBar from '@material-ui/core/AppBar'
import Tabs from '@material-ui/core/Tabs'
import Tab from '@material-ui/core/Tab'
import Typography from '@material-ui/core/Typography'
import Box from '@material-ui/core/Box'
import { Grid } from '@material-ui/core'
import io from 'socket.io-client'
import { useEffect, useState } from 'react'
import {
Line,
LineChart,
XAxis,
YAxis,
Tooltip,
CartesianGrid,
Legend,
} from 'recharts'
import Button from '@material-ui/core/Button'
import Backdrop from '@material-ui/core/Backdrop'
import CircularProgress from '@material-ui/core/CircularProgress'
import IconButton from '@material-ui/core/IconButton'
import { FaPlay, FaPause } from 'react-icons/fa'
import { IconContext } from 'react-icons'
import MuiTooltip from '@material-ui/core/Tooltip'
const socket = io('http://localhost:3000', {
transports: ['websocket', 'polling'],
})
function TabPanel(props) {
const { children, value, index, ...other } = props
return (
<div
role='tabpanel'
hidden={value !== index}
id={`scrollable-auto-tabpanel-${index}`}
aria-labelledby={`scrollable-auto-tab-${index}`}
{...other}
>
{value === index && (
<Box p={3}>
<Typography>{children}</Typography>
</Box>
)}
</div>
)
}
TabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.any.isRequired,
value: PropTypes.any.isRequired,
}
function a11yProps(index) {
return {
id: `scrollable-auto-tab-${index}`,
'aria-controls': `scrollable-auto-tabpanel-${index}`,
}
}
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
width: '100%',
backgroundColor: theme.palette.background.paper,
},
margin: {
margin: theme.spacing(1),
paddingRight: 20,
},
logout: {
margin: theme.spacing(1),
paddingRight: 33,
width: '100px',
},
backdrop: {
zIndex: theme.zIndex.drawer + 1,
color: '#fff',
},
heading: {
fontSize: '4.5em',
letterSpacing: '-1px',
backgroundColor: '#503e9d',
color: 'white',
},
}))
export default function Developer(props) {
const classes = useStyles()
const [value, setValue] = React.useState(0)
const { access } = props
const [data, setData] = useState([])
const [data2, setData2] = useState([])
const [data3, setData3] = useState([])
const [danceMove, setDanceMove] = useState('Dab')
const [danceMove2, setDanceMove2] = useState('Dab')
const [danceMove3, setDanceMove3] = useState('Dab')
const [connection, setConnection] = useState(false)
const [leaderName, setLeaderName] = useState('Leader Name')
const [member1Name, setMember1Name] = useState('Member 1 Name')
const [member2Name, setMember2Name] = useState('Member 2 Name')
const [correctness, setCorrectness] = useState(false)
const handleConnection = () => {
connection ? setConnection(false) : setConnection(true)
console.log('clicked')
}
useEffect(() => {
setLeaderName(localStorage.getItem('leaderName'))
setMember1Name(localStorage.getItem('member1Name'))
setMember2Name(localStorage.getItem('member2Name'))
})
const handleAccess = () => {
access(false)
}
const handleChange = (event, newValue) => {
setValue(newValue)
}
useEffect(() => {
if (connection) {
socket.on('new_data', (newData) => {
console.log(newData.EMG)
setData((currentData) => {
if (currentData.length === 20) {
currentData = currentData.slice(1)
}
return currentData.concat(newData)
})
setDanceMove(newData.danceMove)
})
socket.on('new_data2', (newData2) => {
console.log(newData2.EMG)
setData2((currentData) => {
if (currentData.length === 20) {
currentData = currentData.slice(1)
}
return currentData.concat(newData2)
})
setDanceMove2(newData2.danceMove)
})
socket.on('new_data3', (newData3) => {
console.log(newData3.EMG)
setData3((currentData) => {
if (currentData.length === 20) {
currentData = currentData.slice(1)
}
return currentData.concat(newData3)
})
setDanceMove3(newData3.danceMove)
})
} else {
socket.off('new_data')
socket.off('new_data2')
socket.off('new_data3')
}
}, [connection])
return (
<>
<Grid container justify='center' style={{ marginTop: '-10px' }}>
<Grid item xs={12}>
<Typography variant='h3' align='center' className={classes.heading}>
{' '}
Developer Mode
</Typography>
</Grid>
</Grid>
<div className={classes.root}>
<AppBar position='static' color='default'>
<Tabs
value={value}
onChange={handleChange}
indicatorColor='primary'
textColor='primary'
variant='scrollable'
scrollButtons='auto'
aria-label='scrollable auto tabs example'
>
<Tab label='Member 1' {...a11yProps(0)} />
<Tab label='Leader' {...a11yProps(1)} />
<Tab label='Member 2' {...a11yProps(2)} />
<Tab label='EMG' {...a11yProps(3)} />
<Grid container justify='flex-end'>
<MuiTooltip title='Connect/Disconnect'>
<IconButton
aria-label='connect'
className={classes.margin}
size='large'
onClick={handleConnection}
>
{connection ? (
<IconContext.Provider
value={{ color: 'red', className: 'global-class-name' }}
>
<FaPause size={30} />
</IconContext.Provider>
) : (
<IconContext.Provider
value={{ color: 'green', className: 'global-class-name' }}
>
<FaPlay size={30} />
</IconContext.Provider>
)}
</IconButton>
</MuiTooltip>
<Backdrop
className={classes.backdrop}
open={connection ? !socket.connected : false}
>
<CircularProgress color='inherit' />
</Backdrop>
<Button
variant='contained'
color='secondary'
onClick={handleAccess}
className={classes.logout}
>
Log out
</Button>
</Grid>
</Tabs>
</AppBar>
<TabPanel value={value} index={0}>
<>
<Grid container justify='space-between'>
<Grid item>
<div>
<h1 style={{ color: 'blue' }}>(Left) MPU </h1>
<LineChart width={500} height={300} data={data2}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Accelerometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisMemberOneLeftA'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisMemberOneLeftA'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisMemberOneLeftA'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
<LineChart width={500} height={300} data={data2}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Gyrometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisMemberOneLeftG'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisMemberOneLeftG'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisMemberOneLeftG'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
</div>
</Grid>
<Grid item>
<div>
<h1 style={{ color: 'red' }}>(Right) MPU </h1>
<LineChart width={500} height={300} data={data2}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Accelerometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisMemberOneRightA'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisMemberOneRightA'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisMemberOneRightA'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
<LineChart width={500} height={300} data={data2}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Gyrometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisMemberOneRightG'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisMemberOneRightG'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisMemberOneRightG'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
</div>
</Grid>
</Grid>
</>
</TabPanel>
<TabPanel value={value} index={1}>
<>
<Grid container justify='space-between'>
<Grid item>
<div>
<h1 style={{ color: 'blue' }}>(Left) MPU </h1>
<LineChart width={500} height={300} data={data}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Accelerometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisLeaderLeftA'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisLeaderLeftA'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisLeaderLeftA'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
<LineChart width={500} height={300} data={data}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Gyrometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisLeaderLeftG'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisLeaderLeftG'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisLeaderLeftG'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
</div>
</Grid>
<Grid item>
<div>
<h1 style={{ color: 'red' }}>(Right) MPU </h1>
<LineChart width={500} height={300} data={data}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Accelerometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisLeaderRightA'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisLeaderRightA'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisLeaderRightA'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
<LineChart width={500} height={300} data={data}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Gyrometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisLeaderRightG'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisLeaderRightG'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisLeaderRightG'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
</div>
</Grid>
</Grid>
</>
</TabPanel>
<TabPanel value={value} index={2}>
<>
<Grid container justify='space-between'>
<Grid item>
<div>
<h1 style={{ color: 'blue' }}>(Left) MPU </h1>
<LineChart width={500} height={300} data={data3}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Accelerometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisMemberTwoLeftA'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisMemberTwoLeftA'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisMemberTwoLeftA'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
<LineChart width={500} height={300} data={data3}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Gyrometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisMemberTwoLeftG'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisMemberTwoLeftG'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisMemberTwoLeftG'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
</div>
</Grid>
<Grid item>
<div>
<h1 style={{ color: 'red' }}>(Right) MPU </h1>
<LineChart width={500} height={300} data={data3}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Accelerometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisMemberTwoRightA'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisMemberTwoRightA'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisMemberTwoRightA'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
<LineChart width={500} height={300} data={data3}>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
<Legend />
<XAxis dataKey='time' />
<YAxis
label={{
value: 'Gyrometer',
angle: -90,
position: 'middleLeft',
}}
width={120}
type='number'
domain={[-5000, 5000]}
/>
<Line
name='x'
type='linear'
dataKey='xAxisMemberTwoRightG'
stroke='#820000'
isAnimationActive={false}
/>
<Line
name='y'
type='linear'
dataKey='yAxisMemberTwoRightG'
stroke='#118200'
isAnimationActive={false}
/>
<Line
name='z'
type='linear'
dataKey='zAxisMemberTwoRightG'
stroke='#000982'
isAnimationActive={false}
/>
</LineChart>
</div>
</Grid>
</Grid>
</>
</TabPanel>
<TabPanel value={value} index={3}>
<LineChart
width={500}
height={300}
data={data}
style={{ marginLeft: '350px', marginTop: '120px' }}
>
<CartesianGrid strokeDasharray='3 3' />
<Tooltip />
{/* <Legend /> */}
<XAxis dataKey='time' />
<YAxis
label={{
value: 'EMG',
angle: -90,
position: 'middleLeft',
}}
domain={[-1000, 1000]}
/>
<Line
name='EMG data'
type='linear'
dataKey='EMG'
stroke='#00b339'
isAnimationActive={false}
/>
</LineChart>
</TabPanel>
<TabPanel value={value} index={4}>
Item Five
</TabPanel>
<TabPanel value={value} index={5}>
Item Six
</TabPanel>
<TabPanel value={value} index={6}>
Item Seven
</TabPanel>
</div>
</>
)
}
<file_sep>/frontend/src/components/Cartoon/Cartoon.js
import React from 'react'
import './Cartoon.css'
import FormDialogHome from '../FormDialog/FormDialogHome'
function Cartoon() {
const [open, setOpen] = React.useState(false)
const handleClickOpen = () => {
setOpen(true)
}
const handleClose = () => {
setOpen(false)
}
return (
<>
<FormDialogHome
handleClickOpen={handleClickOpen}
handleClose={handleClose}
open={open}
setOpen={setOpen}
/>
<div className='wrapper' onClick={handleClickOpen}>
<div className='border-circle' id='one' />
<div className='border-circle' id='two' />
<div className='background-circle'>
<div className='triangle-light' />
<div className='body' />
<span className='shirt-text'>D</span>
<span className='shirt-text'>♥</span>
<span className='shirt-text'>N</span>
<span className='shirt-text'>C</span>
<span className='shirt-text'>E</span>
<div className='triangle-dark' />
</div>
<div className='head'>
<div id='SpeechBubble'>I'm a rectangle</div>
<div className='ear' id='left' />
<div className='ear' id='right' />
<div className='hair-main'>
<div className='sideburn' id='left' />
<div className='sideburn' id='right' />
<div className='hair-top' />
</div>
<div className='face'>
<div className='hair-bottom' />
<div className='nose' />
<div className='eye-shadow' id='left'>
<div className='eyebrow' />
<div className='eye' />
</div>
<div className='eye-shadow' id='right'>
<div className='eyebrow' />
<div className='eye' />
</div>
<div className='mouth' />
<div className='shadow-wrapper'>
<div className='shadow' />
</div>
</div>
</div>
<span className='music-note' id='one'>
♫
</span>
<span className='music-note' id='two'>
♪
</span>
</div>
</>
)
}
export default Cartoon
<file_sep>/README.md
# CG4002 AY2020/2021 Semester 2 B11-Dashboard
## Home Page

Home page is where the user will be brought to when they visit our danceboard.
## Playground Page

The Playground page is where the user will most interact with.
## Dancebase

As the name implies, Dancebase is a database of dance moves. It consists of all the dance moves available.
## Progress Page

Progress page is where all the offline analytics data(Fig 5.2.2.3) will be stored and displayed in graphical form.
## **Developer Mode Page**

The developer mode is a page specially designed for our system’s developer. It displays data that the developers are most interested in. Nevertheless, this page is protected with a password that only the developer would know.


## **Overall Software Architecture**
****
Instruction to run:
1. Clone from github
2. Extract it and open up your terminal
3. cd into that folder
4. cd into frontend and type "npm install"
5. After that, type "npm start" to run frontend
For backend,
1. Download PyCharm (Recommended) and use it to open dashboard_database folder
2. Use PyCharm and run main.py file (This pushes random data into database on mongodb atlas)
3. Then open a new terminal and cd into backend folder
4. type "npm install"
5. Then type "npm run"
Password to access developer mode is <PASSWORD><file_sep>/frontend/src/components/VideoCarousel/VideoCarousel.js
import React from 'react'
import Carousel from 'react-elastic-carousel'
import Item from './Item'
import './VideoCarousel.css'
import ReactPlayer from 'react-player'
import BarChart from '../BarChart/BarChart'
import { useState, useEffect } from 'react'
import Tooltip from '@material-ui/core/Tooltip'
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles'
const defaultTheme = createMuiTheme()
const theme = createMuiTheme({
overrides: {
MuiTooltip: {
tooltip: {
fontSize: '2em',
color: 'white',
backgroundColor: '#503e9d',
},
arrow: {
fontSize: 20,
color: '#4A4A4A',
'&::before': {
backgroundColor: '#503e9d',
},
},
},
},
})
const breakPoints = [
{ width: 1, itemsToShow: 1 },
{ width: 550, itemsToShow: 2 },
{ width: 768, itemsToShow: 3 },
{ width: 1200, itemsToShow: 4 },
]
function VideoCarousel() {
const [elbowKickCount, setElbowKickCount] = useState(0)
const [dabCount, setDabCount] = useState(0)
const [gunCount, setGunCount] = useState(0)
const [hairCount, setHairCount] = useState(0)
const [listenCount, setListenCount] = useState(0)
const [pointHighCount, setPointHighCount] = useState(0)
const [sidePumpCount, setSidePumpCount] = useState(0)
const [wipeTableCount, setWipeTableCount] = useState(0)
const increaseElbowKickCount = () => {
setElbowKickCount((prevCount) => {
const newCount = Number(prevCount) + 1
localStorage.setItem('elbowKickCount', newCount)
return newCount
})
}
const increaseDabCount = () => {
setDabCount((prevCount) => {
const newCount = Number(prevCount) + 1
localStorage.setItem('dabCount', newCount)
return newCount
})
}
const increaseGunCount = () => {
setGunCount((prevCount) => {
const newCount = Number(prevCount) + 1
localStorage.setItem('gunCount', newCount)
return newCount
})
}
const increaseHairCount = () => {
setHairCount((prevCount) => {
const newCount = Number(prevCount) + 1
localStorage.setItem('hairCount', newCount)
return newCount
})
}
const increaseListenCount = () => {
setListenCount((prevCount) => {
const newCount = Number(prevCount) + 1
localStorage.setItem('listenCount', newCount)
return newCount
})
}
const increasePointHighCount = () => {
setPointHighCount((prevCount) => {
const newCount = Number(prevCount) + 1
localStorage.setItem('pointHighCount', newCount)
return newCount
})
}
const increaseSidePumpCount = () => {
setSidePumpCount((prevCount) => {
const newCount = Number(prevCount) + 1
localStorage.setItem('sidePumpCount', newCount)
return newCount
})
}
const increaseWipeTableCount = () => {
setWipeTableCount((prevCount) => {
const newCount = Number(prevCount) + 1
localStorage.setItem('wipeTableCount', newCount)
return newCount
})
}
useEffect(() => {
const elbowKickValue = localStorage.getItem('elbowKickCount')
if (elbowKickValue) setElbowKickCount(elbowKickValue)
const dabValue = localStorage.getItem('dabCount')
if (dabValue) setDabCount(dabValue)
const gunValue = localStorage.getItem('gunCount')
if (gunValue) setGunCount(gunValue)
const hairValue = localStorage.getItem('hairCount')
if (hairValue) setHairCount(hairValue)
const listenValue = localStorage.getItem('listenCount')
if (listenValue) setListenCount(listenValue)
const pointHighValue = localStorage.getItem('pointHighCount')
if (pointHighValue) setPointHighCount(pointHighValue)
const sidePumpValue = localStorage.getItem('sidePumpCount')
if (sidePumpValue) setSidePumpCount(sidePumpValue)
const wipeTableValue = localStorage.getItem('wipeTableCount')
if (wipeTableValue) setWipeTableCount(wipeTableValue)
}, [])
return (
<>
<MuiThemeProvider theme={defaultTheme}>
<div className='videocarousel'>
<Carousel breakPoints={breakPoints} itemPadding={[10, 10]}>
<MuiThemeProvider theme={theme}>
<Tooltip title='Elbow Kick' arrow>
<Item>
<ReactPlayer
url='https://www.youtube.com/embed/19GptZzhhjM'
onEnded={increaseElbowKickCount}
/>{' '}
</Item>
</Tooltip>
</MuiThemeProvider>
<MuiThemeProvider theme={theme}>
<Tooltip title='Dab' arrow>
<Item>
<ReactPlayer
url='https://www.youtube.com/embed/hPFdDhZzwKM'
onEnded={increaseDabCount}
/>{' '}
</Item>
</Tooltip>
</MuiThemeProvider>
<MuiThemeProvider theme={theme}>
<Tooltip title='Gun' arrow>
<Item>
<ReactPlayer
url='https://www.youtube.com/embed/l1ApsUn-6Pw'
onEnded={increaseGunCount}
/>{' '}
</Item>
</Tooltip>
</MuiThemeProvider>
<MuiThemeProvider theme={theme}>
<Tooltip title='Hair' arrow>
<Item>
<ReactPlayer
url='https://www.youtube.com/embed/0Mp4zz-33Ow'
onEnded={increaseHairCount}
/>{' '}
</Item>
</Tooltip>
</MuiThemeProvider>
<MuiThemeProvider theme={theme}>
<Tooltip title='Listen' arrow>
<Item>
<ReactPlayer
url='https://www.youtube.com/embed/Kx3pUsL0hyo'
onEnded={increaseListenCount}
/>{' '}
</Item>
</Tooltip>
</MuiThemeProvider>
<MuiThemeProvider theme={theme}>
<Tooltip title='Point High' arrow>
<Item>
<ReactPlayer
url='https://www.youtube.com/embed/WMoRZ0K7qFw'
onEnded={increasePointHighCount}
/>{' '}
</Item>
</Tooltip>
</MuiThemeProvider>
<MuiThemeProvider theme={theme}>
<Tooltip title='Side Pump' arrow>
<Item>
<ReactPlayer
url='https://www.youtube.com/embed/CDT-FrxOqXw'
onEnded={increaseSidePumpCount}
/>{' '}
</Item>
</Tooltip>
</MuiThemeProvider>
<MuiThemeProvider theme={theme}>
<Tooltip title='Wipe Table' arrow>
<Item>
<ReactPlayer
url='https://www.youtube.com/embed/iTQs6-rYasY'
onEnded={increaseWipeTableCount}
/>{' '}
</Item>
</Tooltip>
</MuiThemeProvider>
</Carousel>
</div>
</MuiThemeProvider>
<BarChart
elbowKickCount={elbowKickCount}
dabCount={dabCount}
gunCount={gunCount}
hairCount={hairCount}
listenCount={listenCount}
pointHighCount={pointHighCount}
sidePumpCount={sidePumpCount}
wipeTableCount={wipeTableCount}
/>
</>
)
}
export default VideoCarousel
<file_sep>/frontend/src/components/CollapsibleTable/CollapsibleTable.js
import React from 'react'
import PropTypes from 'prop-types'
import { makeStyles } from '@material-ui/core/styles'
import Box from '@material-ui/core/Box'
import Collapse from '@material-ui/core/Collapse'
import IconButton from '@material-ui/core/IconButton'
import Table from '@material-ui/core/Table'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableContainer from '@material-ui/core/TableContainer'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import Typography from '@material-ui/core/Typography'
import Paper from '@material-ui/core/Paper'
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown'
import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp'
const useRowStyles = makeStyles({
root: {
'& > *': {
borderBottom: 'unset',
},
},
})
function createData(rank, name, points) {
return {
rank,
name,
points,
history: [
{ date: '2020-01-05', accuracy: '50%', syncDelay: 3, score: '10' },
{ date: '2020-01-02', accuracy: '80%', syncDelay: 1, score: '5' },
],
}
}
function Row(props) {
const { row } = props
const [open, setOpen] = React.useState(false)
const classes = useRowStyles()
return (
<React.Fragment>
<TableRow className={classes.root}>
<TableCell>
<IconButton
aria-label='expand row'
size='small'
onClick={() => setOpen(!open)}
>
{open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
</IconButton>
</TableCell>
<TableCell component='th' scope='row' align='left'>
{row.rank}
</TableCell>
<TableCell align='center'> {row.name}</TableCell>
<TableCell align='center'>{row.points}</TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
<Collapse in={open} timeout='auto' unmountOnExit>
<Box margin={1} style={{ backgroundColor: '#a9a9a9' }}>
<Typography variant='h6' gutterBottom component='div'>
Dance History
</Typography>
<Table size='small' aria-label='purchases'>
<TableHead style={{ backgroundColor: '#cffcfc' }}>
<TableRow>
<TableCell>Date</TableCell>
<TableCell>Accuracy</TableCell>
<TableCell align='right'>Sync Delay</TableCell>
<TableCell align='right'>Score</TableCell>
</TableRow>
</TableHead>
<TableBody style={{ backgroundColor: '#3f6641' }}>
{row.history.map((historyRow) => (
<TableRow key={historyRow.date}>
<TableCell component='th' scope='row'>
{historyRow.date}
</TableCell>
<TableCell>{historyRow.accuracy}</TableCell>
<TableCell align='right'>
{historyRow.syncDelay}
</TableCell>
<TableCell align='right'>{historyRow.score}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</Collapse>
</TableCell>
</TableRow>
</React.Fragment>
)
}
Row.propTypes = {
row: PropTypes.shape({
rank: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
points: PropTypes.number.isRequired,
history: PropTypes.arrayOf(
PropTypes.shape({
amount: PropTypes.number.isRequired,
customerId: PropTypes.string.isRequired,
date: PropTypes.string.isRequired,
})
).isRequired,
}).isRequired,
}
const rows = [
createData(1, 'Jack', 6.0),
createData(2, 'May', 9.0),
createData(3, 'Yuki', 16.0),
createData(4, 'Ben', 3.7),
createData(5, 'Chris', 16.0),
]
export default function CollapsibleTable() {
return (
<TableContainer component={Paper}>
<Table aria-label='collapsible table'>
<TableHead style={{ backgroundColor: '#fc00f4' }}>
<TableRow>
<TableCell />
<TableCell align='left'>Rank</TableCell>
<TableCell align='center'>Name </TableCell>
<TableCell align='center'>Points </TableCell>
</TableRow>
</TableHead>
<TableBody style={{ backgroundColor: '#ffd5ad' }}>
{rows.map((row) => (
<Row key={row.name} row={row} />
))}
</TableBody>
</Table>
</TableContainer>
)
}
<file_sep>/frontend/src/components/LineChart/LineChart.js
import React, { useState, useEffect } from 'react'
import { Line } from 'react-chartjs-2'
const LineChart = ({ data, text, label, borderColor, time }) => {
const [lineData, setLineData] = useState({})
console.log(data)
const lineChart = () => {
setLineData({
labels: time,
datasets: [
{
label: label,
fill: false,
lineTension: 0.5,
backgroundColor: '#96a3ff',
borderColor: borderColor,
borderWidth: 2,
data: data,
},
],
})
}
useEffect(() => {
lineChart()
}, [])
return (
<div style={{ width: '100%' }}>
<Line
data={lineData}
options={{
title: {
display: true,
text: text,
fontSize: 20,
},
legend: {
display: true,
position: 'right',
},
}}
/>
</div>
)
}
export default LineChart
<file_sep>/dashboard_database/main.py
# This file tests if the sending to the database is ok. (Data format and connection)
# runboth commands
# pip3 install pymongo
# pip3 install pymongo[srv]
import pymongo
import random
from datetime import datetime
import time
# from sshtunnel import SSHTunnelForwarder
def connectToDatabase():
connection_string = 'mongodb+srv://qianjie:19930927QJ@cluster0.6fcdx.mongodb.net/dummy?ssl=true&ssl_cert_reqs=CERT_NONE'
client = pymongo.MongoClient(connection_string)
return client
# For dancer 1
def sendToCollectionDatas(client, msg):
db = client.get_database('dummy')
collection = db.datas
collection.insert_one(msg)
# For dancer 2
def sendToCollectionDatas2(client, msg):
db = client.get_database('dummy')
collection = db.datas2
collection.insert_one(msg)
# For dancer 3
def sendToCollectionDatas3(client, msg):
db = client.get_database('dummy')
collection = db.datas3
collection.insert_one(msg)
# For evaluated answer
def sendToCollectionDatas4(client, msg):
db = client.get_database('dummy')
collection = db.datas4
collection.insert_one(msg)
# the code below will be placed somewhere in the main program on the ultra96
# at some point, the connection to database will be made
# at some point, the connection made will be used to send data to the database.
# this means some processing has to happen somewhere, such that depending on the type of data,
# the database knows what to update.
# First create connection to database based on connection string.
# Then based on whether the data is coming from dancer1,2,3 or evaluation answer, insert it to the respective collection in the database.
# Note that only dancer_1 has the physical emg connected. So for dancer_2 and _3, the insertion do not include emg field.
# dance_move for the dancer refers to the dance move that the ml predicts that repective dancer is dancing.
# dance_move for the evaluation answer is the most common dance_move out of all 3 dancers.
def main():
client = connectToDatabase()
print("Connected to database - ", client)
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # simulate gyro and acceleration xyz left and right
danceMove1 = ["Hair", "Gun", "ElbowKick", "Wipe-Table", "Side-Pump"]
danceMove2 = ["Hair", "Gun", "ElbowKick", "Wipe-Table", "Side-Pump"]
danceMove3 = ["Hair", "Gun", "ElbowKick", "Wipe-Table", "Side-Pump"]
# list3 = [[1,2,3],[1,3,2],[2,1,3],[2,3,1], [3,1,2], [3,2,1]]
list3 = ["1 2 3", "1 3 2", "2 1 3", "2 3 1", "3 1 2", "3 2 1", ""]
# New data to be sent over to database
while True:
a = random.choice(list1)
b = random.choice(list1)
c = random.choice(list1)
send_time = str(datetime.now())[11:19]
dance_move1 = random.choice(danceMove1)
dance_move2 = random.choice(danceMove2)
dance_move3 = random.choice(danceMove3)
final_dance_move = random.choice([dance_move1, dance_move2, dance_move3])
final_position = random.choice(list3)
final_delay = round(random.uniform(0, 1), 4)
data_to_send_a = f"{a},{b},{c},{a},{b},{c},{a},{b},{c},{a},{b},{c},{send_time},{a},{dance_move1}"
data_to_send_b = f"{b},{c},{a},{b},{c},{a},{b},{c},{a},{b},{c},{a},{send_time},{b},{dance_move2}"
data_to_send_c = f"{c},{b},{a},{c},{b},{a},{c},{b},{a},{c},{b},{a},{send_time},{c},{dance_move3}"
data_to_send_eval = f"{final_dance_move},{final_position},{final_delay}"
split_data_a = data_to_send_a.split(',')
print(split_data_a)
split_data_b = data_to_send_b.split(',')
print(split_data_b)
split_data_c = data_to_send_c.split(',')
print(split_data_c)
split_data_eval = data_to_send_eval.split(',')
print(split_data_eval)
a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15 = split_data_a
b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15 = split_data_b
c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15 = split_data_c
d1, d2, d3 = split_data_eval
data_to_send_datas = {
# Required Datas
"xAxisLeaderLeftA": a1,
"yAxisLeaderLeftA": a2,
"zAxisLeaderLeftA": a3,
"xAxisLeaderLeftG": a4,
"yAxisLeaderLeftG": a5,
"zAxisLeaderLeftG": a6,
"xAxisLeaderRightA": a7,
"yAxisLeaderRightA": a8,
"zAxisLeaderRightA": a9,
"xAxisLeaderRightG": a10,
"yAxisLeaderRightG": a11,
"zAxisLeaderRightG": a12,
"time": a13,
"EMG": a14,
"danceMove": a15,
# # Below data can be dummy for week9
# "position": [1, 2, 3],
# "accuracy": 100,
# "sync": 1.5
}
data_to_send_datas2 = {
# Required Datas
"xAxisMemberOneLeftA": b1,
"yAxisMemberOneLeftA": b2,
"zAxisMemberOneLeftA": b3,
"xAxisMemberOneLeftG": b4,
"yAxisMemberOneLeftG": b5,
"zAxisMemberOneLeftG": b6,
"xAxisMemberOneRightA": b7,
"yAxisMemberOneRightA": b8,
"zAxisMemberOneRightA": b9,
"xAxisMemberOneRightG": b10,
"yAxisMemberOneRightG": b11,
"zAxisMemberOneRightG": b12,
"time": b13,
# "EMG": a14,
"danceMove": b15,
# # Below data can be dummy for week9
# # "position": [1, 2, 3],
# "accuracy": 100,
# "sync": 1.5
}
data_to_send_datas3 = {
# Required Datas
"xAxisMemberTwoLeftA": c1,
"yAxisMemberTwoLeftA": c2,
"zAxisMemberTwoLeftA": c3,
"xAxisMemberTwoLeftG": c4,
"yAxisMemberTwoLeftG": c5,
"zAxisMemberTwoLeftG": c6,
"xAxisMemberTwoRightA": c7,
"yAxisMemberTwoRightA": c8,
"zAxisMemberTwoRightA": c9,
"xAxisMemberTwoRightG": c10,
"yAxisMemberTwoRightG": c11,
"zAxisMemberTwoRightG": c12,
"time": c13,
# "EMG": a14,
"danceMove": c15,
# # Below data can be dummy for week9
# "position": [1, 2, 3],
# "accuracy": 100,
# "sync": 1.5
}
data_to_send_datas4 = {
# # Required Datas
# "xAxisMemberTwoLeftA": c1,
# "yAxisMemberTwoLeftA": c2,
# "zAxisMemberTwoLeftA": c3,
# "xAxisMemberTwoLeftG": c4,
# "yAxisMemberTwoLeftG": c5,
# "zAxisMemberTwoLeftG": c6,
# "xAxisMemberTwoRightA": c7,
# "yAxisMemberTwoRightA": c8,
# "zAxisMemberTwoRightA": c9,
# "xAxisMemberTwoRightG": c10,
# "yAxisMemberTwoRightG": c11,
# "zAxisMemberTwoRightG": c12,
# "time": c13,
# # "EMG": a14,
# "danceMove": c15,
# Below data can be dummy for week9
"finalDanceMove": d1,
"finalPosition": d2,
# "accuracy": 100,
"finalSync": d3
}
print("Sending to database for Dancer 1 - ", data_to_send_datas)
sendToCollectionDatas(client, data_to_send_datas)
print("Sent to datas!")
print("Sending to database for Dancer 2 - ", data_to_send_datas2)
sendToCollectionDatas2(client, data_to_send_datas2)
print("Sent to datas2!")
print("Sending to database for Dancer 3 - ", data_to_send_datas3)
sendToCollectionDatas3(client, data_to_send_datas3)
print("Sent to datas3!")
print("Sending to database for Final Eval - ", data_to_send_datas4)
sendToCollectionDatas4(client, data_to_send_datas4)
print("Sent to datas4!")
time.sleep(2) # 0.05s to simulate 20hz
if __name__ == '__main__':
main()
<file_sep>/frontend/src/pages/Dancebase.js
import React from 'react'
import { Grid, makeStyles, Typography } from '@material-ui/core'
import VideoCarousel from '../components/VideoCarousel/VideoCarousel'
const useStyles = makeStyles((theme) => ({
heading: {
fontSize: '4.5em',
letterSpacing: '-1px',
backgroundColor: '#503e9d',
color: 'white',
},
}))
function Dancebase() {
const classes = useStyles()
return (
<Grid container justify='center' style={{ marginTop: '-10px' }}>
<Grid item xs={12}>
<Typography variant='h3' align='center' className={classes.heading}>
{' '}
Dance Base
</Typography>
<VideoCarousel />
</Grid>
</Grid>
)
}
export default Dancebase
<file_sep>/frontend/src/components/Sidebar/SidebarData.js
import React from 'react'
import { FaPlayCircle } from 'react-icons/fa'
import { GiProgression } from 'react-icons/gi'
import { ImDatabase } from 'react-icons/im'
import { MdDeveloperBoard } from 'react-icons/md'
export const SidebarData = [
{
path: '/playground',
icon: <FaPlayCircle size='2x' />,
className: 'sidebar-icon tooltip ',
toolTipText: 'Dance Ground',
},
{
path: '/dancebase',
icon: <ImDatabase size='2x' />,
className: 'sidebar-icon tooltip ',
toolTipText: 'Dance Base',
},
{
path: '/progress',
icon: <GiProgression size='2x' />,
className: 'sidebar-icon tooltip ',
toolTipText: 'Progress',
},
{
path: '/developer',
icon: <MdDeveloperBoard size='2x' />,
className: 'sidebar-icon tooltip ',
toolTipText: 'Dev Mode',
},
]
<file_sep>/frontend/src/components/Modal/Modal.js
import React, { useRef, useEffect, useCallback } from 'react'
import { useSpring, animated } from 'react-spring'
import styled from 'styled-components'
import { MdClose } from 'react-icons/md'
import { Link } from 'react-router-dom'
import { useState } from 'react'
import Grid from '@material-ui/core/Grid'
const Background = styled.div`
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
position: fixed;
display: flex;
justify-content: center;
align-items: center;
`
const ModalWrapper = styled.div`
width: 800px;
height: 500px;
box-shadow: 0 5px 16px rgba(0, 0, 0, 0.2);
background: #fff;
color: #000;
display: grid;
grid-template-columns: 1fr 1fr;
position: relative;
z-index: 10;
border-radius: 10px;
`
const ModalImg = styled.img`
width: 100%;
height: 100%;
border-radius: 10px 0 0 10px;
background: #000;
`
const ModalContentLeft = styled.div`
display: flex;
flex-direction: column;
justify-content: flexstart;
align-items: center;
line-height: 1.8;
color: #141414;
p {
margin-bottom: 1rem;
}
button {
padding: 10px 24px;
background: #141414;
color: #fff;
border: none;
}
`
const ModalContentRight = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
line-height: 1.8;
color: #141414;
p {
margin-bottom: 1rem;
}
button {
padding: 10px 24px;
background: #141414;
color: #fff;
border: none;
}
`
const CloseModalButton = styled(MdClose)`
cursor: pointer;
position: absolute;
top: 20px;
right: 20px;
width: 32px;
height: 32px;
padding: 0;
z-index: 10;
`
export const Modal = ({
showModal,
setShowModal,
score,
setScore,
maxScore,
setMaxScore,
accuracy,
syncAvg,
posAccuracy,
}) => {
const modalRef = useRef()
const animation = useSpring({
config: {
duration: 250,
},
opacity: showModal ? 1 : 0,
transform: showModal ? `translateY(0%)` : `translateY(-100%)`,
})
const closeModal = (e) => {
if (modalRef.current === e.target) {
setScore(0)
setMaxScore(0)
setShowModal(false)
setSaveStatus(false)
}
}
const closeModalWithCross = () => {
setScore(0)
setMaxScore(0)
setShowModal(false)
setSaveStatus(false)
}
const [saveStatus, setSaveStatus] = React.useState(false)
const [oneScore, setOneScore] = useState(localStorage.getItem('oneScore'))
const [twoScore, setTwoScore] = useState(localStorage.getItem('twoScore'))
const [threeScore, setThreeScore] = useState(
localStorage.getItem('threeScore')
)
const [fourScore, setFourScore] = useState(localStorage.getItem('fourScore'))
const [fiveScore, setFiveScore] = useState(localStorage.getItem('fiveScore'))
const [sixScore, setSixScore] = useState(localStorage.getItem('sixScore'))
const [sevenScore, setSevenScore] = useState(
localStorage.getItem('sevenScore')
)
const [eightScore, setEightScore] = useState(
localStorage.getItem('eightScore')
)
const [nineScore, setNineScore] = useState(localStorage.getItem('nineScore'))
const [tenScore, setTenScore] = useState(localStorage.getItem('tenScore'))
const [accuracyDatas, setAccuracyDatas] = useState(
JSON.parse(localStorage.getItem('accuracyDatas'))
)
const [syncDatas, setSyncDatas] = useState(
JSON.parse(localStorage.getItem('syncDatas'))
)
const [time, setTime] = useState(JSON.parse(localStorage.getItem('time')))
const [flag, setFlag] = useState(true)
const increaseOneScore = () => {
setOneScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('oneScore', newScore)
return newScore
})
}
const increaseTwoScore = () => {
setTwoScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('twoScore', newScore)
return newScore
})
}
const increaseThreeScore = () => {
setThreeScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('threeScore', newScore)
return newScore
})
}
const increaseFourScore = () => {
setFourScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('fourScore', newScore)
return newScore
})
}
const increaseFiveScore = () => {
setFiveScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('fiveScore', newScore)
return newScore
})
}
const increaseSixScore = () => {
setSixScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('sixScore', newScore)
return newScore
})
}
const increaseSevenScore = () => {
setSevenScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('sevenScore', newScore)
return newScore
})
}
const increaseEightScore = () => {
setEightScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('eightScore', newScore)
return newScore
})
}
const increaseNineScore = () => {
setNineScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('nineScore', newScore)
return newScore
})
}
const increaseTenScore = () => {
setTenScore((prevScore) => {
const newScore = Number(prevScore) + 1
localStorage.setItem('tenScore', newScore)
return newScore
})
}
const keyPress = useCallback(
(e) => {
if (e.key === 'Escape' && showModal) {
setShowModal(false)
setScore(0)
console.log('I pressed')
}
},
[setShowModal, showModal]
)
const handleSaveButton = (e) => {
setSaveStatus(true)
if (Math.floor(accuracy.toFixed(0) / 10) === 1) {
increaseOneScore()
} else if (Math.floor(accuracy.toFixed(0) / 10) === 2) {
increaseTwoScore()
} else if (Math.floor(accuracy.toFixed(0) / 10) === 3) {
increaseThreeScore()
} else if (Math.floor(accuracy.toFixed(0) / 10) === 4) {
increaseFourScore()
} else if (Math.floor(accuracy.toFixed(0) / 10) === 5) {
increaseFiveScore()
} else if (Math.floor(accuracy.toFixed(0) / 10) === 6) {
increaseSixScore()
} else if (Math.floor(accuracy.toFixed(0) / 10) === 7) {
increaseSevenScore()
} else if (Math.floor(accuracy.toFixed(0) / 10) === 8) {
increaseEightScore()
} else if (Math.floor(accuracy.toFixed(0) / 10) === 9) {
increaseNineScore()
} else if (Math.floor(accuracy.toFixed(0) / 10) === 10) {
increaseTenScore()
}
setAccuracyDatas((oldDatas) => [...oldDatas, Math.floor(accuracy)])
localStorage.setItem('accuracyDatas', JSON.stringify(accuracyDatas))
setSyncDatas((oldDatas) => [...oldDatas, syncAvg.toFixed(4)])
localStorage.setItem('syncDatas', JSON.stringify(syncDatas))
setTime((oldDatas) => [...oldDatas, new Date().toLocaleTimeString()])
localStorage.setItem('time', JSON.stringify(time))
}
useEffect(() => {
document.addEventListener('keydown', keyPress)
return () => document.removeEventListener('keydown', keyPress)
}, [keyPress])
return (
<>
{showModal ? (
<Background onClick={closeModal} ref={modalRef}>
<animated.div style={animation}>
<ModalWrapper showModal={showModal}>
<ModalContentLeft style={{ justifyContent: 'center' }}>
<Grid container direction='column'>
<Grid item xs={12}>
<h1>Position Accuracy</h1>
<p>{Math.floor(posAccuracy.toFixed(1))}%</p>
</Grid>
<Grid item xs={12}>
<h1>Team Accuracy</h1>
<p>{Math.floor(accuracy.toFixed(1))}%</p>
</Grid>
<Grid item xs={12}>
<h1>Overall Sync</h1>
<p>{syncAvg.toFixed(4)}ms</p>
</Grid>
<Grid item xs={12}>
<h1>Team Score</h1>
<p>{Math.floor(accuracy.toFixed(0) / 10)}</p>
</Grid>
</Grid>
<button onClick={handleSaveButton}>Save</button>
<p>{saveStatus ? 'saved!' : ''}</p>
</ModalContentLeft>
<ModalContentRight>
<div>
{accuracy > 80 ? (
<h1>You are doing great! Keep it up!</h1>
) : accuracy > 50 ? (
<h1>Practice more! You can be better</h1>
) : (
<h1>Do not give up! You can do it!</h1>
)}
<p>Tips: Watch video tutorial to improve further!</p>
<Link to='/dancebase'>
<button>Watch Now</button>
</Link>
</div>
</ModalContentRight>
<CloseModalButton
aria-label='Close modal'
onClick={closeModalWithCross}
/>
</ModalWrapper>
</animated.div>
</Background>
) : null}
</>
)
}
<file_sep>/frontend/src/pages/Home.js
import React from 'react'
import { Grid, Typography } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import Cartoon from '../components/Cartoon/Cartoon'
import SpeechBubble from '../components/SpeechBubble/SpeechBubble'
import './Home.css'
const useStyles = makeStyles((theme) => ({
root: {},
heading: {
fontSize: '4.5em',
letterSpacing: '-1px',
backgroundColor: '#503e9d',
color: 'white',
},
cartoon: {
marginTop: '100px',
},
}))
function Home() {
const classes = useStyles()
return (
<>
<div class='bg'></div>
<div class='bg bg2'></div>
<div class='bg bg3'></div>
<Grid container justify='center' style={{ marginTop: '-10px' }}>
<Grid item xs={12}>
<Typography variant='h3' align='center' className={classes.heading}>
{' '}
Welcome to Dance Dance
</Typography>
</Grid>
</Grid>
<Grid container justify='center'>
<Grid item>
<SpeechBubble type='h1' message='Click me!' />
</Grid>
</Grid>
<Grid container justify='center' className={classes.cartoon}>
<Cartoon />
</Grid>
</>
)
}
export default Home
<file_sep>/backend/models/dummy_data.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const dummyDataSchema = new Schema({
xAxis: { type: Number, required: true },
yAxis: { type: Number, required: true },
zAxis: { type: Number, required: true },
danceMove: { type: String, required: true },
position: [{ type: Number, required: true }],
})
module.exports = mongoose.model('DummyData', dummyDataSchema)
<file_sep>/backend/models/data.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const DataSchema = new Schema({
// Member 1 Left
xAxisMemberOneLeftA: { type: Number, required: true },
yAxisMemberOneLeftA: { type: Number, required: true },
zAxisMemberOneLeftA: { type: Number, required: true },
xAxisMemberOneLeftG: { type: Number, required: true },
yAxisMemberOneLeftG: { type: Number, required: true },
zAxisMemberOneLeftG: { type: Number, required: true },
// Member 1 Right
xAxisMemberOneRightA: { type: Number, required: true },
yAxisMemberOneRightA: { type: Number, required: true },
zAxisMemberOneRightA: { type: Number, required: true },
xAxisMemberOneRightG: { type: Number, required: true },
yAxisMemberOneRightG: { type: Number, required: true },
zAxisMemberOneRightG: { type: Number, required: true },
// Leader Left
xAxisLeaderLeftA: { type: Number, required: true },
yAxisLeaderLeftA: { type: Number, required: true },
zAxisLeaderLeftA: { type: Number, required: true },
xAxisLeaderLeftG: { type: Number, required: true },
yAxisLeaderLeftG: { type: Number, required: true },
zAxisLeaderLeftG: { type: Number, required: true },
// Leader Right
xAxisLeaderRightA: { type: Number, required: true },
yAxisLeaderRightA: { type: Number, required: true },
zAxisLeaderRightA: { type: Number, required: true },
xAxisLeaderRightG: { type: Number, required: true },
yAxisLeaderRightG: { type: Number, required: true },
zAxisLeaderRightG: { type: Number, required: true },
// Member 2 Left
xAxisMemberTwoLeftA: { type: Number, required: true },
yAxisMemberTwoLeftA: { type: Number, required: true },
zAxisMemberTwoLeftA: { type: Number, required: true },
xAxisMemberTwoLeftG: { type: Number, required: true },
yAxisMemberTwoLeftG: { type: Number, required: true },
zAxisMemberTwoLeftG: { type: Number, required: true },
// Member 2 Right
xAxisMemberTwoRightA: { type: Number, required: true },
yAxisMemberTwoRightA: { type: Number, required: true },
zAxisMemberTwoRightA: { type: Number, required: true },
xAxisMemberTwoRightG: { type: Number, required: true },
yAxisMemberTwoRightG: { type: Number, required: true },
zAxisMemberTwoRightG: { type: Number, required: true },
// EMG
xAxisEMG: { type: Number, required: true },
yAxisEMG: { type: Number, required: true },
zAxisEMG: { type: Number, required: true },
time: { type: String, required: true },
danceMove: { type: String, required: true },
position: [{ type: Number, required: true }],
accuracy: { type: Number, required: true },
sync: { type: Number, required: true },
})
module.exports = mongoose.model('Data', DataSchema)
<file_sep>/frontend/src/components/BarChart/BarChartScore.js
import React from 'react'
import { Bar, defaults } from 'react-chartjs-2'
defaults.global.tooltips.enabled = false
const BarChartScore = (props) => {
return (
<div>
<Bar
data={{
labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
datasets: [
{
label: 'Scores',
data: [
props.oneScore,
props.twoScore,
props.threeScore,
props.fourScore,
props.fiveScore,
props.sixScore,
props.sevenScore,
props.eightScore,
props.nineScore,
props.tenScore,
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(110, 110, 110, 0.2)',
'rgba(0, 201, 54, 0.2)',
'rgba(0, 11, 54, 0.2)',
'rgba(0, 11, 200, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(110, 110, 110, 1)',
'rgba(0, 201, 54, 1)',
'rgba(0, 11, 54, 1)',
'rgba(0, 11, 200, 1)',
],
borderWidth: 1,
},
],
}}
height={400}
width={600}
options={{
maintainAspectRatio: false,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
title: {
display: true,
position: 'top',
fontStyle: 'bold',
fontSize: 16,
padding: 30,
text: 'Team Score',
},
legend: {
display: false,
},
}}
/>
</div>
)
}
export default BarChartScore
<file_sep>/frontend/src/components/SpeechBubble/SpeechBubble.js
import React from 'react'
import './SpeechBubble.css'
import Typography from '@material-ui/core/Typography'
function SpeechBubble(props) {
return (
<>
<div className='speech-bubble'>
<Typography variant={props.type}>{props.message}</Typography>
</div>
</>
)
}
export default SpeechBubble
<file_sep>/frontend/src/components/BarChart/BarChart.js
import React from 'react'
import { Bar, defaults } from 'react-chartjs-2'
defaults.global.tooltips.enabled = false
const BarChart = (props) => {
return (
<div>
<Bar
data={{
labels: [
'Elbow Kick',
'Dab',
'Gun',
'Hair',
'Listen',
'Point High',
'Side Pump',
'Wipe Table',
],
datasets: [
{
label: 'View count of all the dance move',
data: [
props.elbowKickCount,
props.dabCount,
props.gunCount,
props.hairCount,
props.listenCount,
props.pointHighCount,
props.sidePumpCount,
props.wipeTableCount,
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(110, 110, 110, 0.2)',
'rgba(0, 201, 54, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(110, 110, 110, 1)',
'rgba(0, 201, 54, 1)',
],
borderWidth: 1,
},
],
}}
height={400}
width={600}
options={{
maintainAspectRatio: false,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
title: {
display: true,
position: 'top',
fontStyle: 'bold',
fontSize: 16,
padding: 30,
text: 'View Counts Of Each Dance Move',
},
legend: {
display: false,
},
}}
/>
</div>
)
}
export default BarChart
<file_sep>/backend/routes/authenticate-route.js
const express = require('express')
const authenticateControllers = require('../controllers/authenticate-controller')
const router = express.Router()
router.post('/', authenticateControllers.validatePassword)
module.exports = router
<file_sep>/backend/controllers/authenticate-controller.js
const express = require('express')
const passwordData = require('../models/password')
const ID = '60350e0fc4d3baa9bc8b89cc'
const validatePassword = async (req, res, next) => {
const passwordObj = await passwordData.find({})
let passwordDB = passwordObj[0].password
let password = parseInt(req.body.password)
if (password === <PASSWORD>) {
res.json(true)
} else {
res.json(false)
}
}
exports.validatePassword = validatePassword
| cc7b060ad5988914166996fe4dfef8fd3574d9d6 | [
"JavaScript",
"Python",
"Markdown"
] | 22 | JavaScript | qjie7/cg4002-dashboard | f142a5d1e30d657042e04d8639e2c70b157955aa | 3000540a031e52be301143c50290a910b9cd7cca |
refs/heads/master | <repo_name>AngelMagdalena/InternetStoreCourseWork<file_sep>/DAL/EF/Entities/DbProduct.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace DAL.EF.Entities
{
public class DbProduct
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public string Code { get; set; }
[MaxLength(20)]
public int Size { get; set; }
[MaxLength(20)]
public string Colour { get; set; }
[Required]
[MaxLength(50)]
public string Material { get; set; }
[MaxLength(50)]
public string Brend { get; set; }
[MaxLength(50)]
public string Season { get; set; }
public int CountOrder { get; set; }
// Ссылка на автора
public int UserID { get; set; }
public DbUser User { get; set; }
// Ссылка на подкатегорию
public int SubCategoryID { get; set; }
public DbSubCategory SubCategory { get; set; }
public DateTime DatePublication { get; set; }
[DataType(DataType.Currency)]
public decimal Price { get; set; }
}
}
<file_sep>/BLL/Entities/SubCategory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Entities
{
public class SubCategory:AbstractCategory
{
public SubCategory()
{
Products = new List<Product>();
}
public override int ID { get; set; }
public override string Name { get; set; }
public int CategoryID { get; set; }
public MainCategory Category { get; set; }
public virtual ICollection<Product> Products { get; set; }
public override string ToString()
{
return Name;
}
}
}
<file_sep>/BLL/Entities/Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Entities
{
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public string Code { get; set; }
public int Size { get; set; }
public string Colour { get; set; }
public string Material { get; set; }
public string Brend { get; set; }
public string Season { get; set; }
public int CountOrder { get; set; }
public int AuthorID { get; set; }
public User Author { get; set; }
public int SubCategoryID { get; set; }
public SubCategory SubCategory { get; set; }
public DateTime DatePublication { get; set; }
public decimal Price { get; set; }
}
}
<file_sep>/DAL/EF/Entities/DbMainCategory.cs
using System.Collections.Generic;
namespace DAL.EF.Entities
{
public class DbMainCategory : DbAbstractCategory
{
public DbMainCategory()
{
SubCategorys = new List<DbSubCategory>();
}
public override int ID { get; set; }
//[RegularExpression(pattern: @"^[A-ZА-ЯЪ]+[a-zа-яъA-ZА-ЯЪ\-\s]*$", ErrorMessage = "Название должно быть с большой буквы, и может содержать только буквы, пробелы,тире")]
public override string Name { get; set; }
// Ссылка на подкатегории
public ICollection<DbSubCategory> SubCategorys { get; set; }
}
}
<file_sep>/DAL/EF/Entities/DbSubCategory.cs
using System.Collections.Generic;
namespace DAL.EF.Entities
{
public class DbSubCategory : DbAbstractCategory
{
public DbSubCategory()
{
Products = new List<DbProduct>();
}
public override int ID { get; set; }
//[RegularExpression(pattern: @"^[A-ZА-ЯЪ]+[a-zа-яъA-ZА-ЯЪ\-\s]*$", ErrorMessage = "Название должно быть с большой буквы, и может содержать только буквы, пробелы,тире")]
public override string Name { get; set; }
// Ссылка на категорию
public int CategoryID { get; set; }
public DbMainCategory Category { get; set; }
// Ссылка на заказы
public virtual ICollection<DbProduct> Products { get; set; }
}
}
<file_sep>/BLL/Entities/User.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Entities
{
public class User
{
public int ID { get; set; }
public int UserGroupID { get; set; }
public UserGroup UserGroup { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public decimal Money { get; set; }
public virtual ICollection<Product> AuctionProducts { get; set; }
public virtual ICollection<Product> BoughtProducts { get; set; }
public virtual ICollection<Product> AddedProducts { get; set; }
public override string ToString()
{
return Name;
}
}
}
<file_sep>/DAL/EF/Entities/Abstract/DbAbstractCategory.cs
namespace DAL.EF.Entities
{
public abstract class DbAbstractCategory
{
public abstract int ID { get; set; }
public abstract string Name { get; set; }
}
}
<file_sep>/BLL/Manager/SubCategoryManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Interfaces;
using BLL.Entities;
using DAL.EF.Entities;
using Ninject;
using DAL.EF.Interfaces;
using AutoMapper;
using DAL;
namespace BLL.Manager
{
public class SubCategoryManager:ISubCategoryManager
{
IKernel ninject;
IUnitOfWork Db;
public SubCategoryManager()
{
ninject = new StandardKernel();
ninject.Bind<IUnitOfWork>().To<UnitOfWork>();
Db = ninject.Get<IUnitOfWork>();
}
public SubCategoryManager(IUnitOfWork _db)
{
Db = _db;
}
public bool CheckTitle(string title)
{
IEnumerable<DbSubCategory> categories = Db.SubCategorys.GetAll();
foreach (DbSubCategory c in categories)
{
if (c.Name == title) return true;
}
return false;
}
public void CreateSubCategory(SubCategory item, MainCategory m_cat)
{
MainCategory category = Mapper.Map<DbMainCategory, MainCategory>(Db.MainCategorys.GetItem(m_cat.ID));
var newSubCat = new DbSubCategory()
{
Name = item.Name,
Category = Db.MainCategorys.GetItem(m_cat.ID),
CategoryID = m_cat.ID
};
Db.SubCategorys.Create(newSubCat);
category.SubCategorys.Add(item);
Db.SubCategorys.Update(newSubCat);
Db.Save();
}
public void Dispose()
{
Db.Dispose();
}
public void EditSubCategory(SubCategory item, MainCategory m_cat)
{
var newSubCategory = new DbSubCategory()
{
Name = item.Name,
Category = Db.MainCategorys.GetItem(m_cat.ID),
CategoryID = m_cat.ID
};
Db.MainCategorys.Update(Db.MainCategorys.GetItem(item.CategoryID));
Db.SubCategorys.Update(newSubCategory);
Db.Save();
}
public List<SubCategory> GetAllSubCategories()
{
return Mapper.Map<IEnumerable<DbSubCategory>, List<SubCategory>>(Db.SubCategorys.GetAll());
}
public SubCategory GetSubCategory(int id)
{
return Mapper.Map<DbSubCategory, SubCategory>(Db.SubCategorys.GetItem(id));
}
public void RemoveSubCategory(int id)
{
SubCategory sub_cat = Mapper.Map<DbSubCategory, SubCategory>(Db.SubCategorys.GetItem(id));
if (sub_cat == null)
{
throw new ArgumentNullException();
}
MainCategory main_cat = Mapper.Map<DbMainCategory, MainCategory>(Db.MainCategorys.GetItem(sub_cat.CategoryID));
main_cat.SubCategorys.Remove(sub_cat);
Db.MainCategorys.Update(Db.MainCategorys.GetItem(sub_cat.CategoryID));
Db.SubCategorys.Delete(id);
}
}
}
}
<file_sep>/DAL/Repository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using DAL.EF;
using DAL.EF.Interfaces;
namespace DAL
{
class Repository<Type> : IRepository<Type>
where Type : class
{
private StoreContext db;
private bool disposed = false;
public Repository()
{
this.db = new StoreContext();
}
public virtual IEnumerable<Type> Get()
{
return db.Set<Type>().AsNoTracking().ToList();
}
public virtual IEnumerable<Type> GetAll()
{
IQueryable<Type> query = db.Set<Type>();
return query.ToList();
}
public Type GetItem(int ID)
{
Type item = db.Set<Type>().Find(ID);
if (item != null)
{
return item;
}
else
{
throw new ArgumentNullException();
}
}
public void Create(Type item)
{
db.Set<Type>().Add(item);
Save();
}
public void Update(Type item)
{
db.Entry(item).State = EntityState.Modified;
}
public void Delete(int ID)
{
Type item = db.Set<Type>().Find(ID);
if (item != null)
{
db.Set<Type>().Remove(item);
}
}
public void Save()
{
db.SaveChanges();
}
private void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
db.Dispose();
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public IEnumerable<Type> Find(Func<Type, Boolean> predicate)
{
return db.Set<Type>().Where(predicate).ToList();
}
}
}
<file_sep>/DAL/EF/Interfaces/IUnitOfWork.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL.EF.Entities;
namespace DAL.EF.Interfaces
{
public interface IUnitOfWork : IDisposable
{
IRepository<DbProduct> Products { get; }
IRepository<DbSubCategory> SubCategorys { get; }
IRepository<DbMainCategory> MainCategorys { get; }
IRepository<DbUserGroup> UserGroups { get; }
IRepository<DbUser> Users { get; }
void Save();
}
}
<file_sep>/BLL/Entities/UserGroup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Entities
{
public class UserGroup
{
public UserGroup()
{
Users = new List<User>();
}
public int ID { get; set; }
public string Name { get; set; }
public int Access { get; set; }
public virtual ICollection<User> Users { get; set; }
public override string ToString()
{
return Name;
}
}
}
<file_sep>/BLL/Interfaces/IUserManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Entities;
namespace BLL.Interfaces
{
public interface IUserManager
{
void CreateUser(User user, UserGroup user_group);
void EditUser(User user);
void RemoveUser(int id);
bool CheckUser(string login, string password);
User GetUser(int id);
bool Buying(Product Product, int user_id);
bool Reserving(Product Product, int user_id);
void Dispose();
}
}
<file_sep>/BLL/Manager/ProductManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Entities;
using BLL.Interfaces;
using Ninject;
using DAL;
using DAL.EF;
using DAL.EF.Interfaces;
using DAL.EF.Entities;
using AutoMapper;
using System.Text.RegularExpressions;
namespace BLL.Manager
{
public class ProductManager:IProductManager
{
string regexp = (@"^/d{6}$");
IKernel ninject;
IUnitOfWork Db;
public ProductManager()
{
ninject = new StandardKernel();
ninject.Bind<IUnitOfWork>().To<UnitOfWork>();
Db = ninject.Get<IUnitOfWork>();
}
public ProductManager(IUnitOfWork _db)
{
Db = _db;
}
public void CreateProduct(Product product, User user, SubCategory sub_cat)
{
SubCategory category = Mapper.Map<DbSubCategory, SubCategory>(Db.SubCategorys.GetItem(sub_cat.ID));
var newProduct = new DbProduct()
{
Name = product.Name,
Size = product.Size,
Photo = product.Photo,
Colour = product.Colour,
Material = product.Material,
Brend = product.Brend,
Season = product.Season,
Price = product.Price,
SubCategory = Db.SubCategorys.GetItem(sub_cat.ID),
SubCategoryID = sub_cat.ID
};
Db.Products.Create(newProduct);
category.Products.Add(product);
Db.Products.Update(newProduct);
Db.Save();
}
public void RemoveProduct(int id)
{
Product product = Mapper.Map<DbProduct, Product>(Db.Products.GetItem(id));
if (product == null)
{
throw new ArgumentNullException();
}
SubCategory category = Mapper.Map<DbSubCategory, SubCategory>(Db.SubCategorys.GetItem(product.SubCategoryID));
category.Products.Remove(product);
Db.SubCategorys.Update(Db.SubCategorys.GetItem(product.SubCategoryID));
Db.Products.Delete(id);
}
public bool CheckCode(string code)
{
IEnumerable<DbProduct> products = Db.Products.GetAll();
if (Regex.IsMatch(code, regexp))
{
foreach (DbProduct p in products)
{
if (p.Code == code) return true;
}
}
return false;
}
public void Dispose()
{
Db.Dispose();
}
public void EditProduct(Product product, SubCategory sub_cat)
{
var newProduct = new DbProduct()
{
Name = product.Name,
Size = product.Size,
Photo = product.Photo,
Colour = product.Colour,
Material = product.Material,
Brend = product.Brend,
Season = product.Season,
Price = product.Price,
SubCategory = Db.SubCategorys.GetItem(sub_cat.ID),
SubCategoryID = sub_cat.ID
};
Db.SubCategorys.Update(Db.SubCategorys.GetItem(product.SubCategoryID));
Db.Products.Update(newProduct);
Db.Save();
}
public List<Product> Filter(IEnumerable<Product> Products, Product Product)
{
List<Product> prod = new List<Product>();
foreach (Product p in Products)
{
if (p == Product)
prod.Add(p);
}
return prod;
}
public List<Product> GetAllProducts()
{
return Mapper.Map<IEnumerable<DbProduct>, List<Product>>(Db.Products.GetAll());
}
public Product GetProduct(int id)
{
return Mapper.Map<DbProduct, Product>(Db.Products.GetItem(id));
}
}
}
}
}
<file_sep>/BLL/Interfaces/IProductManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Entities;
namespace BLL.Interfaces
{
public interface IProductManager
{
void CreateProduct(Product product, User author, SubCategory sub_category);
void EditProduct(Product product, SubCategory sub_cat);
void RemoveProduct(int id);
bool CheckCode(string code);
Product GetProduct(int id);
List<Product> Filter(IEnumerable<Product> Products, Product Product);
List<Product> GetAllProducts();
void Dispose();
}
}
<file_sep>/BLL/Manager/UserGroupManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Entities;
using BLL.Interfaces;
using Ninject;
using DAL;
using DAL.EF.Entities;
using DAL.EF.Interfaces;
using AutoMapper;
namespace BLL.Manager
{
public class UserGroupManager:IUserGroupManager
{
IKernel ninject;
IUnitOfWork Db;
public UserGroupManager()
{
ninject = new StandardKernel();
ninject.Bind<IUnitOfWork>().To<UnitOfWork>();
Db = ninject.Get<IUnitOfWork>();
}
public UserGroupManager(IUnitOfWork _db)
{
Db = _db;
}
public void CreateUserGroup(UserGroup user_group)
{
UserGroup u_group = Mapper.Map<DbUserGroup, UserGroup>(Db.UserGroups.GetItem(user_group.ID));
var newUserGroup = new DbUserGroup()
{
Name = user_group.Name,
Access = user_group.Access
};
Db.UserGroups.Create(newUserGroup);
Db.Save();
}
public void Dispose()
{
Db.Dispose();
}
public void EditUserGroup(UserGroup user_group)
{
var newUserGroup = new DbUserGroup()
{
Name = user_group.Name,
Access = user_group.Access
};
Db.UserGroups.Update(newUserGroup);
Db.Save();
}
public UserGroup GetUserGroup(int id)
{
return Mapper.Map<DbUserGroup, UserGroup>(Db.UserGroups.GetItem(id));
}
public void RemoveUserGroup(int id)
{
UserGroup user_group = Mapper.Map<DbUserGroup, UserGroup>(Db.UserGroups.GetItem(id));
if (user_group == null)
{
throw new ArgumentNullException();
}
Db.UserGroups.Delete(id);
}
}
}
}
<file_sep>/BLL/Manager/UserManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Entities;
using BLL.Interfaces;
using Ninject;
using DAL;
using DAL.EF;
using DAL.EF.Interfaces;
using DAL.EF.Entities;
using AutoMapper;
using System.Text.RegularExpressions;
namespace BLL.Manager
{
public class UserManager : IUserManager
{
IKernel ninject;
IUnitOfWork Db;
public UserManager()
{
ninject = new StandardKernel();
ninject.Bind<IUnitOfWork>().To<UnitOfWork>();
Db = ninject.Get<IUnitOfWork>();
}
public bool Buying(Product Product, int user_id)
{
throw new NotImplementedException();
}
public bool CheckUser(string login, string password)
{
throw new NotImplementedException();
}
public void CreateUser(User user, UserGroup user_group)
{
/*
UserGroup usergroup = Mapper.Map<DbUserGroup, UserGroup>(Db.UserGroups.GetItem(user_group.ID));
SubCategory category = Mapper.Map<DbSubCategory, SubCategory>(Db.SubCategorys.GetItem(sub_cat.ID));
var newUser = new DbUser()
{
Name = user.Name;
};
Db.Products.Create(newProduct);
category.Products.Add(product);
Db.Products.Update(newProduct);
Db.Save();
*/
}
public void Dispose()
{
Db.Dispose();
}
public void EditUser(User user)
{
throw new NotImplementedException();
}
public User GetUser(int id)
{
return Mapper.Map<DbUser, User>(Db.Users.GetItem(id));
}
public void RemoveUser(int id)
{
User user = Mapper.Map<DbUser, User>(Db.Users.GetItem(id));
if (user == null)
{
throw new ArgumentNullException();
}
UserGroup group = Mapper.Map<DbUserGroup, UserGroup>(Db.UserGroups.GetItem(user.UserGroupID));
group.Users.Remove(user);
Db.Users.Delete(id);
}
public bool Reserving(Product Product, int user_id)
{
throw new NotImplementedException();
}
}
}
<file_sep>/BLL/Interfaces/ISubCategoryManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Entities;
namespace BLL.Interfaces
{
public interface ISubCategoryManager
{
void CreateSubCategory(SubCategory item, MainCategory parent);
bool CheckTitle(string title);
void RemoveSubCategory(int id);
void EditSubCategory(SubCategory item, MainCategory parent);
List<SubCategory> GetAllSubCategories();
SubCategory GetSubCategory(int id);
void Dispose();
}
}
<file_sep>/BLL/Interfaces/IUserGroupManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Entities;
namespace BLL.Interfaces
{
public interface IUserGroupManager
{
void CreateUserGroup(UserGroup user_group);
void EditUserGroup(UserGroup user_group);
void RemoveUserGroup(int id);
UserGroup GetUserGroup(int id);
void Dispose();
}
}
<file_sep>/DAL/EF/Context/StoreContext.cs
using System.Data.Entity;
using DAL.EF.Entities;
namespace DAL.EF
{
public class StoreContext : DbContext
{
public StoreContext() : base("IStore")
{ }
public StoreContext(string connectString) : base(connectString)
{
Database.SetInitializer<StoreContext>(new StoreDbInitializer());
}
public DbSet<DbUser> Users { get; set; }
public DbSet<DbUserGroup> UserGroups { get; set; }
public DbSet<DbProduct> Products { get; set; }
public DbSet<DbMainCategory> MainCategorys { get; set; }
public DbSet<DbSubCategory> SubCategorys { get; set; }
// Переопределяем метод OnModelCreating для добавления
// настроек конфигурации
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Entity<User>().HasAlternateKey(user => user.).HasName("AlternateKey_LicensePlate");
modelBuilder.Configurations.Add(new SubCutegoryConfiguration());
modelBuilder.Configurations.Add(new MainCategoryConfiguration());
modelBuilder.Configurations.Add(new ProductConfiguration());
modelBuilder.Configurations.Add(new UserGroupConfiguration());
modelBuilder.Configurations.Add(new UserConfiguration());
}
public class StoreDbInitializer : DropCreateDatabaseAlways<StoreContext>
{
protected override void Seed(StoreContext db)
{
}
}
}
}<file_sep>/BLL/Entities/AbstractCategory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Entities
{
public abstract class AbstractCategory
{
public abstract int ID { get; set; }
public abstract string Name { get; set; }
}
}
<file_sep>/BLL/Infrastructure/MapperConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using BLL.Entities;
using DAL.EF.Entities;
namespace BLL.Infrastructure
{
public class MapperConfig
{
public static void Initialize()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<DbProduct, Product>();
cfg.CreateMap<DbSubCategory, SubCategory>();
cfg.CreateMap<DbMainCategory, MainCategory>();
cfg.CreateMap<DbUserGroup, UserGroup>();
cfg.CreateMap<DbUser, User>();
});
}
}
}
<file_sep>/DAL/EF/Interfaces/IRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.EF.Interfaces
{
public interface IRepository<Type> : IDisposable
where Type : class
{
IEnumerable<Type> GetAll();
Type GetItem(int ID);
void Create(Type item);
void Update(Type item);
void Delete(int ID);
void Save();
IEnumerable<Type> Find(Func<Type, Boolean> predicate);
}
}
<file_sep>/DAL/EF/Entities/DbUser.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace DAL.EF.Entities
{
public class DbUser
{
public int ID { get; set; }
// Ссылка на групу
public int UserGroupID { get; set; }
public DbUserGroup UserGroup { get; set; }
//[RegularExpression(pattern: @"^[A-ZА-ЯЪ]+[a-zа-яъA-ZА-ЯЪ\-\s]*$", ErrorMessage = "Имя должно быть с большой буквы, и может содержать только буквы, пробелы,тире")]
public string Name { get; set; }
//[RegularExpression(pattern: @"^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$", ErrorMessage = "E-mail может содержать только буквы, цифры, символы _, -, ., +")]
public string Email { get; set; }
//[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Currency)]
public decimal Money { get; set; }
// Ссылка на заказы
public virtual ICollection<DbProduct> Products { get; set; }
}
}
<file_sep>/BLL/Entities/MainCategory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Entities
{
public class MainCategory:AbstractCategory
{
public MainCategory()
{
SubCategorys = new List<SubCategory>();
}
public override int ID { get; set; }
public override string Name { get; set; }
public ICollection<SubCategory> SubCategorys { get; set; }
public override string ToString()
{
return Name;
}
}
}
<file_sep>/DAL/EF/Entities/DbUserGroup.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace DAL.EF.Entities
{
public class DbUserGroup
{
public DbUserGroup()
{
Users = new List<DbUser>();
}
public int ID { get; set; }
//[RegularExpression(pattern: @"^[A-ZА-ЯЪ]+[a-zа-яъA-ZА-ЯЪ\-\s]*$", ErrorMessage = "Название должно быть с большой буквы, и может содержать только буквы, пробелы,тире")]
public string Name { get; set; }
[Range(0, 3)]
public int Access { get; set; }
// Ссылка на пользователей
public virtual ICollection<DbUser> Users { get; set; }
}
}
<file_sep>/DAL/EF/Context/StoreConfigurations.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using DAL.EF.Entities;
namespace DAL.EF
{
// Настройки для SubCutegory
public class SubCutegoryConfiguration : EntityTypeConfiguration<DbSubCategory>
{
public SubCutegoryConfiguration()
{
this.HasKey(prop => prop.ID);
this.Property(prop => prop.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(prop => prop.Name)
.IsRequired()
.HasMaxLength(60)
.HasColumnType("varchar");
this.HasMany(scat => scat.Products)
.WithRequired(scat => scat.SubCategory)
.HasForeignKey(scat => scat.SubCategoryID);
this.ToTable("SubCategory");
}
}
// Настройки для MainCategory
public class MainCategoryConfiguration : EntityTypeConfiguration<DbMainCategory>
{
public MainCategoryConfiguration()
{
this.HasKey(prop => prop.ID);
this.Property(prop => prop.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(prop => prop.Name)
.IsRequired()
.HasMaxLength(60)
.HasColumnType("varchar");
this.HasMany(mcat => mcat.SubCategorys)
.WithRequired(mcat => mcat.Category)
.HasForeignKey(mcat => mcat.CategoryID);
this.ToTable("Category");
}
}
// Настройки для Product
public class ProductConfiguration : EntityTypeConfiguration<DbProduct>
{
public ProductConfiguration()
{
this.HasKey(prop => prop.ID);
this.Property(prop => prop.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(prop => prop.Name)
.IsRequired()
.HasMaxLength(60)
.HasColumnType("varchar");
this.Property(prop => prop.Code)
.IsRequired()
.HasMaxLength(5)
.HasColumnType("varchar");
this.Property(prop => prop.Size)
.IsRequired()
.HasColumnType("int");
this.Property(prop => prop.Colour)
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar");
this.Property(prop => prop.Material)
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar");
this.Property(prop => prop.Brend)
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar");
this.Property(prop => prop.Season)
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar");
this.Property(prop => prop.CountOrder)
.IsRequired()
.HasColumnType("int");
this.Property(prop => prop.Photo)
.HasColumnType("image");
this.Property(prop => prop.DatePublication)
.IsRequired()
.HasColumnType("datetime");
this.Property(prop => prop.Price)
.IsRequired();
this.ToTable("Product");
}
}
// Настройки для UserGroup
public class UserGroupConfiguration : EntityTypeConfiguration<DbUserGroup>
{
public UserGroupConfiguration()
{
this.HasKey(prop => prop.ID);
this.Property(prop => prop.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.HasMany(ugroup => ugroup.Users)
.WithRequired(ugroup => ugroup.UserGroup)
.HasForeignKey(ugroup => ugroup.UserGroupID);
this.Property(prop => prop.Name)
.IsRequired()
.HasMaxLength(60)
.HasColumnType("varchar");
this.Property(prop => prop.Access).IsRequired();
this.ToTable("UserGroup");
}
}
// Настройки для User
public class UserConfiguration : EntityTypeConfiguration<DbUser>
{
public UserConfiguration()
{
this.HasKey(prop => prop.ID);
this.Property(prop => prop.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(prop => prop.Name)
.IsRequired()
.HasMaxLength(60)
.HasColumnType("varchar");
this.Property(prop => prop.Email)
.IsRequired()
.HasMaxLength(60)
.HasColumnType("varchar");
this.Property(prop => prop.Password)
.IsRequired()
.HasColumnType("varchar");
this.ToTable("User");
}
}
}
<file_sep>/BLL/Manager/MainCategoryManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Interfaces;
using BLL.Entities;
using DAL.EF.Entities;
using Ninject;
using DAL.EF.Interfaces;
using AutoMapper;
using DAL;
namespace BLL.Manager
{
public class MainCategoryManager:IMainCategoryManager
{
IKernel ninject;
IUnitOfWork Db { get; set; }
public MainCategoryManager()
{
ninject = new StandardKernel();
ninject.Bind<IUnitOfWork>().To<UnitOfWork>();
Db = ninject.Get<IUnitOfWork>();
}
public MainCategoryManager(IUnitOfWork _db)
{
Db = _db;
}
public bool CheckTitle(string title)
{
IEnumerable<DbMainCategory> categories = Db.MainCategorys.GetAll();
foreach (DbMainCategory cat in categories)
{
return (cat.Name == title);
}
return false;
}
public void CreateMainCategory(MainCategory m_cat)
{
if (m_cat == null)
{
throw new ArgumentNullException();
}
DbMainCategory new_m_cat = new DbMainCategory
{
Name = m_cat.Name
};
Db.MainCategorys.Create(new_m_cat);
}
public void Dispose()
{
Db.Dispose();
}
public void EditMainCategory(MainCategory entity)
{
if (entity == null)
{
throw new ArgumentNullException();
}
DbMainCategory tmp = new DbMainCategory
{
Name = entity.Name
};
Db.MainCategorys.Update(tmp);
Db.Save();
}
public List<MainCategory> GetAllMainCategories()
{
return Mapper.Map<IEnumerable<DbMainCategory>, List<MainCategory>>(Db.MainCategorys.GetAll());
}
public MainCategory GetMainCategory(int id)
{
return Mapper.Map<DbMainCategory, MainCategory>(Db.MainCategorys.GetItem(id));
}
public void RemoveMainCategory(int id)
{
DbMainCategory m_cat = Db.MainCategorys.GetItem(id);
if (m_cat == null)
{
throw new ArgumentNullException();
}
Db.SubCategorys.Delete(id);
foreach (DbSubCategory s_cat in m_cat.SubCategorys)
{
s_cat.Category = null;
s_cat.CategoryID = -1;
}
Db.Save();
}
}
}
}
<file_sep>/DAL/UnitOfWork.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL.EF;
using DAL.EF.Interfaces;
using DAL.EF.Entities;
namespace DAL
{
public class UnitOfWork : IUnitOfWork, IDisposable
{
private StoreContext db;
private Repository<DbProduct> products;
private Repository<DbSubCategory> sub_categorys;
private Repository<DbMainCategory> main_categorys;
private Repository<DbUserGroup> user_groups;
private Repository<DbUser> users;
private bool disposed = false;
public UnitOfWork(string connectString)
{
db = new StoreContext(connectString);
}
public UnitOfWork()
{
db = new StoreContext("Auction");
}
public IRepository<DbProduct> Products
{
get
{
if (products == null)
{
products = new Repository<DbProduct>();
}
return products;
}
}
public IRepository<DbSubCategory> SubCategorys
{
get
{
if (sub_categorys == null)
{
sub_categorys = new Repository<DbSubCategory>();
}
return sub_categorys;
}
}
public IRepository<DbMainCategory> MainCategorys
{
get
{
if (main_categorys == null)
{
main_categorys = new Repository<DbMainCategory>();
}
return main_categorys;
}
}
public IRepository<DbUserGroup> UserGroups
{
get
{
if (user_groups == null)
{
user_groups = new Repository<DbUserGroup>();
}
return user_groups;
}
}
public IRepository<DbUser> Users
{
get
{
if (users == null)
{
users = new Repository<DbUser>();
}
return users;
}
}
public void Save()
{
db.SaveChanges();
}
private void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
db.Dispose();
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
<file_sep>/BLL/Infrastructure/ServiceModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject.Modules;
using DAL;
using DAL.EF.Interfaces;
namespace BLL.Infrastructure
{
public class ServiceModule:NinjectModule
{
private string connectString;
public ServiceModule() { }
public ServiceModule(string connectStr)
{
connectString = connectStr;
}
public override void Load()
{
Bind<IUnitOfWork>().To<UnitOfWork>().WithConstructorArgument(connectString);
}
}
}
<file_sep>/BLL/Interfaces/IMainCategoryManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Entities;
namespace BLL.Interfaces
{
public interface IMainCategoryManager
{
void CreateMainCategory(MainCategory m_cat);
bool CheckTitle(string title);
void RemoveMainCategory(int id);
void EditMainCategory(MainCategory entity);
List<MainCategory> GetAllMainCategories();
MainCategory GetMainCategory(int id);
void Dispose();
}
}
| 0696dd29b44de6bc7e577a4ee25e3ab3f02e55e9 | [
"C#"
] | 30 | C# | AngelMagdalena/InternetStoreCourseWork | cbf960ee9ad838440c02cb109816942dbcf6b4db | b8f88d79ce1f42a7e83ee3945b2cd173c3494889 |
refs/heads/master | <repo_name>jessicachakmlee/FlashCards<file_sep>/frontend/src/App.js
import React, {Component} from 'react';
import styled from 'styled-components';
import {Link, Route, Switch} from "react-router-dom";
//components
import QuestionList from './components/QuestionList';
import AddQuestion from './components/AddQuestion.js';
import AddCategory from './components/AddCategory.js';
import QuestionAnswerGenerator from './components/QuestionAnswerGenerator.js';
import CategoriesList from "./components/CategoriesList";
const Banner = styled.div`
width: 100%;
height: 100px;
background-image: url('https://wikitravel.org/upload/shared//6/6a/Default_Banner.jpg');
font-size: 80px;
color: white;
font-family: Almendra Display;
text-transform: uppercase;
text-align: center;
margin: 10px;
`;
const CategoryQuestionDiv = styled.div`
display: flex;
justify-content: space-around;
`;
const StyledCategoryLink = styled(Link)`
margin: 20px;
background-color: cornflowerblue;
color: white;
font-size: 16px;
font-weight: 700;
width: 25%;
text-align: center;
border-radius: 2px;
border: 1px solid black;
text-decoration: none;
padding: 10px
:hover {
background: skyblue;
}
:focus{
outline: 0px solid transparent;
}
`;
const StyledQuestionLink = styled(Link)`
margin: 20px;
background-color: #8FBC8F;
color: white;
font-size: 16px;
font-weight: 700;
width: 25%;
text-align: center;
border-radius: 2px;
border: 1px solid black;
text-decoration: none;
align-self: center;
padding: 10px
:hover {
background: yellowgreen;
}
:focus{
outline: 0px solid transparent;
}
`;
class App extends Component {
render() {
return (
<div>
<CategoryQuestionDiv>
<StyledCategoryLink to={'/addCategories'}>Add Categories</StyledCategoryLink>
<StyledQuestionLink to={'/addQuestions'}>Add Questions</StyledQuestionLink>
</CategoryQuestionDiv>
<Banner>FlashCards</Banner>
<QuestionAnswerGenerator/>
<Banner>Questions List</Banner>
<QuestionList/>
<Banner>Categories List</Banner>
<CategoriesList />
<Switch>
<Route exact path="/addCategories" component={AddCategory}/>
<Route exact path="/addQuestions" component={AddQuestion}/>
</Switch>
</div>
)
}
}
export default App;
<file_sep>/frontend/src/components/AddQuestion.js
import React, {Component} from "react";
import styled from 'styled-components';
import {graphql, compose} from 'react-apollo';
import {getCategoriesQuery, addQuestionMutation, getQuestionsQuery} from "../queries/queries";
const OverlayWrapper = styled.div`
position: fixed;
top: 0px;
left: 0px;
z-index: 2001;
width: 100%;
height: 100%;
box-shadow: rgba(0, 0, 0, 0.25) 0px 0px 60px 20px;
display: flex;
-webkit-box-align: center;
align-items: center;
background: rgba(0, 0, 0, 0.5);
`;
const OverlaySpan = styled.span`
margin: 0px auto;
:before {
content:'x';
font-size: 22px;
font-weight: 800;
color: white;
position: relative;
top: 0;
right: -612px;
}
`;
const ContentDiv = styled.div`
max-width: calc(90%);
box-shadow: rgba(0, 0, 0, 0.25) 0px 0px 60px 20px;
transform: scale(1);
display: flex;
flex-direction: column;
max-height: calc(100vh - 50px);
background: white;
margin: 0px auto;
padding: 40px;
overflow: auto;
`;
const QuestionSubmissionDiv = styled.div`
display: flex;
flex-direction: column;
`;
const QuestionSubmissionTitle = styled.h2`
text-align: center;
border: 1px solid;
background: darkseagreen;
`;
const QSubmissionForm = styled.form`
display: flex;
height: auto;
width: auto;
flex-direction: column;
border: 3px dashed darkseagreen;
padding: 10px;
align-self: center;
margin: 0 10px 20px 10px;
width: 500px;
`;
const QAlabel = styled.label`
flex: 1;
`;
const QSubmissiontextarea = styled.textarea`
flex: 4;
margin-bottom: 10px;
`;
const QSelect = styled.select`
width: 25%;
height: auto;
margin: 10px 0;
`;
const InputDiv = styled.div`
margin-top: 10px;
align-self: flex-end;
`;
const StyledInput = styled.input`
background: darkseagreen;
width: 100px;
height: 25px;
:hover {
background: yellowgreen;
}
:focus{
outline: 0px solid transparent;
}
`;
class AddQuestion extends Component {
constructor(props) {
super(props);
this.state = {
TextAreaQuestion: "",
TextAreaAnswer: "",
categoryId: null
}
}
displayCategories = () => {
let data = this.props.getCategoriesQuery;
if (data.loading) {
return <option disabled>Loading Categories</option>
} else {
return data.categories.map(category =>
<option key={category.id} value={category.id}>{category.name}</option>
)
}
};
handleChangeQuestion = (event) => {
this.setState({
TextAreaQuestion: event.target.value
})
};
handleChangeAnswer = (event) => {
this.setState({
TextAreaAnswer: event.target.value
})
};
handleChangeCategory = (event) => {
this.setState({
categoryId: event.target.value
})
};
handleSubmit = (event) => {
alert('Question Submitted');
this.state.categoryId ?
this.props.addQuestionMutation({
variables: {
name: this.state.TextAreaQuestion,
answer: this.state.TextAreaAnswer,
categoryId: this.state.categoryId
},
refetchQueries: [{query: getQuestionsQuery}, {query: getCategoriesQuery}]
})
:
this.props.addQuestionMutation({
variables: {
name: this.state.TextAreaQuestion,
answer: this.state.TextAreaAnswer,
},
refetchQueries: [{query: getQuestionsQuery}]
});
event.preventDefault();
this.props.history.goBack();
};
render() {
return (
<OverlayWrapper onClick={() => this.props.history.goBack()}>
<OverlaySpan>
<ContentDiv onClick={e => e.stopPropagation()}>
<QuestionSubmissionTitle>Question Submission</QuestionSubmissionTitle>
<QSubmissionForm onSubmit={this.handleSubmit}>
<QuestionSubmissionDiv>
<QAlabel> Enter Question: </QAlabel>
<QSubmissiontextarea value={this.state.TextAreaQuestion}
onChange={this.handleChangeQuestion}
rows="4"
cols="50"
id="questionText"
name="questionText"
wrap="hard">Question</QSubmissiontextarea>
<QAlabel> Enter Answer: </QAlabel>
<QSubmissiontextarea value={this.state.TextAreaAnswer}
onChange={this.handleChangeAnswer}
rows="4"
cols="50"
id="questionAnswer"
name="questionAnswer"
wrap="hard">Answer</QSubmissiontextarea>
<QAlabel> Choose Category: </QAlabel>
<QSelect value={this.state.categoryId} onChange={this.handleChangeCategory}>
<option key={"all-categories-add-question"} value={null}>No Category (will appear in All)</option>
{this.displayCategories()}
</QSelect>
</QuestionSubmissionDiv>
<InputDiv>
<StyledInput type="submit"/>
</InputDiv>
</QSubmissionForm>
</ContentDiv>
</OverlaySpan>
</OverlayWrapper>
)
}
}
export default compose(
graphql(getCategoriesQuery, {name: "getCategoriesQuery"}),
graphql(addQuestionMutation, {name: "addQuestionMutation"})
)(AddQuestion);<file_sep>/server/models/category.js
const mongoose = require('mongoose');
const categorySchema = new mongoose.Schema({
name: String,
questions: []
});
const CategoryS = mongoose.model('Category', categorySchema);
module.exports = CategoryS<file_sep>/frontend/src/queries/queries.js
import {gql} from 'apollo-boost';
const getCategoriesQuery = gql`
{
categories{
name
id
questions {
id
name
answer
category{
name
id
}
}
}
}
`;
const getQuestionsQuery = gql`
{
questions {
name
id
answer
category{
name
id
}
}
}
`;
const getCategoryQuestionsQuery = gql`
query ($id: ID) {
category (id: $id){
id
name
questions {
id
name
answer
}
}
}
`;
const addQuestionMutation = gql`
mutation ($name: String!, $answer:String!, $categoryId: ID){
addQuestion (question: $name, answer: $answer, categoryId: $categoryId){
name
answer
}
}
`;
const deleteQuestionMutation = gql`
mutation ($id: ID!) {
deleteQuestion(id: $id){
name
}
}
`;
const addCategoryMutation = gql`
mutation ($name: String!) {
addCategory(name: $name){
name
id}
}
`;
const deleteCategoryMutation = gql`
mutation ($id: ID!) {
deleteCategory(id: $id){
name
}
}
`;
const addCategoryToQuestionMutation = gql`
mutation ($questionId: ID!, $categoryId: ID!) {
addCategoryToQuestion(id: $questionId, categoryId: $categoryId) {
name
id
}
}
`;
export{getQuestionsQuery, getCategoriesQuery, addQuestionMutation, deleteQuestionMutation, addCategoryMutation,
deleteCategoryMutation, addCategoryToQuestionMutation, getCategoryQuestionsQuery};<file_sep>/frontend/src/components/QuestionAnswerGenerator.js
import React, {Component} from "react";
import styled from 'styled-components';
import {graphql, compose} from 'react-apollo';
import { withApollo } from 'react-apollo'
import {getCategoriesQuery, getQuestionsQuery, getCategoryQuestionsQuery} from "../queries/queries";
const QuestionAnswerContainer = styled.div`
display: flex;
flex-direction: column;
`;
const QuestionAnswerDiv = styled.div`
flex: 1;
`;
const QATitle = styled.h2`
margin: 5px 10px;
text-align: center;
color: cornflowerblue;
`;
const QAContent = styled.div`
display: flex;
flex-direction: column;
margin: 0px 10px;
`;
const QuestionShow = styled.div`
min-width: 90%;
height: 250px;
padding: 20px;
border: 3px dashed cornflowerblue;
overflow: auto;
`;
const buttonDiv = styled.div`
display: flex;
flex-direction: row;
`;
const NextQuestionButton = styled.button`
background: cornflowerblue;
color: white;
font-size: 16px;
font-weight: 700;
width: 50%;
height: 50px;
align-self: center;
:hover {
background: skyblue;
}
:focus{
outline: 0px solid transparent;
}
`;
const DeleteQuestionButton = styled.button`
background: palevioletred;
color: white;
font-size: 10px;
font-weight: 700;
width: 100px;
height: 25px;
align-self: flex-end;
:hover {
background: lightpink;
}
:focus{
outline: 0px solid transparent;
}
`;
const AnswerDiv = styled.div`
flex: 1;
`;
const AnswerTextDiv = styled.div`
min-width: 90%;
height: 250px;
padding: 20px;
border: 3px dashed cornflowerblue;
`;
const AnswerText = styled.span`
display: block;
visibility: ${props => props.show ? 'visible' : 'hidden'};
overflow: auto;
height: 250px;
`;
const ShowAnswerButton = styled.button`
background: ${props => props.show ? 'palevioletred' : 'cornflowerblue'};
color: white;
font-size: 16px;
font-weight: 700;
width: 50%;
height: 50px;
align-self: center;
:hover {
background: ${props => props.show ? 'lightpink' : 'skyblue'};
}
:focus{
outline: 0px solid transparent;
}
`;
const QSelect = styled.select`
width: 25%;
height: auto;
margin: 10px 0;
align-self:center
`;
const QuestionAnswerWrapper = styled.div`
display: flex;
`;
class QuestionAnswerGenerator extends Component {
constructor(props) {
super(props);
const questionsLoaded = () => {
let data = this.props.getQuestionsQuery;
if (data.loading) {
return [];
} else {
return data.questions;
}
};
this.state = {
categorySelected: null,
questions: questionsLoaded(),
AnswerShown: false,
randomNumber: 0,
}
};
componentDidUpdate(prevProps, prevState) {
const allquestionsLoaded = () => {
let data = this.props.getQuestionsQuery;
if (data.loading) {
return [];
} else {
return data.questions
}
};
if (prevProps.getQuestionsQuery.loading !== this.props.getQuestionsQuery.loading) {
this.setState({
questions: allquestionsLoaded()
})
}
}
displayCategories = () => {
let data = this.props.getCategoriesQuery;
if (data.loading) {
return <option disabled>Loading Categories</option>
} else {
return data.categories.map(category =>
<option key={category.id} value={category.id}>{category.name}</option>
)
}
};
randomNumber = () => {
return Math.floor(Math.random() * this.state.questions.length);
};
randomize = () => {
this.setState({
AnswerShown: false,
randomNumber: this.randomNumber()
});
};
showAnswer = () => {
this.setState((prevState) => {
return {AnswerShown: !prevState.AnswerShown}
});
};
handleChangeCategory = async(event) => {
event.persist();
const allQuestionsLoaded = () => {
let data = this.props.getQuestionsQuery;
if (data.loading) {
return [];
} else {
return data.questions
}
};
if (event.target.value === 'all') {
this.setState({
questions: allQuestionsLoaded(),
categorySelected: event.target.value
})
} else {
const data = await this.props.client.query({
query: getCategoryQuestionsQuery,
variables: {id: event.target.value}});
const Categoryquestions = data.data.category.questions;
this.setState((prevState) => {
return {
questions: Categoryquestions,
categorySelected: event.target.value
}
})
}
};
render() {
const ShownQuestion = this.state.categorySelected !== null && this.state.questions.length === 0 ?
'No Questions in this Category, please select another category.'
: (this.state.questions[this.state.randomNumber] ?
this.state.questions[this.state.randomNumber].name
: 'Loading Question...');
const ShownAnswer = this.state.questions[this.state.randomNumber] ? this.state.questions[this.state.randomNumber].answer : 'Loading Answer...';
const ShowAnswerButtonToggle = this.state.AnswerShown ? 'Hide Answer' : 'Show Answer';
return (
<QuestionAnswerContainer>
<QATitle>Category</QATitle>
<QSelect value={this.state.categoryId} onChange={e => this.handleChangeCategory(e)}>
<option key={'all-categories'} value={'all'}>All</option>
{this.displayCategories()}
</QSelect>
<QuestionAnswerWrapper>
<QuestionAnswerDiv>
<QATitle>Questions</QATitle>
<QAContent>
<QuestionShow>{ShownQuestion}</QuestionShow>
<NextQuestionButton onClick={this.randomize}>
Next Question
</NextQuestionButton>
</QAContent>
</QuestionAnswerDiv>
<QuestionAnswerDiv>
<QATitle>Answers</QATitle>
<QAContent>
<AnswerTextDiv>
<AnswerText show={this.state.AnswerShown}>{ShownAnswer}</AnswerText>
</AnswerTextDiv>
<ShowAnswerButton show={this.state.AnswerShown}
onClick={this.showAnswer}>{ShowAnswerButtonToggle}
</ShowAnswerButton>
</QAContent>
</QuestionAnswerDiv>
</QuestionAnswerWrapper>
</QuestionAnswerContainer>
)
}
}
export default compose(
withApollo,
graphql(getQuestionsQuery, {name: "getQuestionsQuery"}),
graphql(getCategoriesQuery, {name: "getCategoriesQuery"}),
graphql(getCategoryQuestionsQuery, {name: "getCategoryQuestionsQuery"})
)(QuestionAnswerGenerator); | e689493aa12f52dd9b97f288e10aee7fd3cae572 | [
"JavaScript"
] | 5 | JavaScript | jessicachakmlee/FlashCards | dc10f73e78d3f3187685b138a8620264bd240bb4 | fed90f86817537b8e86ebe19e93f381af39ad681 |
refs/heads/master | <repo_name>sethcoast/GivvApp<file_sep>/app/src/main/java/com/example/macbookpro/givvapp/controller/employer/EmployerMainActivity.java
package com.example.macbookpro.givvapp.controller.employer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.macbookpro.givvapp.R;
public class EmployerMainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employer_main);
}
}
<file_sep>/app/src/main/java/com/example/macbookpro/givvapp/support/GivvClickListener.java
package com.example.macbookpro.givvapp.support;
import android.view.View;
/**
* Created by macbookpro on 10/14/17
*/
public interface GivvClickListener<DataType> {
void onItemClicked(DataType data, View view, int position);
}
<file_sep>/app/src/main/java/com/example/macbookpro/givvapp/controller/admin/AddCompanyActivity.java
package com.example.macbookpro.givvapp.controller.admin;
import android.support.v7.app.AppCompatActivity;
import com.example.macbookpro.givvapp.support.GivvActivity;
/**
* Created by macbookpro on 10/14/17
*/
public class AddCompanyActivity extends GivvActivity {
}
<file_sep>/app/src/main/java/com/example/macbookpro/givvapp/support/GivvActivity.java
package com.example.macbookpro.givvapp.support;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.example.macbookpro.givvapp.R;
/**
* Created by macbookpro on 10/14/17
*/
public class GivvActivity extends AppCompatActivity {
private static final String LOADING = "Loading...";
private AlertDialog errorDialog;
protected ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
protected boolean displayUp() {
return true;
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
View view = getLayoutInflater().inflate(layoutResID, null);
configureToolbar(view);
super.setContentView(view);
}
private void configureToolbar(View view) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(displayUp());
}
}
@NonNull
@Override
public ActionBar getSupportActionBar() {
ActionBar actionBar = super.getSupportActionBar();
if (actionBar != null) {
return actionBar;
}
throw new NullPointerException("Toolbar must be included in the Activity layout file");
}
}
<file_sep>/app/src/main/java/com/example/macbookpro/givvapp/controller/CompanyActivity.java
package com.example.macbookpro.givvapp.controller;
import android.support.v7.app.AppCompatActivity;
import com.example.macbookpro.givvapp.support.GivvActivity;
/**
* Created by macbookpro on 10/14/17
*/
public class CompanyActivity extends GivvActivity {
}
<file_sep>/app/src/main/java/com/example/macbookpro/givvapp/controller/admin/CharitiesFragment.java
package com.example.macbookpro.givvapp.controller.admin;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.macbookpro.givvapp.R;
import com.example.macbookpro.givvapp.controller.CompanyActivity;
import com.example.macbookpro.givvapp.model.Charity;
import com.example.macbookpro.givvapp.support.GivvClickListener;
import com.example.macbookpro.givvapp.support.GivvFragment;
import com.example.macbookpro.givvapp.support.GivvRecyclerAdapter;
import com.example.macbookpro.givvapp.support.GivvRecyclerView;
import com.example.macbookpro.givvapp.support.GivvViewHolder;
import java.util.ArrayList;
import java.util.List;
/**
* Created by macbookpro on 10/14/17
*/
public class CharitiesFragment extends GivvFragment {
public static CharitiesFragment newInstance(ArrayList<Charity> charities) {
CharitiesFragment fragment = new CharitiesFragment();
Bundle args = new Bundle();
args.putParcelableArrayList("charities", charities);
fragment.setArguments(args);
return fragment;
}
@Override
public String getTitle() {
return "Charities";
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycler_view, null);
List<Charity> charities = getArguments().getParcelableArrayList("charities");
CharityAdapter adapter = new CharityAdapter(charities);
GivvRecyclerView recyclerView = (GivvRecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setAdapter(adapter);
return view;
}
private class CharityAdapter extends GivvRecyclerAdapter<Charity> {
public CharityAdapter(List<Charity> charities) {
super(charities);
}
@Override
public CharityViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new CharityViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.default_list_item_indicator, null));
}
private class CharityViewHolder extends GivvViewHolder<Charity> {
TextView textView;
public CharityViewHolder(View view) {
super(view);
textView = (TextView) view.findViewById(R.id.textView);
}
@Override
public void bind(final Charity data, GivvClickListener<Charity> listener) {
super.bind(data, listener);
textView.setText(data.getName());
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), CompanyActivity.class).putExtra("company", data));
}
});
}
}
}
}
<file_sep>/app/src/main/java/com/example/macbookpro/givvapp/model/Donation.java
package com.example.macbookpro.givvapp.model;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
/**
* Created by macbookpro on 10/14/17
*/
public class Donation implements Parcelable {
private Date donationDate;
private double amount;
public Donation(Date donationDate, double amount) {
this.donationDate = donationDate;
this.amount = amount;
}
protected Donation(Parcel in) {
amount = in.readDouble();
}
public static final Creator<Donation> CREATOR = new Creator<Donation>() {
@Override
public Donation createFromParcel(Parcel in) {
return new Donation(in);
}
@Override
public Donation[] newArray(int size) {
return new Donation[size];
}
};
public Date getDonationDate() {
return donationDate;
}
public void setDonationDate(Date donationDate) {
this.donationDate = donationDate;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeDouble(amount);
}
}
| f6fbbeef6f4a7bc8d1d51e3110186b8a19927268 | [
"Java"
] | 7 | Java | sethcoast/GivvApp | c93ed0c02bcb62c14d7fd68f15d2da7915d709fc | b2a397d59b92f9064972c485a31e4918e0a8f31c |
refs/heads/master | <repo_name>richard-stern/MyTest<file_sep>/MenuController.cs
using UnityEngine;
using System.Collections;
#if !UNITY_PS4
using UnityEngine.SceneManagement;
#endif
public class MenuController : MonoBehaviour
{
public GameObject GameSelect;
public GameObject MenuSelect;
public GameObject OptionsSelect;
public GameObject FadeManager;
//public GameObject LevelTransition;
private Animator GSanim;
private Animator MSanim;
private Animator OPanim;
//public Vector3 ScreenMouse;
private int MyRandom;
private int SceneIndex;
public int waitTime = 0;
// Initialize variables,UI panels and animators
void Start()
{
SceneIndex = 0;
MenuSelect.SetActive(true);
OptionsSelect.SetActive(false);
GSanim = GameSelect.GetComponent<Animator>();
//GSanim.SetBool("GSmove", false);
GSanim.enabled = true;
MSanim = MenuSelect.GetComponent<Animator>();
MSanim.SetBool("MSmoveLeft", false);
MSanim.SetBool("MSmoveDown", false);
//Added a comment
MSanim.enabled = true;
OPanim = OptionsSelect.GetComponent<Animator>();
// OPanim.SetBool("OPmove", false);
OPanim.enabled = false;
}
// Activate the GameSelectButtons animation and transition all buttons left
public void OnGameSelectButtonPress()
{
GameSelect.SetActive(true);
GSanim.enabled = true;
GSanim.SetBool("Cat2",true);
MSanim.enabled = true;
MSanim.SetBool("MSmoveLeft",true);
//Explode();
}
public void OnHighScoreButtonPress()
{
}
public void OnOptionsButtonPress()
{
OptionsSelect.SetActive(true);
OPanim.enabled = true;
OPanim.SetBool("OPmove",true);
MSanim.enabled = true;
MSanim.SetBool("MSmoveDown",true);
}
public void OnExitButtonPress()
{
Application.Quit();
}
public void OnTelevisionButtonPress()
{
SceneIndex = 1;
StartCoroutine("StartGameEvent");
}
public void OnVideoGameButtonPress()
{
SceneIndex = 2;
StartCoroutine("StartGameEvent");
}
public void OnMoviesButtonPress()
{
SceneIndex = 3;
StartCoroutine("StartGameEvent");
}
public void OnRandomButtonPress()
{
MyRandom = Random.Range ((int)0, (int)3);
if (MyRandom == 0)
{
SceneIndex = 1;
}
else if (MyRandom == 1)
{
SceneIndex = 2;
}
else
{
SceneIndex = 3;
}
StartCoroutine("StartGameEvent");
}
public void OnGSBackButtonPress()
{
MSanim.SetBool("MSmoveLeft",false);
GSanim.SetBool("GSmove",false);
//Explode ();
}
public void OnOPBackButtonPress()
{
MSanim.SetBool("MSmoveDown",false);
OPanim.SetBool("OPmove",false);
//Explode ();
}
IEnumerator StartGameEvent()
{
//Explode();
yield return new WaitForSeconds(1);
#if !UNITY_PS4
FadeManager.GetComponent<Fading>().BeginFade(1);
#endif
yield return new WaitForSeconds(1);
if (SceneIndex == 1)
{
#if UNITY_PS4
Application.LoadLevel("Television_Scene");
#endif
#if !UNITY_PS4
SceneManager.LoadScene("Television_Scene");
#endif
}
else if (SceneIndex == 2)
{
#if UNITY_PS4
Application.LoadLevel("VidGame_Scene");
#endif
#if !UNITY_PS4
SceneManager.LoadScene("VidGame_Scene");
#endif
}
else
{
#if UNITY_PS4
Application.LoadLevel("Movie_Scene");
#endif
#if !UNITY_PS4
SceneManager.LoadScene("Movie_Scene");
#endif
}
}
// Button press effect test function
private void Explode()
{
//LevelTransition.SetActive(true);
//ScreenMouse = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x,Input.mousePosition.y,0));
//Instantiate(LevelTransition, ScreenMouse, Quaternion.identity);
//LevelTransition.SetActive (false);
}
}
| 2828e32c5de29825047f45f273e29616ae646b59 | [
"C#"
] | 1 | C# | richard-stern/MyTest | 3f7c40c70ba067c85de1f22f8807b74ad38a89e4 | e72275487c6f048ff215bc9410c24aebd08056b5 |
refs/heads/master | <file_sep>import { Collaborateur } from './../model/collaborateur.model';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class CollaborateurService {
constructor(private http: HttpClient) {}
public urlBase: string = 'http://localhost:8036/collaborateur';
public _collaborateur: Collaborateur;
public _collaborateurs: Array<Collaborateur>;
findAll() {
this.http.get<Array<Collaborateur>>(this.urlBase + '/').subscribe(
(data) => {
this._collaborateurs = data;
},
(error) => {
alert('Error Colaborateur');
}
);
}
get collaborateur(): Collaborateur {
if (this._collaborateur == null) {
this._collaborateur = new Collaborateur();
}
return this._collaborateur;
}
get collaborateurs(): Array<Collaborateur> {
if (this._collaborateurs == null) {
this._collaborateurs = new Array<Collaborateur>();
}
return this._collaborateurs;
}
set collaborateur(value: Collaborateur) {
this._collaborateur = value;
}
set collaborateurs(value: Array<Collaborateur>) {
this._collaborateurs = value;
}
// addCollaborateur(collaborateur: Collaborateur) {
// this.http.post(this.urlBase + '/', collaborateur).subscribe(
// (data) => {
// if (data == 1) {
// }
// },
// (error) => {}
// );
// }
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {Stock} from '../../controller/model/Stock.model';
import {StockService} from '../../controller/service/stock-service.service';
@Component({
selector: 'app-stock-list',
templateUrl: './stock-list.component.html',
styleUrls: ['./stock-list.component.css']
})
export class StockListComponent implements OnInit {
constructor(private stockService: StockService) {
}
get stocks(): Array<Stock> {
return this.stockService.stocks;
}
ngOnInit(): void {
this.stockService.findAll();
}
delete(i: number, reference: string, reference2: string) {
}
update(i: number, c: Stock) {
}
}
<file_sep>export class Collaborateur {
private id: number;
public codeCollaborateur: string;
public fullname: string;
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { StockService } from './stock-service.service';
import { OperationStock } from '../model/operationStock.model';
@Injectable({
providedIn: 'root',
})
export class OperationstockService {
constructor(private http: HttpClient, private stockservice: StockService) {}
get operationstock(): OperationStock {
if (this._operationstock == null) {
this._operationstock = new OperationStock();
}
return this._operationstock;
}
set operationstock(value: OperationStock) {
this._operationstock = value;
}
get operationstocks(): Array<OperationStock> {
if (this._operationstocks == null) {
this._operationstocks = new Array<OperationStock>();
}
return this._operationstocks;
}
set operationstocks(value: Array<OperationStock>) {
this._operationstocks = value;
}
private urlBase = 'http://localhost:8036';
private url = '/Stock/OperationStockBean';
private _operationstock: OperationStock;
private _operationstocks: Array<OperationStock>;
findAll(): void {
this.http
.get<Array<OperationStock>>(this.urlBase + this.url + '/')
.subscribe((data) => {
this.operationstocks = data;
});
}
save() {
this.http
.post(this.urlBase + this.url + '/', this.operationstock)
.subscribe((data) => {
if (data === -1) {
alert(
'l un d est reference entre n est pas disponible dans la base de donnees'
);
}
if (data === -2) {
open('http://localhost:4200/stockks');
alert('veuiliez enregistre un stock');
}
if (data === -3) {
alert('la quantites voulu a transferee n est pas disponible ');
}
this.operationstock = null;
if (data > 0) {
this.operationstock.id = this.operationstocks.length + 1;
this.operationstocks.push(this.clone(this.operationstock));
this.findAll();
this.operationstock = null;
}
});
}
private clone(operationstock: OperationStock) {
const myClone = new OperationStock();
myClone.qte = operationstock.qte;
myClone.magasinSource.reference = operationstock.magasinSource.reference;
myClone.magasinDestination.reference =
operationstock.magasinDestination.reference;
myClone.id = operationstock.id;
myClone.material.reference = operationstock.material.reference;
return myClone;
}
find(reference: String) {
this.http
.get<Array<OperationStock>>(
this.urlBase + this.url + '/trouve/refmagasin/' + reference
)
.subscribe((data) => {
console.log(data);
this.operationstocks = data;
});
}
// findByCritere(qteMax: number, qteMin: number) {
// this.http.post<Array<OperationStock>>(this.urlBase+this.url+'/criteria',qte)
// }
}
<file_sep>import { Collaborateur } from './../../controller/model/collaborateur.model';
import { CollaborateurService } from './../../controller/service/collaborateur.service';
import { Component, OnInit } from '@angular/core';
import {InterventionService} from '../../controller/service/intervention.service';
import {InterventionMembreEquipe} from '../../controller/model/intervention-membre-equipe.model';
@Component({
selector: 'app-collaborateur-create',
templateUrl: './collaborateur-create.component.html',
styleUrls: ['./collaborateur-create.component.css'],
})
export class CollaborateurCreateComponent implements OnInit {
constructor(private collaborateurService: CollaborateurService,private interventionService:InterventionService) {}
// get collaborateur(): Collaborateur {
// return this.collaborateurService.collaborateur;
// }
//
// get collaborateurs(): Array<Collaborateur> {
// return this.collaborateurService.collaborateurs;
// }
get collaborateur(): InterventionMembreEquipe {
return this.interventionService.collaborateur;
}
get collaborateurs(): Array<Collaborateur> {
return this.collaborateurService.collaborateurs;
}
selected: string = '';
// public addMembres() {
// this.equipesService.addMembres();
// }
// get membre(): MembreEquipe {
// return this.equipesService.membre;
// }
ngOnInit(): void {
this.collaborateurService.findAll();
}
saveCollaboraateur() {
this.interventionService.saveCollaboraateur();
}
isSelected($event: any) {
this.collaborateur.membreEquipe.collaborateur.codeCollaborateur=$event.target.value;
}
}
<file_sep>// import { MembreEquipe } from './../controller/model/membre-equipe.model';
// import { EquipesService } from './../controller/service/equipes.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-membre-equipe',
templateUrl: './membre-equipe.component.html',
styleUrls: ['./membre-equipe.component.css'],
})
export class MembreEquipeComponent implements OnInit {
// constructor(private equipesService: EquipesService) {}
constructor() {
}
// public addMembres() {
// this.equipesService.addMembres();
// }
//
// get membre(): MembreEquipe {
// return this.equipesService.membre;
// }
ngOnInit(): void {}
}
<file_sep>// import { EquipesService } from './../controller/service/equipes.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-equipes',
templateUrl: './equipes.component.html',
styleUrls: ['./equipes.component.css']
})
export class EquipesComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<file_sep>import { Collaborateur } from './../../controller/model/collaborateur.model';
import { CollaborateurService } from './../../controller/service/collaborateur.service';
import { Component, OnInit } from '@angular/core';
import {InterventionService} from '../../controller/service/intervention.service';
import {Intervention} from '../../controller/model/intervention.model';
@Component({
selector: 'app-collaborateur-list',
templateUrl: './collaborateur-list.component.html',
styleUrls: ['./collaborateur-list.component.css'],
})
export class CollaborateurListComponent implements OnInit {
page= 1;
pageSize= 5;
collectionSize=this.interventionService.interventions.length
code: string;
constructor(private collaborateurService: CollaborateurService,private interventionService: InterventionService) {}
get collaborateurs(): Array<Collaborateur> {
return this.collaborateurService.collaborateurs;
}
get interventions(): Array<Intervention> {
return this.interventionService.interventions;
}
ngOnInit(): void {
this.interventionService.findAll();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Stock } from '../model/Stock.model';
import {HttpClient} from '@angular/common/http';
import {Resource} from '@angular/compiler-cli/src/ngtsc/metadata';
// import * as FileSaver from 'file-saver';
// import * as XLSX from 'xlsx';
// const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
// const EXCEL_EXTENSION = '.xlsx';
@Injectable({
providedIn: 'root'
})
export class StockService {
private _stock: Stock;
private _stocks: Array<Stock>;
private urlBase = 'http://localhost:8036';
private url = '/Stock-api/Stockage';
private _index: number;
get stock(): Stock {
if (this._stock == null) {
this._stock = new Stock();
}
return this._stock;
}
set stock(value: Stock) {
this._stock = value;
}
get stocks(): Array<Stock> {
if (this._stocks == null) {
this._stocks = new Array<Stock>();
}
return this._stocks;
}
set stocks(value: Array<Stock>) {
this._stocks = value;
}
constructor(private http: HttpClient) { }
save() {
if (this.stock.id == null) {
this.http.post(this.urlBase + this.url + '/', this.stock).subscribe(
data => {
if (data === 1){
this.findAll();
}
if (data === -2) {
alert('donner une valeur deja existante ');
}
if (data === 2){
this.findAll();
}
}, error => alert('error 404')
);
}
else{
const stocke = new Stock();
stocke.qte = this.stock.qte - this.stocks[this._index].qte;
stocke.id = this.stock.id;
stocke.material.reference = this.stock.material.reference;
stocke.magasin.reference = this.stock.magasin.reference;
this.http.post(this.urlBase + this.url + '/', stocke).subscribe(
data => {
console.log(data);
}
);
this.stocks[this._index] = this.clone(this.stock);
}
this.stock = null;
}
findAll() {
this.http.get<Array<Stock>>(this.urlBase + this.url + '/').subscribe(
data => {
this.stocks = data;
}, error => {
console.log(error);
});
}
clone(stock: Stock) {
const myClone = new Stock();
myClone.id = stock.id;
myClone.material.reference = stock.material.reference;
myClone.qte = stock.qte;
myClone.magasin.reference = stock.magasin.reference;
return myClone;
}
}
<file_sep>import {Collaborateur} from './collaborateur.model';
export class User {
public id: number;
public collaborateur = new Collaborateur();
public login: string;
public role: string;
public password: string;
}
<file_sep>import { EtatIntervention } from './../model/etat-intervention.model';
import { MateraialIntervention } from './../model/materaial-intervention.model';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Intervention } from './../model/intervention.model';
import {StockService} from './stock-service.service';
import {Conseils} from '../model/conseils.model';
import { InterventionVo } from '../model/intervention-vo.model';
import {InterventionMembreEquipe} from '../model/intervention-membre-equipe.model';
import {UserService} from './user.service';
import {CollaborateurListComponent} from "../../collaborateur/collaborateur-list/collaborateur-list.component";
import {MatDialog} from "@angular/material/dialog";
@Injectable({
providedIn: 'root',
})
export class InterventionService {
constructor(private http: HttpClient, private stockService: StockService, private userService: UserService,public dialog: MatDialog) {}
public _intervention: Intervention;
public _interventions: Array<Intervention>;
private _collaborateurs = this.intervention.interventionMembreEquipe;
private _collaborateur: InterventionMembreEquipe;
private _codeCollaborateur = this.collaborateur.membreEquipe.collaborateur.codeCollaborateur;
private _materialInterventions = this.intervention.materaialInterventions;
private _materialIntervention: MateraialIntervention;
private _conseilIntervention: Conseils;
private _conseilInterventions: Array<Conseils>;
private urlBase = 'http://localhost:8036/Intervention-api/intervention';
private _index: number;
urlCriteria = 'http://localhost:8036/Intervention-api/intervention/criteria';
public _interventionVo: InterventionVo;
get conseilIntervention(): Conseils {
if (this._conseilIntervention == null){
this._conseilIntervention = new Conseils();
}
return this._conseilIntervention;
}
set conseilIntervention(value: Conseils) {
this._conseilIntervention = value;
}
get conseilInterventions(): Array<Conseils> {
if (this._conseilInterventions == null){
this._conseilInterventions = new Array<Conseils>();
}
return this._conseilInterventions;
}
set conseilInterventions(value: Array<Conseils>) {
this._conseilInterventions = value;
}
get interventionVo(): InterventionVo {
if (this._interventionVo == null) {
this._interventionVo = new InterventionVo();
}
return this._interventionVo;
}
set interventionVO(value: InterventionVo) {
this._interventionVo = value;
}
get materialInterventions(): Array<MateraialIntervention> {
if ( this._materialInterventions == null){
this._materialInterventions = new Array<MateraialIntervention>();
}
return this._materialInterventions;
}
set materialInterventions(value: MateraialIntervention[]) {
this._materialInterventions = value;
}
get materialIntervention(): MateraialIntervention {
if ( this._materialIntervention == null){
this._materialIntervention = new MateraialIntervention();
}
return this._materialIntervention;
}
set materialIntervention(value: MateraialIntervention) {
this._materialIntervention = value;
}
get collaborateur(): InterventionMembreEquipe {
if (this._collaborateur == null){
// this._collaborateur.collaborateur = new Collaborateur();
this._collaborateur = new InterventionMembreEquipe();
}
return this._collaborateur;
}
set collaborateur(value: InterventionMembreEquipe) {
this._collaborateur = value;
}
private _materials: Array<MateraialIntervention>;
private _etatIntervention: EtatIntervention;
get collaborateurs(): Array<InterventionMembreEquipe> {
if (this._collaborateurs == null){
this._collaborateurs = new Array<InterventionMembreEquipe>();
}
return this._collaborateurs;
}
set collaborateurs(value: Array<InterventionMembreEquipe>) {
this._collaborateurs = value;
}
get materials(): Array<MateraialIntervention> {
if (this._materials == null){
this._materials = new Array<MateraialIntervention>();
}
return this._materials;
}
set materials(value: Array<MateraialIntervention>) {
this._materials = value;
}
get etatIntervention(): EtatIntervention {
if (this._etatIntervention == null){
this._etatIntervention = new EtatIntervention();
}
return this._etatIntervention;
}
set etatIntervention(value: EtatIntervention) {
this._etatIntervention = value;
}
get intervention(): Intervention {
if (this._intervention == null) {
this._intervention = new Intervention();
}
return this._intervention;
}
set intervention(value: Intervention) {
this._intervention = value;
}
get interventions(): Array<Intervention> {
if (this._interventions == null) {
this._interventions = new Array<Intervention>();
}
return this._interventions;
}
set interventions(value: Array<Intervention>) {
this._interventions = value;
}
public findByCriteria(){
this.http.post<Array<Intervention>>(this.urlCriteria, this.interventionVo).subscribe(
data => {
this.interventions = data ;
}, error => {
console.log(error); }
);
}
saveCollaboraateur() {
this.collaborateur.intervention = this.intervention;
this.collaborateurs.push(this._collaborateur);
this._codeCollaborateur = this.collaborateur.membreEquipe.collaborateur.codeCollaborateur;
console.log(this._codeCollaborateur);
this._collaborateur = null;
}
saveStock(){
this.materialIntervention.intervention = this.intervention;
this.materialIntervention.collaborateur.codeCollaborateur = this._codeCollaborateur;
this.materialInterventions.push(this._materialIntervention);
this.stockService.stock = null;
console.log(this._materialInterventions);
// this.materialIntervention.push(this.materialIntervention);
}
saveConseil(){
this.conseilIntervention.intervention = this.intervention;
this.conseilIntervention.collaborateur.codeCollaborateur = this._codeCollaborateur;
this.conseilInterventions.push(this._conseilIntervention);
this.intervention.conseils = this.conseilInterventions;
this._conseilIntervention = null;
console.log(this._conseilInterventions);
console.log(this.intervention);
}
getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
}
// JSON.stringify(circularReference, getCircularReplacer());
saveIntervention() {
console.log(this.intervention);
const stringifi = JSON.stringify(this.intervention, this.getCircularReplacer());
this.http.post(this.urlBase + '/', JSON.parse(stringifi)).subscribe(
data => {
if (data < 0) {
alert('one of the reference are not available');
}
else{
console.log('success' + data);
}
}
);
}
public update(index: number, intervention: Intervention) {
this.intervention = this.intervention;
this._index = index;
}
public findAll(){
if (this.userService.User.role === 'admin') {
this.http.get<Array<Intervention>>(this.urlBase + '/').subscribe(
data => {
this.interventions = data;
}
// }, error => {
// console.log(error); }
);
}
else {// (this.userService.User.role === 'collaborateur')
this.http.get<Array<Intervention>>(this.urlBase + '/codeCollan/' + this.userService.User.collaborateur.codeCollaborateur).subscribe(
data => {
this.interventions = data;
}
);
}
}
openDialog() {
this.dialog.open(CollaborateurListComponent);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {InterventionService} from '../../controller/service/intervention.service';
import {Intervention} from '../../controller/model/intervention.model';
@Component({
selector: 'app-intervention-info',
templateUrl: './intervention-info.component.html',
styleUrls: ['./intervention-info.component.css']
})
export class InterventionInfoComponent implements OnInit {
constructor(private interventionService:InterventionService) { }
get intervention(): Intervention {
return this.interventionService.intervention;
}
get interventions(): Array<Intervention> {
return this.interventionService.interventions;
}
ngOnInit(): void {
}
}
<file_sep>import { User } from './../controller/model/user.model';
import { UserService } from './../controller/service/user.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
constructor(private userService: UserService) {}
get User(): User {
return this.userService.User;
}
connected() {
this.userService.isconnected();
}
seConnecter(username, password) {
this.userService.seConnecter(username, password);
}
ngOnInit(): void {}
}
<file_sep>import { Equipe } from './../../controller/model/equipe.model';
// import { EquipesService } from './../../controller/service/equipes.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-equipe-list',
templateUrl: './equipe-list.component.html',
styleUrls: ['./equipe-list.component.css']
})
export class EquipeListComponent implements OnInit {
panelOpenState = false;
// constructor(private equipeService:EquipesService) { }
// get equipes(): Array<Equipe> {
// return this.equipeService.equipes;
// }
// get equipe(): Equipe {
// return this.equipeService.equipe;
// }
// public delete(index: number){
// this.equipes.splice(index, 1);
// }
// public deleteColl(index: number){
// this.equipeSelect.membres.splice(index, 1);
// }
// public update(index: number, equipe: Equipe){
// this.equipeService.update(index, equipe);
// }
ngOnInit(): void {
}
// get equipeSelect(): Equipe {
// return this.equipeService.equipeSelect;
// }
// search(referenceMagasin: string, referenceMaterial: string) {
//
// }
// public findByEquipeRef(equipe: Equipe){
// this.equipeService.findByEquipeRef(equipe);
// }
}
<file_sep>import { OperationstockService } from './../../controller/service/operationstock.service';
import { Component, OnInit } from '@angular/core';
// import { OperationstockService } from '../../Controller/Service/operationstock.service';
import { OperationStock } from '../../controller/model/operationStock.model';
@Component({
selector: 'app-operation-stock-create',
templateUrl: './operation-stock-create.component.html',
styleUrls: ['./operation-stock-create.component.css'],
})
export class OperationStockCreateComponent implements OnInit {
qteMin: number;
qteMax: number;
constructor(private operationStockservice: OperationstockService) {}
ngOnInit(): void {}
get operationstocks(): Array<OperationStock> {
return this.operationStockservice.operationstocks;
}
get operationstock(): OperationStock {
return this.operationStockservice.operationstock;
}
save() {
this.operationStockservice.save();
}
findbyCritere(qteMax: number, qteMin: number) {
// this.operationStockservice.findByCritere(qteMax,qteMin);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {InterventionService} from '../../controller/service/intervention.service';
import {Conseils} from '../../controller/model/conseils.model';
@Component({
selector: 'app-intervention-consiel',
templateUrl: './intervention-consiel.component.html',
styleUrls: ['./intervention-consiel.component.css']
})
export class InterventionConsielComponent implements OnInit {
constructor(private interventionService: InterventionService) { }
ngOnInit(): void {
}
get conseilIntervention(): Conseils {
return this.interventionService.conseilIntervention;
}
ajouter() {
this.interventionService.saveConseil();
}
}
<file_sep>import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {StockService} from '../controller/service/stock-service.service';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import { Workbook } from 'exceljs';
import * as fs from 'file-saver';
import {Stock} from '../controller/model/Stock.model';
@Component({
selector: 'app-stock',
templateUrl: './stock.component.html',
styleUrls: ['./stock.component.css']
})
export class StockComponent implements OnInit {
constructor(private stockService: StockService) { }
public panelExpanded = false;
public panelExpande = false;
referenceMagasin: string;
referenceMaterial: string;
fileName = 'Stock.xlsx';
@ViewChild('htmlData') htmlData: ElementRef;
// data: Array<Stock> = this.stockService.stocks;
ngOnInit(): void {
this.stockService.findAll();
}
search(referenceMagasin: string, referenceMaterial: string) {
}
public openPDF(): void {
const DATA = document.getElementById('htmlData');
html2canvas(DATA).then(canvas => {
const fileWidth = 208;
const fileHeight = canvas.height * fileWidth / canvas.width;
const FILEURI = canvas.toDataURL('image/png');
const PDF = new jsPDF('p', 'mm', 'a4');
const position = 0;
PDF.addImage(FILEURI, 'PNG', 0, position, fileWidth, fileHeight);
PDF.save('stock.pdf');
});
}
exportexcel() {
const workbook = new Workbook();
const worksheet = workbook.addWorksheet('ProductData');
// workbook.csv.writeBuffer().then((data) => {
// let blob = new Blob([data], { type: 'text/csv' });
// fs.saveAs(blob, 'ProductData.csv');
// });
worksheet.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'material', key: 'material', width: 32 },
{ header: 'magasin', key: 'magasin', width: 10 },
{ header: 'qte', key: 'qte', width: 10 },
// { header: 'Price', key: 'price', width: 10, style: { font: { name: 'Arial Black', size: 10} } },
];
this.stockService.stocks.forEach(e => {
worksheet.addRow({id: e.id, material: e.material.reference, magasin: e.magasin.reference, qte: e.qte}, 'n');
});
workbook.xlsx.writeBuffer().then((data) => {
const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
fs.saveAs(blob, 'Stocks.xlsx');
});
}
}
<file_sep>export class OperationStockVo {
references: String;
Qte: String;
QteMin: String;
QteMax: String;
}
<file_sep>import { Intervention } from './../../controller/model/intervention.model';
import { InterventionService } from './../../controller/service/intervention.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-intervention-create',
templateUrl: './intervention-create.component.html',
styleUrls: ['./intervention-create.component.css'],
})
export class InterventionCreateComponent implements OnInit {
constructor(private interventionService: InterventionService) {}
ngOnInit(): void {}
modeVue = '';
get intervention(): Intervention {
return this.interventionService.intervention;
}
changeVue(vue: string) {
this.modeVue = vue;
}
save() {
this.interventionService.saveIntervention();
}
}
<file_sep>import { Intervention } from './../../controller/model/intervention.model';
import { InterventionService } from './../../controller/service/intervention.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-intervention-list',
templateUrl: './intervention-list.component.html',
styleUrls: ['./intervention-list.component.css'],
})
export class InterventionListComponent implements OnInit {
constructor(private interventionService: InterventionService) {}
page= 1;
pageSize= 5;
collectionSize=this.interventionService.interventions.length
code: string;
ngOnInit(): void {
this.interventionService.findAll();
}
get interventions(): Array<Intervention> {
return this.interventionService.interventions;
}
get intervention(): Intervention {
return this.interventionService.intervention;
}
get interventionVo(){
return this.interventionService.interventionVo;
}
public deleteIntervention(index: number){
this.interventions.splice(index, 1);
}
public update(index: number, intervention: Intervention){
this.interventionService.update(index, intervention);
}
public findByCriteria(){
this.interventionService.findByCriteria();
}
openDialog() {
this.interventionService.openDialog();
}
}
<file_sep>import { MaterialModule } from './material/material.module';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NavbarComponent } from './navbar/navbar.component';
import { ChefEquipeComponent } from './chef-equipe/chef-equipe.component';
import { CollaborateurComponent } from './collaborateur/collaborateur.component';
import { AdministrateurComponent } from './administrateur/administrateur.component';
import { HomeComponent } from './home/home.component';
import { PageNotfoundComponent } from './page-notfound/page-notfound.component';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { EquipesComponent } from './equipes/equipes.component';
import { EquipeCreateComponent } from './equipes/equipe-create/equipe-create.component';
import { EquipeListComponent } from './equipes/equipe-list/equipe-list.component';
import { MatTabsModule } from '@angular/material/tabs';
import { MatCardModule } from '@angular/material/card';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { FormsModule } from '@angular/forms';
import { StockListComponent } from './stock/stock-list/stock-list.component';
import { StockCreateComponent } from './stock/stock-create/stock-create.component';
import { StockComponent } from './stock/stock.component';
import { HttpClientModule } from '@angular/common/http';
import { InterventionComponent } from './intervention/intervention.component';
import { InterventionCreateComponent } from './intervention/intervention-create/intervention-create.component';
import { InterventionListComponent } from './intervention/intervention-list/intervention-list.component';
import { CollaborateurCreateComponent } from './collaborateur/collaborateur-create/collaborateur-create.component';
import { CollaborateurListComponent } from './collaborateur/collaborateur-list/collaborateur-list.component';
import { InterventionInfoComponent } from './intervention/intervention-info/intervention-info.component';
import { MembreEquipeComponent } from './membre-equipe/membre-equipe.component';
import { InterventionConsielComponent } from './intervention/intervention-consiel/intervention-consiel.component';
import {OperationStockCreateComponent} from './operation-stock/operation-stock-create/operation-stock-create.component';
import {OperationStockListComponent} from './operation-stock/operation-stock-list/operation-stock-list.component';
import {OperationStockComponent} from './operation-stock/operation-stock.component';
import {MatPaginatorModule} from '@angular/material/paginator';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { LoginComponent } from './login/login.component';
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
ChefEquipeComponent,
CollaborateurComponent,
AdministrateurComponent,
HomeComponent,
PageNotfoundComponent,
EquipesComponent,
EquipeCreateComponent,
EquipeListComponent,
StockComponent,
StockCreateComponent,
StockListComponent,
InterventionComponent,
InterventionCreateComponent,
InterventionListComponent,
CollaborateurCreateComponent,
CollaborateurListComponent,
InterventionInfoComponent,
MembreEquipeComponent,
InterventionConsielComponent,
OperationStockComponent,
OperationStockCreateComponent,
OperationStockListComponent,
LoginComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MaterialModule,
MatIconModule,
MatListModule,
MatToolbarModule,
MatSidenavModule,
MatButtonModule,
FlexLayoutModule,
MatTabsModule,
MatCardModule,
MatSnackBarModule,
FormsModule,
HttpClientModule,
MatSnackBarModule,
MatPaginatorModule,
NgbModule,
],
providers: [],
bootstrap: [AppComponent],
entryComponents: [EquipeCreateComponent, CollaborateurListComponent]
})
export class AppModule {}
<file_sep>// import { MembreEquipe } from './../../controller/model/membre-equipe.model';
// import { Equipe } from './../../controller/model/equipe.model';
// import { EquipesService } from './../../controller/service/equipes.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-equipe-create',
templateUrl: './equipe-create.component.html',
styleUrls: ['./equipe-create.component.css']
})
export class EquipeCreateComponent implements OnInit {
// constructor(private equipeService:EquipesService) { }
// panelOpenState = false;
//
// get equipe(): Equipe {
// return this.equipeService.equipe;
// }
// public deleteColl(index: number){
// this.equipe.membres.splice(index, 1);
// }
//
// // get membre(): MembreEquipe {
// // return this.equipeService.membre;
// // }
// public save() {
// this.equipeService.save();
// }
// public addMembres() {
// this.equipeService.addMembres();}
//
//
ngOnInit(): void {
// this.equipeService.findAll();
}
}
<file_sep>import { EquipesComponent } from './equipes/equipes.component';
import { PageNotfoundComponent } from './page-notfound/page-notfound.component';
import { ChefEquipeComponent } from './chef-equipe/chef-equipe.component';
import { CollaborateurComponent } from './collaborateur/collaborateur.component';
import { AdministrateurComponent } from './administrateur/administrateur.component';
import { HomeComponent } from './home/home.component';
import { NgModule, Component } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {StockComponent} from "./stock/stock.component";
import {InterventionComponent} from './intervention/intervention.component';
import {OperationStockComponent} from './operation-stock/operation-stock.component';
const componenets = [
ChefEquipeComponent,
CollaborateurComponent,
AdministrateurComponent,
HomeComponent,
PageNotfoundComponent,
EquipesComponent,
StockComponent,
InterventionComponent,
OperationStockComponent
];
const routes: Routes = [
{path: '', component: componenets[3]},
{path: 'home',component: componenets[3]},
{path: 'admin', component: componenets[2]},
{path: 'collaborateur',component: componenets[1]},
{path: 'chef-equipe', component: componenets[0]},
{path: 'equipes',component: componenets[5]},
{path: 'stock',component: componenets[6]},
{path: 'intervention', component: componenets[7]},
{path: 'operationStock',component:componenets[8]},
{path: '**', component: componenets[4]}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>export class InterventionVo {
public id: number;
public dateDeProbleme: Date;
public dateDebut: Date;
public dateFin: Date;
public description: string;
public libelle: string;
public code: string;
}
<file_sep>// import { EquipeCreateComponent } from './../../equipes/equipe-create/equipe-create.component';
// import { MembreEquipe } from './../model/membre-equipe.model';
// import { Injectable } from '@angular/core';
// import { Equipe } from '../model/equipe.model';
// import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
// import { HttpClient } from '@angular/common/http';
//
//
// @Injectable({
// providedIn: 'root'
// })
// export class EquipesService {
// private urlbase = 'http://localhost:8036';
// private url = 'http://localhost:8036/equipe/';
// private urlEquipe = 'http://localhost:8036/membreEquipe/';
// private urlEquipeRef = 'http://localhost:8036/membreEquipe/equipe/ref/'
// public _equipe: Equipe;
// public _equipes : Array<Equipe>;
// public _membre : MembreEquipe;
// private _index: number;
// private _equipeSelect : Equipe;
//
// constructor(private diag : MatDialog,
// private http: HttpClient
// ) { }
// public findAll(){
// this.http.get<Array<Equipe>>(this.url + '/').subscribe(
// data => {
// this.equipes = data ;
// }, error => {
// console.log(error); }
// );
// }
// get equipeSelect(): Equipe {
// if (this._equipeSelect == null){
// this._equipeSelect = new Equipe();
// }
// return this._equipeSelect;
// }
//
// set equipeSelect(value: Equipe) {
// this._equipeSelect = value;
// }
//
//
// get equipe(): Equipe {
// if (this._equipe == null){
// this._equipe = new Equipe();
// let membres = new Array<MembreEquipe>();
// this._equipe.membres = membres;
// let chef = new MembreEquipe();
// this._equipe.chefEquipe = chef;
// }
// return this._equipe;
// }
// set equipe(value: Equipe) {
// this._equipe = value;
// }
//
// get equipes(): Array<Equipe> {
// if (this._equipes == null){
// this._equipes = new Array<Equipe>();
// }
// return this._equipes;
// }
// set equipes(value: Array<Equipe>) {
// this._equipes = value;
// }
//
// get membre(): MembreEquipe {
// if (this._membre == null){
// this._membre = new MembreEquipe();
// }
// return this._membre;
// }
// set membre(value: MembreEquipe) {
// this._membre = value;
// }
//
// public save(){
// if (this.equipe.id == null){
// this.http.post( this.url + '/', this.equipe).subscribe(
// data => {
// if (data > 0){
// this.equipes.push(this.mycloneEquipe(this.equipe));
//
//
// }else {
// alert('error lors de la création d equipe : ' + data);
// }
// }
// );
// this.equipe.id = this.equipes.length + 1;
// this.equipes.push(this.mycloneEquipe(this.equipe));
// this.equipe = new Equipe();
//
//
// }else {
// this.equipes[this._index] = this.mycloneEquipe(this.equipe);
// }
// }
// public addMembres() {
// this.membre.id = this.equipe.membres.length + 1;
// this.equipe.membres.push(this.cloneMembre(this.membre));
// this.membre = new MembreEquipe();
// }
// public findByEquipeRef(equipe: Equipe){
// this.equipeSelect = equipe;
// if ( this.equipeSelect != null) {
// this.http.get<Array<MembreEquipe>>(this.urlEquipeRef + equipe.ref).subscribe(
// data => {
// this.equipeSelect.membres = data;
// }, error => {
// console.log('wow');
// }
// );
// }
// }
// public update(index: number, equipe: Equipe) {
// this.equipe = this.mycloneEquipe(equipe);
// this._index = index;
// }
// private mycloneEquipe(equipe: Equipe) {
// const myClone = new Equipe();
// myClone.id = equipe.id;
// myClone.ref = equipe.ref;
// myClone.libelle = equipe.libelle;
// myClone.chefEquipe = equipe.chefEquipe;
// myClone.membres = new Array<MembreEquipe>();
// equipe.membres.forEach(element => {
// myClone.membres.push(element);
// });
// return myClone;
// }
// private cloneMembre(membre: MembreEquipe) {
// const myCloneMembre = new MembreEquipe();
// // myCloneMembre.id = membre.id;
// // myCloneMembre.fullname = membre.fullname;
// // myCloneMembre.phone = membre.phone;
// return myCloneMembre;
// }
// }
<file_sep>import { Component, OnInit } from '@angular/core';
import { Stock } from 'src/app/controller/model/Stock.model';
import { StockService } from 'src/app/controller/service/stock-service.service';
import {InterventionService} from '../../controller/service/intervention.service';
import {Intervention} from '../../controller/model/intervention.model';
import {MateraialIntervention} from '../../controller/model/materaial-intervention.model';
import {MaterialService} from '../../controller/service/material.service';
import {Material} from '../../controller/model/material.model';
import {Magasin} from '../../controller/model/magasin.model';
import {MagasinService} from '../../controller/service/magasin.service';
@Component({
selector: 'app-stock-create',
templateUrl: './stock-create.component.html',
styleUrls: ['./stock-create.component.css']
})
export class StockCreateComponent implements OnInit {
private selected: any;
constructor(private stockService: StockService, private interventionService: InterventionService, private materialService: MaterialService, private magasinService: MagasinService) { }
get intervention(): Intervention {
return this.interventionService.intervention;
}
get stock(): Stock {
return this.stockService.stock;
}
get materials(): Array<Material>{
return this.materialService.materials;
}
get magasins(): Array<Magasin>{
return this.magasinService.magasins;
}
ngOnInit(): void {
this.materialService.findAll();
this.magasinService.findAll();
}
isupdateable() {
// return this.stock.id != null;
}
public Save(){
return this.stockService.save();
}
empty() {
}
evaluate() {
if (this.intervention.code == null){
this.Save();
}
else {
const materialintervention = new MateraialIntervention();
materialintervention.material = this.stock.material;
materialintervention.magasin = this.stock.magasin;
materialintervention.qte = this.stock.qte;
this.interventionService.materialIntervention = materialintervention;
this.interventionService.saveStock();
}
}
isSelected($event: any) {
this.stock.magasin.reference = $event.target.value;
}
isSelecte($event: any) {
this.stock.material.reference = $event.target.value;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { User } from '../controller/model/user.model';
import {UserService} from '../controller/service/user.service';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
mobile = false;
constructor(private userService: UserService) { }
ngOnInit(): void {
if (window.screen.width === 360) { // 768px portrait
this.mobile = true;
}
}
get User(): User {
return this.userService.User;
}
isAdmin() {
return this.User.role !== 'admin';
}
Collaborateur() {
return this.User.role !== 'collaborateur';
}
ischef() {
return this.User.role !== 'chef-equipe';
}
isStockRespo() {
return this.User.role !== 'reponsableDeStock';
}
}
<file_sep>
import { NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import {MatToolbarModule} from '@angular/material/toolbar';
import { FlexLayoutModule } from '@angular/flex-layout';
import {MatSidenavModule} from '@angular/material/sidenav';
import {MatTableModule} from '@angular/material/table';
import {MatDialogModule} from '@angular/material/dialog';
import {MatInputModule} from '@angular/material/input';
import {MatStepperModule} from '@angular/material/stepper';
import {MatTabsModule} from '@angular/material/tabs';
import {MatCardModule} from '@angular/material/card';
import {MatSnackBarModule} from '@angular/material/snack-bar';
import {MatExpansionModule} from '@angular/material/expansion';
import {MatPaginatorModule} from '@angular/material/paginator';
const MaterialModules = [
MatButtonModule,
MatToolbarModule,
FlexLayoutModule,
MatSidenavModule,
MatTableModule,
MatDialogModule,
MatInputModule,
MatStepperModule,
MatTabsModule,
MatCardModule,
MatSnackBarModule,
MatExpansionModule,
MatPaginatorModule
];
@NgModule({
imports: [MaterialModules],
exports: [MaterialModules]
})
export class MaterialModule { }
| 034472754be5a8273b0d8632d9e7b52d0d029f8b | [
"TypeScript"
] | 28 | TypeScript | ZOUANI/gmao-front-end | 9a8d6461892800433eb23e2d1109f5fb239e3cd5 | 39eb5378d327302b604ca09ff17b4be74ed8d53b |
refs/heads/master | <repo_name>zhumingmei/Django001<file_sep>/BookPublisher/app01/models.py
from django.db import models
# Create your models here.
class Publisher(models.Model):
pid = models.AutoField(primary_key=True) # id自增 主键
name = models.CharField(max_length=40, unique=True) # 不可重复
class Book(models.Model):
title = models.CharField(max_length=40)
pub = models.ForeignKey('Publisher', on_delete=models.CASCADE) # 级联删除
# 通过关系管理对象去拿相应的数据
class Author(models.Model):
name = models.CharField(max_length=30) # 此举定义了app01_author表,也就是作者这张表
books = models.ManyToManyField('Book') # 此句定义了app01_author_books这张表,也就是第三张表<file_sep>/BookPublisher/app01/templatetags/my_tags.py
from django import template
register = template.Library()
@register.inclusion_tag('page.html')
def page(num):
return {'num':range(1,num + 1)}
<file_sep>/BookPublisher/ss.py
print('ssssssssssss')<file_sep>/BookPublisher/app01/views.py
from django.shortcuts import render, redirect, HttpResponse
from app01 import models
from django.urls import reverse
from django.views import View
from django.utils.decorators import method_decorator
# Create your views here.
###################删除出版社,书籍和作者整合delete###################
def delete(request,table,pk):
# 根据前端传过来的id查找数据库中的数据,返回的是一个对象列表
class_table = getattr(models,table.capitalize())
print()
del_id = class_table.objects.filter(pk=pk)
if not del_id:
return HttpResponse('删除的数据不存在')
del_id.delete() # 删除数据
return redirect(reverse(table)) # 重定向返回到显示页面
#########################################出版社管理系统################################
def publisher_system(request):
# 获取所有的对象
all_publisher = models.Publisher.objects.all().order_by('pid')
# 向浏览器前端返回渲染的网页和数据库的数据对象
return render(request, 'publisher_system.html', {'all_publisher': all_publisher})
# 增加
def add_publisher(request):
error = ''
# 如果是POST请求则执行增加操作
if request.method == "POST":
# 获取前端传过来的数据
get_publisher = request.POST.get('add_publisher')
# 从前端传过来的数据进行check,如果存在或者为空,则返回相应信息给客户
if models.Publisher.objects.filter(name=get_publisher):
error = '出版社已存在'
if not get_publisher:
error = '出版社不能为空'
# 如果正常,则增加到数据库中
if not error:
models.Publisher.objects.create(name=get_publisher)
return redirect('/publisher_system/') # 增加数据成功后重定向显示
return render(request, 'add_publisher.html', {'error': error}) # 若增加数据失败则传入错误信息并返回当前页面
# 删除
def del_publisher(request,pk):
# 获取前端传过来的id数据
# get_id = request.GET.get('id') # url上携带的参数 不是GET请求提交参数
# 根据前端传过来的id查找数据库中的数据,返回的是一个对象列表
del_id = models.Publisher.objects.filter(pid=pk)
if not del_id:
return HttpResponse('删除的数据不存在')
del_id.delete() # 删除数据
return redirect('/publisher_system/') # 重定向返回到显示页面
# 编辑修正数据edit_publisher
def edit_publisher(request,pk):
# get请求时判断数据是否存在
error = ''
# get_id = request.GET.get('id')
edit_id = models.Publisher.objects.filter(pid=pk)
if not edit_id:
return HttpResponse('编辑的数据不存在')
edit = edit_id[0]
print(request.method)
# 编辑之后的请求的post请求
if request.method == 'POST':
# 获取前端传过来的name数据
get_name = request.POST.get('edit_publisher')
# check编辑后的名字是否符合条件,符合则将编辑后的渲染到页面
if models.Publisher.objects.filter(name=get_name):
error = '修正的出版社名字已存在'
if get_name == edit.name:
error = '出版社名字已存在'
if not get_name:
error = '出版社名字不能为空'
if not error:
edit.name = get_name
edit.save() # save之后才真正的更新到了数据库
return redirect('/publisher_system/') # 重定向返回到显示页面
# get请求时候,会渲染此页面,并将对象传到前端页面
return render(request, 'edit_publisher.html', {'edit': edit, 'error': error})
#######################################图书管理系统###################################
# 给FBV加装饰器
import time
def timer(func):
def inner(*args,**kwargs):
start = time.time()
ret = func(*args,**kwargs)
print('time-->>>',time.time()-start)
return ret
return inner
@timer
def book_system(request):
# 从数据库获取所有的图书,并从出版社表中取出出版社名字
book_all = models.Book.objects.all()
return render(request, 'book_system.html', {'book_all': book_all})
#增加图书(FBV)
# def add_book(request):
# pub_all = models.Publisher.objects.all()
# error = ''
# # 如果是POST请求则执行增加操作
# if request.method == "POST":
# # 获取前端传过来的数据
# get_book = request.POST.get('add_book')
# pub_id = request.POST.get('pub_id')
# # 从前端传过来的数据进行check,如果存在或者为空,则返回相应信息给客户
# if models.Book.objects.filter(title=get_book):
# error = '书名已存在'
# if not get_book:
# error = '书名不能为空'
#
# # 如果正常,则增加到数据库中
# if not error:
# # 增加数据到数据库
# # 注意这里,因为Book的pub是一个Publisher对象,所以要么传一个Publisher对象,要么直接传pub_id
# # 这里还可以这样写:pub_id=pub_id-->> pub = models.Publisher.objects.get(pk=pub_id) 获取的是唯一符合条件的对象
# models.Book.objects.create(title=get_book, pub_id=pub_id)
#
# return redirect('/book_system/') # 增加数据成功后重定向显示
#
# return render(request, 'add_book.html', {'error': error, 'pub_all': pub_all}) # 若增加数据失败则传入错误信息并返回当前页面
#增加图书(CBV写法)
# 写法二可以写多个:@method_decorator(timer,name='get')
# @method_decorator(timer,name='post')
# 写法三name指定为dispatch:@method_decorator(timer,name='dispatch')
@method_decorator(timer,name='dispatch')
class AddBook(View):
#写法四调用父类的dispatch:@method_decorator(timer)
def dispatch(self, request, *args, **kwargs):
ret = super().dispatch(request, *args, **kwargs)
return ret
# 写法一:@method_decorator(timer)
def get(self, request, *args, **kwargs):
pub_all = models.Publisher.objects.all()
return render(request, 'add_book.html', {'pub_all': pub_all}) # 若增加数据失败则传入错误信息并返回当前页面
def post(self, request, *args, **kwargs):
pub_all = models.Publisher.objects.all()
error = ''
# 获取前端传过来的数据
get_book = request.POST.get('add_book')
pub_id = request.POST.get('pub_id')
# 从前端传过来的数据进行check,如果存在或者为空,则返回相应信息给客户
if models.Book.objects.filter(title=get_book):
error = '书名已存在'
if not get_book:
error = '书名不能为空'
# 如果正常,则增加到数据库中
if not error:
# 增加数据到数据库
# 注意这里,因为Book的pub是一个Publisher对象,所以要么传一个Publisher对象,要么直接传pub_id
# 这里还可以这样写:pub_id=pub_id-->> pub = models.Publisher.objects.get(pk=pub_id) 获取的是唯一符合条件的对象
models.Book.objects.create(title=get_book, pub_id=pub_id)
return redirect('/book_system/') # 增加数据成功后重定向显示
return render(request, 'add_book.html', {'pub_all': pub_all}) # 若增加数据失败则传入错误信息并返回当前页面
# 删除图书
def del_book(request,pk):
# 获取前端传过来的id数据
# get_id = request.GET.get('id') # url上携带的参数 不是GET请求提交参数
# 根据前端传过来的id查找数据库中的数据,返回的是一个对象列表
del_id = models.Book.objects.filter(pk=pk)
if not del_id:
return HttpResponse('删除的数据不存在')
del_id.delete() # 删除数据
return redirect('/book_system/') # 重定向返回到显示页面
# 修改书名和出版社的名字
def edit_book(request,pk):
# get请求时判断数据是否存在
error = ''
# get_id = request.GET.get('id')
edit_id = models.Book.objects.filter(pk=pk)
if not edit_id:
return HttpResponse('编辑的数据不存在')
edit = edit_id[0]
# 编辑之后的请求的post请求
if request.method == 'POST':
# 获取前端传过来的name数据
get_book_name = request.POST.get('edit_book')
get_publisher_id = request.POST.get('edit_publisher')
# check编辑后的名字是否符合条件,符合则将编辑后的渲染到页面
if models.Book.objects.filter(title=get_book_name):
error = '修正的书名已存在'
if get_book_name == edit.title:
error = '书名已存在'
if not get_book_name:
error = '书名不能为空'
if not error:
edit.title = get_book_name
edit.pub = models.Publisher.objects.get(pk=get_publisher_id)
edit.save() # save之后才真正的更新到了数据库
return redirect('/book_system/') # 重定向返回到显示页面
pub_all = models.Publisher.objects.all()
# get请求时候,会渲染此页面,并将对象传到前端页面
return render(request, 'edit_book.html', {'edit': edit, 'pub_all': pub_all, 'error': error})
#########################################作者管理系统###############################################
def author_system(request):
all_author = models.Author.objects.all()
# #查询所有的作者
# # all_author--->>> <QuerySet [<Author: Author object>, <Author: Author object>, <Author: Author object>, <Author: Author object>]>
# print('all_author--->>>',all_author)
#
# #author是单独的作者对象
# for author in all_author:
# print('author.name--->>>', author.name) # 张燕秋 、张小红、刘宇、韩红 (也就是将所有的作者姓名输出)
#
# # type类型输出的是:<class 'django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager'>
# # ManyRelatedManager就是关系管理对象、
# print('author.books--->>>', author.books,type(author.books)) # 输出:app01.Book.None(注意books这里是)
#
# #关系管理对象有自己的方法.all() 拿到的就是Book书籍对象
# #作者对象-->关系对象--->书籍对象-->再去拿书籍对象中相应的属性值
# print('author.books.all--->>>', author.books.all()) # QuerySet [<Book: Book object>]>
#
# boo = author.books.all() # 注意取得的是所有的Book对象
# for bo in boo:
# print('bo.title--->>>',bo.title) # 所有书名都输出
if not all_author:
return HttpResponse('要查询的数据不存在')
return render(request, 'author_system.html', {'all_author': all_author})
def add_author(request):
error = ''
if request.method == 'POST':
# 获取前端传过来的数据
add_author = request.POST.get('add_author')
# getlist获取的是所有的pk,getlist返回的是列表值
# request.POST.get('author_book')--> get获取的是当前的pk值,如果有多个取得是最后一个
book_id = request.POST.getlist('author_book')
if models.Author.objects.filter(name=add_author):
error = '用户名已存在,请重新输入'
if not add_author:
error = '用户名不能为空,请重新输入'
if not error:
# 存入数据库
author_name = models.Author.objects.create(name=add_author) # 返回的是一个作者对象
# #create 方法返回的也是一个对象
# print('author_name-->>',author_name) # author_name-->> Author object
# author_name.books 是关系管理对象 ,就是负责管理多对多的关系的,将上面获取到的书籍列表直接set就可以了
author_name.books.set(book_id)
return redirect('/author_system/')
all_book = models.Book.objects.all()
return render(request, 'add_author.html', {'all_book': all_book, 'error': error})
def del_author(request,pk):
# 通过参数传递,所以不需要获取了
# pk = request.GET.get('pk')
aut_obj = models.Author.objects.filter(pk=pk)
if not aut_obj:
return HttpResponse('要删除的数据不存在')
aut_obj.delete()
return redirect('/author_system/')
def edit_author(request,pk):
# pk = request.GET.get('pk')
edit_author = models.Author.objects.filter(pk=pk) # 获取对象列表
edit_author = edit_author[0]
error = ''
if request.method == 'POST':
get_author = request.POST.get('edit_author')
get_id = request.POST.getlist('authod_id') # 用getlist获取列表值(获取多个值)
if not get_author:
error = '修改的作者名称不能为空'
if models.Author.objects.filter(name=get_author):
error = '作者名称已存在'
if not error:
edit_author.name = get_author
edit_author.save() # 先将名字提交到数据库
edit_author.books.set(get_id) # 更新books字段,因为books是多对多关系,所以要取到关系管理对象再通过set插入数据
return redirect('/author_system/')
book_all = models.Book.objects.all()
return render(request, 'edit_author.html', {'edit_author': edit_author, 'book_all': book_all, 'error': error})
###########################test 动态路由#########################
def index(request):
ind1 = reverse('app01:blogs',args=('666',))
print(ind1)
ind2 = reverse('app01:blog2',args=('kkkk',8956,))
print(ind2)
# return HttpResponse('你好,我是动态url,index')
return render(request, 'index3.html')
def indexs(request):
return HttpResponse('你好,我是动态url,indexs')
def years(request,years):
return HttpResponse('你好,我是动态url,years',years)
def yearsmonth(request,years,month):
print(years)
print(month)
return HttpResponse('你好,我是动态url,yearsmonth')
def year(request,yy,mm):
print(yy)
print(mm)
return HttpResponse('你好,我是动态url,year')
def index2(request,num = 1):
print('num--->>>',num)
return HttpResponse('你好,我是动态url,index2')
# 路由分发
def blog(request,year):
print(year)
return HttpResponse('你好,我是动态url,blog')
def blogs(request,year):
print(year)
return HttpResponse('你好,我是动态url,blogs')
def blog2(request,years,months):
return HttpResponse('你好,我是动态url,blog2')
# 反向解析
def blog(request):
return HttpResponse('你好,我是动态url,反向解析blog')
def index3(request):
return render(request, 'index3.html')
def index10(request):
return HttpResponse('你好,我是动态url,index10')
def home(request):
return HttpResponse('app01,home')
<file_sep>/BookPublisher/BookPublisher/urls.py
"""BookPublisher URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from app01 import views
urlpatterns = [
###################删除出版社,书籍和作者整合###################
url(r'^del_(author|publisher|book)/(\d+)/', views.delete),
###################出版社管理系统############################
url(r'^publisher_system/', views.publisher_system, name='publisher'),
url(r'^add_publisher/', views.add_publisher),
# url(r'^del_publisher/(\d+)/', views.del_publisher),
url(r'^edit_publisher/(\d+)/', views.edit_publisher),
##################图书管理系统##########################
url(r'^book_system/', views.book_system, name='book'),
# url(r'^add_book/', views.add_book),
url(r'^add_book/', views.AddBook.as_view()),
# url(r'^del_book/(\d+)/', views.del_book),
# id通过分组命名之后,作为参数传递
# url(r'^edit_book/', views.edit_book),
url(r'^edit_book/(\d+)/', views.edit_book),
#################作者管理系统#########################
url(r'^author_system/', views.author_system, name='author'),
url(r'^add_author/', views.add_author),
# url(r'^del_author/(\d+)/', views.del_author),
url(r'^edit_author/(?P<pk>\d+)/', views.edit_author),
######################动态路由test#############################
# 静态路由
url(r'^index/$', views.index),
# 动态路由
url(r'^index/[0-9]{3}/$', views.indexs),
url(r'^index/[0-9]{3}$|dex[123]{2}$', views.index), # http://127.0.0.1:8068/dex23
# 分组命名匹配
# 分组之后,会按照位置参数进行传参,参数个数无限制
# 传一个参数
url(r'^index/([0-9]{3})/$', views.years),
# 传两个参数,只要是分组,就当作是一个参数传递
url(r'^index/([a-z]{4})/(\d{4})/$', views.yearsmonth),
# 分组命名之后,将捕获的参数,会按照关键字参数进行传参,参数个数无限制
# 用分组或者命名分组看情况而定,推荐使用命名分组,名字和参数名要一样,因为是关键字参数
# 捕获的参数都是字符串形式,路径+参数,最后匹配的还是路径
url(r'^index/(?P<yy>[a-z]{3})/(?P<mm>\d{3})/$', views.year),
# 再形参位置给num传递了一个默认值,这样不传递参数就用num默认值
# 如果传入新的num值将覆盖掉num默认值,使用最新的num值
url(r'^index2/$', views.index2),
# http://127.0.0.1:8068/index2/page236/
url(r'^index2/page(?P<num>[0-9]{3})/$', views.index2),
######################路由分发器#######################
# 例如我访问的路径是:http://127.0.0.1:8068/app01/blog/666/
# 先将app01 和 url路径中的app01进行匹配,剩余的/blog/666/在app01下的路径相匹配
# app01/ 中的/不能不加,必须加上斜杠 app01和后面的路径要拼接所以要加
url(r'^app01/', include('app01.urls',namespace='app01')),
url(r'^app02/', include('app02.urls',namespace='app02')),
]
<file_sep>/BookPublisher/app01/urls.py
"""BookPublisher URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/',d include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
# 反向解析
url(r'^index/$', views.index,name='index'),
url(r'^index3/$', views.index3,y = 123),
# 因为我定义了name,所以无论我的路径怎么修改,前端都能通过name去找到对应的处理函数
# 静态路由
url(r'^blog999995588kkk/$', views.blog, name='blog'),
# 动态路由
url(r'^blogs/([0-9]{3})/$', views.blogs, name='blogs'),
# 分组命名匹配
# 分组之后,会按照位置参数进行传参,参数个数无限制
# 传一个参数
# http://127.0.0.1:8068/app01/blog/666/
url(r'^blog/([0-9]{3})/$', views.blog),
# 传两个参数,只要是分组,就当作是一个参数传递
# http://127.0.0.1:8068/app01/blog/abcd/8888/
url(r'^blog/(?P<years>[a-z]{4})/(?P<months>\d{4})/$', views.blog2, name='blog2'),
#####命名空间#########
url(r'^home/$', views.home, name='home'),
#特殊情况,先了解,app01下又包含了一个分发器
# url(r'^xxxx/', include('app01.xx',namespace='xx')),
]
| 9bb8af24d72562165083e2fee673118b72929250 | [
"Python"
] | 6 | Python | zhumingmei/Django001 | 0917c1ce2b5c1e3615cea2923603f91aa7775e92 | c18da940f4af1847986ea13168e92431faf64f88 |
refs/heads/master | <repo_name>tuan3w/googledocs<file_sep>/test/Readme.md
Feature extraction:
- feature extract by zones : 10 x10 --> 100 features
- feature based profiles --> 10 x 4 feature
- feature extracted based hotizontal projection 10 x2<file_sep>/README.md
OCR Tool like Google Docs <br/>
Select text and right click to copy content<file_sep>/highlight/js/goo.js
var goo = {
version: "0.0.1",
author: "TuanZendF"
};
goo.Initialize = function(container,width, height){
//create canvas div
goo.cv = document.createElement('canvas');
goo.privCanvas = document.createElement('canvas');
if (width && height && typeof width == 'number' && typeof height == 'number' ){
goo.privCanvas.width = goo.cv.width = width;
goo.privCanvas.height = goo.cv.height = height;
}
else {
goo.privCanvas.width = goo.cv.width = 400 ;
goo.privCanvas.height = goo.cv.height = 300;
}
goo.privCanvas.style.position = goo.cv.style.position = 'absolute';
goo.privCanvas.style.display = 'none';
goo.hlContainer = document.createElement('div');
goo.hlContainer.style.width = 0;
goo.hlContainer.style.height = 0;
goo.hlContainer.style.position = 'absolute';
goo.hlContainer.style.zIndex = "100";
var parrent = document.getElementById(container);
parrent.appendChild(goo.cv);
parrent.appendChild(goo.privCanvas);
parrent.appendChild(goo.hlContainer);
goo.container = parrent;
goo.ct = goo.cv.getContext('2d');
goo.privContext = goo.privCanvas.getContext('2d');
};
goo.setSize = function(w, h){
goo.container.style.width = goo.privCanvas.style.width = goo.cv.style.width = w + 'px';
goo.container.style.height = goo.privCanvas.style.height = goo.cv.style.height = h + 'px';
}
/*
* goo.Bitmap
*
*/
goo.Bitmap = function(img){
var that = this;
var tContext = goo.privContext;
var tCanvas = goo.privCanvas;
goo.setSize(img.width, img.height);
//get image data
tContext.drawImage(img, 0, 0)
var tempData = tContext.getImageData(0,0,img.width,img.height).data;
that.data = Matrix.create(img.height, img.width);
that.width = img.width;
that.height = img.height;
that.histGram = new Array(256);
for (var i=0; i< 256; i++)
that.histGram[i] = 0;
var index = 0;
for (var i=0; i< img.height; i++){
for (var j=0; j< img.width; j++){
that.data[i][j] = Math.floor(tempData[index] * 0.2 + tempData[index + 1] * 0.72 + 0.08 * tempData[index+2]);
index += 4;
}
}
//this.makeHistogram();
this.toBinary(150);
this.calcTextRange();
};
var Bitmap_proto = goo.Bitmap.prototype;
/**
* Draw Bitmap data
*/
Bitmap_proto.draw = function(x,y){
var img = goo.ct.createImageData(this.width, this.height);
var imgData = img.data;
var index = 0;
for (var i=0; i< this.height; i ++){
for (var j=0; j< this.width; j++){
imgData[index + 2] = imgData[index + 1]= imgData[index] = this.data[i][j];
imgData[index + 3] = 255;
index+=4;
}
}
if (x && y )
goo.ct.putImageData(img, x, y);
else
goo.ct.putImageData(img, 0, 0);
//goo.ct.strokeRect(this.left, this.top, this.right - this.left + 1, this.bottom - this.top +1 );
return this;
};
/**
* Add highlight tool
*/
Bitmap_proto.addTool = function(){
this.tool = new goo.Tool(this);
}
/**
* Inverse transform
*/
Bitmap_proto.inverse = function(){
for (var i=0; i< this.height; i++){
for (var j=0; j<this.width; j++){
this.data[i][j] = 255 - this.data[i][j];
}
}
}
/**
* Normalized transform
*/
Bitmap_proto.normalize = function() {
var min = 255;
var max = 0;
for (var i = 0; i < this.height; i++) {
for (var j = 0; j < this.width; j++) {
if (this.data[i][j] < min) {
min = this.data[i][j];
// alert(min);
}
if (this.data[i][j] > max)
max = this.data[i][j];
}
}
var range = max - min;
if (range == 255) //normalized
return;
for (var i = 0; i < this.height; i++) {
for (var j = 0; j < this.width; j++) {
this.data[i][j] = Math.floor(255 * 1.0 * (this.data[i][j] - min) / range);
}
}
};
/**
* History gram
*/
Bitmap_proto.makeHistogram = function(){
var data = this.data;
for (var i=0; i< this.height; i++){
for (var j=0; j< this.width; j++){
this.histGram[data[i][j]]++;
}
}
for (var i=0; i< 256; i++){
this.histGram[i] /= (this.width * this.height);
}
return this.histGram;
}
Bitmap_proto.histEqualize = function(){
this.makeHistogram();
var fixGray = new Array(256);
fixGray[0] =0;
for (var i=1; i< 256; i++){
fixGray[i] = Math.floor(fixGray[i-1] + this.histGram[i] * i);
}
//fix gray
for (var i=0; i< this.height; i++){
for (var j=0; j< this.width; j++){
this.data[i][j] = fixGray[this.data[i][j]];
}
}
}
/**
* convert to binary Image
*/
Bitmap_proto.toBinary = function(threshold) {
//alert('binary');
if (threshold) { //has threshold parameters
for (var i = 0; i < this.height; i++) {
for (var j = 0; j < this.width; j++) {
//alert(this.data + "is" );
if (this.data[i][j] < threshold)
this.data[i][j] = 0;
else
this.data[i][j] = 255;
}
}
} else {
//alert('local')
//use local threshold algorithm
//local size : 5x5
for (var x = 0; x < this.height - 5; x += 5) {
for (var y = 0; y < this.width - 5; y += 5) {
threshold_constrast = 10;
var min = 256, max = -1;
for (var i = x; i < x + 5; i++) {
for (var j = y; j < y + 5; j++) {
if (this.data[i][j] < min)
min = this.data[i][j];
if (this.data[i][j] > max)
max = this.data[i][j];
}
}
var local_constrast = max - min;
var mid_gray = (max + min) / 2;
if (local_constrast < threshold_constrast) {
if (mid_gray < 50)//foreground
for (var i = x; i < x + 5; i++) {
for (var j = y; j < y + 5; j++) {
this.data[i][j] = 0;
}
}
else
for (var i = x; i < x + 5; i++) {
for (var j = y; j < y + 5; j++) {
this.data[i][j] = 255;
}
}
} else {
for (var i = x; i < x + 5; i++) {
for (var j = y; j < y + 5; j++) {
if (this.data[i][j] < mid_gray) {
this.data[i][j] = 0;
} else {
this.data[i][j] = 255;
}
}
}
}
}
}
}
};
Bitmap_proto.calcTextRange = function(){
this.left = 0;
this.right = this.width - 1;
this.top = 0;
this.bottom = this.height - 1;
var isEdge = false;
var count = 0;
//find left border
while (!isEdge){
count = 0;
for (var i=0; i< this.height; i++)
if (this.data[i][this.left] == 0)
count ++;
if (count > 10){ //number of black points is larger than 10 points
isEdge = true;
}
else
this.left ++;
}
//find right border
isEdge = false;
while (!isEdge){
count = 0;
for (var i=0; i< this.height; i++)
if (this.data[i][this.right] == 0)
count ++;
if (count > 10){ //number of black points is larger than 10 points
isEdge = true;
}
else
this.right--;
}
//find top border
isEdge = false;
while (!isEdge){
count = 0;
for (var i=0; i< this.width; i++)
if (this.data[this.top][i] == 0)
count ++;
if (count > 10){ //number of black points is larger than 10 points
isEdge = true;
}
else
this.top++;
}
//find bottom border
isEdge = false;
while (!isEdge){
count = 0;
for (var i=0; i< this.width; i++)
if (this.data[this.bottom][i] == 0)
count ++;
if (count > 10){ //number of black points is larger than 10 points
isEdge = true;
}
else
this.bottom--;
}
console.log('top : ' + this.top + ',botom : ' + this.bottom + ', right: ' + this.right + ',left: ' + this.left);
};
/**
* Highlight tool
*
*/
goo.Tool = function(bitmap){
this.bitmap = bitmap;
this.hlSet = []; //highlight containers
var that = this;
var p1, p2;
var scrollLeft = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
var scrollTop = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
var x, y;
var isMousedown = false;
function getMousePos(e){
x = e.clientX - goo.cv.parentNode.offsetLeft + scrollLeft;
y = e.clientY - goo.cv.parentNode.offsetTop + scrollTop;
}
goo.container.addEventListener("mouseup", handler,false);
goo.container.addEventListener("mousedown", handler,false);
goo.container.addEventListener("mousemove", handler,false);
function handler(e){
//console.log(x + "," + y);
switch (e.type){
case "mousedown":
//alert('mouse down')
isMousedown = true;
goo.UnHighLight(); // un highlight
//alert(x);
getMousePos(e);
p1 = new Point(x,y);
break;
case "mousemove":
if (isMousedown) {
console.log("mouse is move")
getMousePos(e);
p2 = new Point(x,y);
if ( p1.y < p2.y)
that.process(p1, p2);
else
that.process(p2, p1);
}
break;
case "mouseup":
isMousedown = false;
//alert('mouse up')
break;
}
}
}
var tool_proto = goo.Tool.prototype;
/**
* Get highlight set
*/
tool_proto.getHighLightSet = function(){
return this.hlSet;
}
/**
* hihlight paragraph bound by 2 points
*
*/
tool_proto.process = function(p1, p2){
console.log('highlight')
var that = this;
//remove history highlight
goo.hlContainer.innerHTML = "";
var bitmap = that.bitmap.data;
var left = that.bitmap.left;
var right = that.bitmap.right;
var top = that.bitmap.top;
var bottom = that.bitmap.bottom;
//alert(p1.x + ',' + p2.x)
//not process if out of text range
if ((p1.x < that.bitmap.left && p2.x < that.bitmap.left )||
(p1.x > that.bitmap.right && p2.x > that.bitmap.right)||
( p2.y < that.bitmap.top)||
(p1.y > this.bitmap.bottom))
return;
//check line is empty
function isEmptyLine(y){
var blackPoints = 0;
for (var i= right; i>= left; i--)
if (bitmap[y][i] == 0) {
blackPoints ++;
if (blackPoints > 1) //number of black points is larger than 6 (in row)
return false;
}
return true;
}
//check collumn is empty
// x : x-coordinate
// y1,y2 : y-coordinate
function isEmptyCol(x,y1,y2){
for (var i = y1; i<= y2; i++)
if (bitmap[i][x] == 0)
return false;
return true;
}
// find nextEmptyline
// y {number} y-coordinate
function findNextEmptyLine(y){
y++;
if (y > bottom)
return y;
if (isEmptyLine(y))
while ( y<= bottom && isEmptyLine(y)) y++;
else {
while ( y<= bottom && !isEmptyLine(y)) y++;
y--;
}
return y;
}
function findEmptyCol(x,y1,y2,dir){
if ( dir == 0) {
if (isEmptyCol(x,y1,y2)) {
x++;
while (isEmptyCol(x,y1,y2) && x <= right) x++;
}else {
x --;
while (!isEmptyCol(x-1,y1,y2) && x >= left) x--;
}
}else {
if (isEmptyCol(x,y1,y2)) {
x--;
while (isEmptyCol(x,y1,y2) && x >= left) x--;
}else {
x ++;
while (!isEmptyCol(x+1,y1,y2) && x <= right) x++;
}
}
return x;
}
//get line of point
// p {Point}
var y1,y2,x1,x2;
//find top-line
y1 = p1.y;
that.hlSet = [];
if ( y1 < top)
y1 = top;
else
if (isEmptyLine(y1)) //move down
while (isEmptyLine(y1)) y1 ++;
else // move up
while (!isEmptyLine(y1)) y1 --;
//find bottom-line
var yB = p2.y;
if (yB > bottom)
yB = bottom + 1;
else if (isEmptyLine(yB)){
while (isEmptyLine(yB) ) yB--;
while (!isEmptyLine(yB)) yB --;
yB++;
}else {
while (!isEmptyLine(yB)) yB --;
yB++;
isBottomLine = false;
}
if (yB == y1) { //same line
//alert('same line');
y2 = findNextEmptyLine(y1);
x1 = p1.x < p2.x ? p1.x : p2.x;
x2 = p1.x + p2.x - x1;
console.log(p2.x - p1.x)
if ( p1.x < left)
x1= findEmptyCol(left,y1,y2,0);
else
x1 = findEmptyCol(x1,y1,y2,0);
if (p2.x > right)
x2 = findEmptyCol(right,y1,y2,1);
else
x2 = findEmptyCol(x2,y1,y2,1);
if (x1 < x2 ){
var o = {x: x1, y: y1, w: x2 -x1 +1, h: y2 - y1 + 1};
that.hlSet.push(o);
}
goo.Highlight(that.hlSet);
return;
}
else { //not in same line
//add top line
y2 = findNextEmptyLine(y1);
if ( p1.x < left)
x1= findEmptyCol(left,y1,y2,0);
else
x1 = findEmptyCol(p1.x,y1,y2,0);
x2 = findEmptyCol(right,y1,y2,1);
if (x1 < x2) {
var o = {x: x1, y: y1, w: x2 -x1 +1, h: y2 - y1 + 1};
that.hlSet.push(o);
}
y1 = findNextEmptyLine(y2);
y2 = findNextEmptyLine(y1);
//add next full-length line
while (y1 < yB) {
x1 = findEmptyCol(left, y1, y2, 0);
x2 = findEmptyCol(right, y1, y2, 1);
var o = {x: x1, y: y1, w: x2 -x1 +1, h: y2 - y1 + 1};
that.hlSet.push(o);
y1 = findNextEmptyLine(y2);
y2 = findNextEmptyLine(y1);
}
//add last line
y2 = findNextEmptyLine(y1);
x1 = findEmptyCol(left, y1, y2, 0);
x2 = p2.x;
if (x2 > right)
x2 = findEmptyCol(right, y1, y2, 1);
else
x2 = findEmptyCol(x2, y1, y2,1);
if ( x1 < x2 ){
var o = {x: x1, y: y1, w: x2 -x1 +1, h: y2 - y1 + 1};
that.hlSet.push(o);
}
goo.Highlight(that.hlSet); //highlight
}
};
/**
* goo.HighLight
* o {object} o.x : left coordinate
* o.y : top y coordinate
* o.w : width of rectangle
* o.h : height of rectangle
*/
goo.Highlight = function(set){
//console.log('highlight');
goo.UnHighLight();
for (var i=0; i< set.length; i++){
var o = set[i];
var ele = document.createElement('div');
ele.className="highlight";
ele.style.height = o.h + "px";
ele.style.left = o.x + "px";
ele.style.top = o.y + "px" ;
ele.style.width = o.w + 'px';
goo.hlContainer.appendChild(ele);
}
}
/**
* goo.UnHighLight
*/
goo.UnHighLight = function(){
goo.hlContainer.innerHTML = "";
}
<file_sep>/test/js/SampleData.js
function SampleData(letter, width, height){
this.grid = Matrix.create(height, width);
this.letter = letter;
};
SampleData.prototype.setData = function(x,y,v){
this.grid[x][y] = v;
};
SampleData.prototype.getData = function(x,y){
return this.grid[x][y];
};
SampleData.prototype.clear = function(){
Matrix.fill(this.grid, 0);
};
SampleData.prototype.getHeight = function(){
return this.grid.length;
};
SampleData.prototype.getWidth = function(){
return this.grid[0].length;
};
SampleData.prototype.setLetter = function(letter){
this.letter = letter;
};
SampleData.prototype.getLetter = function(){
return this.letter;
};
SampleData.prototype.clone = function(){
obj = SampleData(this.letter, this.getHeight()(), this.getWidth());
obj.grid = Matrix.clone(this.grid);
return obj;
}
| dad3ea8f931b02cc3134bddb452c523970d230fa | [
"Markdown",
"JavaScript"
] | 4 | Markdown | tuan3w/googledocs | 7cc4ac60a530e035cf9a029fc800fd30e923da65 | 293da2f4a93bd24a4ae4646ad8dc96355663c2e0 |
refs/heads/master | <file_sep>export class MarqueComputer {
name: string;
logo: string;
constructor(Pname = null, Plogo = null) {
this.name = Pname;
this.logo = Plogo;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
statusBtnAddComputer = false;
statusBtnAdminComputer = false;
constructor() { }
ngOnInit(): void {
}
clickAddComputer() {
this.statusBtnAddComputer = true;
this.statusBtnAdminComputer = false;
}
clickAdminComputer() {
this.statusBtnAddComputer = false;
this.statusBtnAdminComputer = true;
}
}
<file_sep>import { MarqueComputer } from './marque-computer';
describe('MarqueComputer', () => {
it('should create an instance', () => {
expect(new MarqueComputer()).toBeTruthy();
});
});
<file_sep>import { Injectable } from '@angular/core';
import { MarqueComputer } from '../models/marque-computer';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import {catchError, retry} from 'rxjs/internal/operators';
import { Computer } from '../models/computer';
@Injectable({
providedIn: 'root'
})
export class ComputerService {
computers: Computer[];
apiURL = 'http://localhost:3000/computers';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
marqueDisponible = [
new MarqueComputer('Dell', 'logoDell'),
new MarqueComputer('Hp', 'logoHp'),
new MarqueComputer('Apple', 'logoApple'),
new MarqueComputer('Asus', 'logoAsus'),
];
typeDisponible = ['Portable', 'Fixe', 'Tablette hybride' ];
categoryDisponible = ['Gaming', 'Bureautique', 'Premier Prix'];
constructor(private httpClient: HttpClient) {
this.computers = [];
}
// Afficher tous les ordinateurs
getAllComputer(): Observable<Computer []> {
return this.httpClient.get<Computer []>(this.apiURL).pipe(retry(1), catchError(this.handleError));
}
// Avoir l'ordinateur par ID
getComputerById(id: number): Observable<Computer> {
return this.httpClient.get<Computer>(this.apiURL + '/' + id).pipe(retry(1), catchError(this.handleError));
}
// Créer un ordinateur
addComputer(computer: Computer): Observable<Computer> {
return this.httpClient.post<Computer>(this.apiURL, computer).pipe(retry(1), catchError(this.handleError));
}
// Editer un ordinateur
editComputer(computer: Computer): Observable<Computer> {
return this.httpClient.put<Computer>(this.apiURL + '/' + computer.id, computer).pipe(retry(1), catchError(this.handleError));
}
// Suprimer un ordinateur
deleteComputer(id: number): Observable<Computer> {
return this.httpClient.delete<Computer>(this.apiURL + '/' + id).pipe(retry(1), catchError(this.handleError));
}
handleError(error) {
let errorMessage = '';
if ( error.error instanceof ErrorEvent ) {
errorMessage = error.error.message;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Computer } from 'src/app/models/computer';
import {faSpinner} from '@fortawesome/free-solid-svg-icons/faSpinner';
import { ActivatedRoute, Router } from '@angular/router';
import { ComputerService } from 'src/app/services/computer.service';
import { MarqueComputer } from 'src/app/models/marque-computer';
@Component({
selector: 'app-edit-computer',
templateUrl: './edit-computer.component.html',
styleUrls: ['./edit-computer.component.css']
})
export class EditComputerComponent implements OnInit {
isLoading: boolean;
id: number;
faSpinner = faSpinner;
editComputerForm: Computer;
marqueDisponible: MarqueComputer[];
typeDisponible: string[];
categoryDisponible: string[];
constructor(private route: ActivatedRoute, private computerService: ComputerService, private router: Router) { }
ngOnInit() {
this.marqueDisponible = this.computerService.marqueDisponible;
this.typeDisponible = this.computerService.typeDisponible;
this.categoryDisponible = this.computerService.categoryDisponible;
// tslint:disable-next-line: radix
this.id = parseInt(this.route.snapshot.paramMap.get('id'));
this.isLoading = true;
this.computerService.getComputerById(+this.route.snapshot.paramMap.get('id')).subscribe((data: Computer) => {
this.editComputerForm = data;
this.isLoading = false;
});
}
validationEditForm() {
this.computerService.editComputer(this.editComputerForm).subscribe((data: Computer) => this.router.navigate(['/home']));
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {faSpinner} from '@fortawesome/free-solid-svg-icons/faSpinner';
import { Computer } from 'src/app/models/computer';
import { ActivatedRoute, Router } from '@angular/router';
import { ComputerService } from 'src/app/services/computer.service';
@Component({
selector: 'app-detail-computer',
templateUrl: './detail-computer.component.html',
styleUrls: ['./detail-computer.component.css']
})
export class DetailComputerComponent implements OnInit {
faSpinner = faSpinner;
isLoading: boolean;
id: number;
infoComputer: Computer;
constructor(private route: ActivatedRoute, private computerService: ComputerService, private router: Router) { }
ngOnInit(): void {
// tslint:disable-next-line: radix
this.id = parseInt(this.route.snapshot.paramMap.get('id'));
this.isLoading = true;
this.computerService.getComputerById(+this.route.snapshot.paramMap.get('id')).subscribe((data: Computer) => {
this.infoComputer = data;
this.isLoading = false;
});
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AdminComputerComponent } from './admin-computer.component';
describe('AdminComputerComponent', () => {
let component: AdminComputerComponent;
let fixture: ComponentFixture<AdminComputerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AdminComputerComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AdminComputerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { ComputerService } from 'src/app/services/computer.service';
import {faSpinner} from '@fortawesome/free-solid-svg-icons/faSpinner';
import {faEye} from '@fortawesome/free-solid-svg-icons/';
import { Computer } from 'src/app/models/computer';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
isLoading: boolean;
faSpinner = faSpinner;
faEye = faEye;
computers: Computer[];
constructor(private computerService: ComputerService) { }
ngOnInit() {
this.isLoading = true;
return this.computerService.getAllComputer().subscribe((data: Computer []) => {
this.computers = data;
this.isLoading = false;
});
}
}
<file_sep>export class Computer {
id: number;
modele: string;
marque: string;
type: string;
category: string;
prixAchat: number;
prixVente: number;
dateEntreeStock: Date;
constructor(Pid = null, Pmodele = null, Pmarque = null, Ptype = null, Pcategory = null,
PprixAchat = null, PprixVente = null, PdateEntreeStock = null) {
this.id = Pid;
this.modele = Pmodele;
this.marque = Pmarque;
this.type = Ptype;
this.category = Pcategory;
this.prixAchat = PprixAchat;
this.prixVente = PprixVente;
this.dateEntreeStock = PdateEntreeStock;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {faSpinner} from '@fortawesome/free-solid-svg-icons/faSpinner';
import { Computer } from 'src/app/models/computer';
import { ComputerService } from 'src/app/services/computer.service';
import {faPen} from '@fortawesome/free-solid-svg-icons/';
import {faTrash} from '@fortawesome/free-solid-svg-icons/';
@Component({
selector: 'app-admin-computer',
templateUrl: './admin-computer.component.html',
styleUrls: ['./admin-computer.component.css']
})
export class AdminComputerComponent implements OnInit {
faSpinner = faSpinner;
faPen = faPen;
faTrash = faTrash;
isLoading: boolean;
computers: Computer[];
constructor(private computerService: ComputerService) { }
ngOnInit() {
this.isLoading = true;
return this.computerService.getAllComputer().subscribe((data: Computer []) => {
this.computers = data;
this.isLoading = false;
});
}
deleteArticle(id: number) {
this.computerService.deleteComputer(id).subscribe((data: Computer) => {
this.computerService.getAllComputer().subscribe((result: Computer[] ) => {
this.computers = result;
});
});
}
}
| 90956416ed123dcb90b883dc3c04298dcccd49c1 | [
"TypeScript"
] | 10 | TypeScript | FRAIZZY/Exam-Angular-Martins-Anthony | 74b3ba9dc75476dd0dbe7ab27f2e630c8190467a | f4dee3893cf54145617b4f1319d5a333aed9a455 |
refs/heads/master | <file_sep># MachineLearning
this is my machine learning code
<file_sep># -*- coding: utf-8 -*-
import operator
from numpy import *
import matplotlib
import matplotlib.pyplot as plt
from os import listdir #用于显示文件夹下的文件
def classify(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
temp = tile(inX, (dataSetSize, 1))
diffMat = tile(inX, (dataSetSize, 1)) - dataSet
sqdiffMat = diffMat ** 2
sqDistances = sqdiffMat.sum(axis=1)
distances = sqDistances ** 0.5
sortedDistIndices = distances.argsort()
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistIndices[i]]
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
sortedClassCount = sorted(classCount.iteritems(),
key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
def file2matrix(filename):
fr = open(filename)
arrayoLines = fr.readlines() # 读取每一行数据,结果应该是list 40920 8.326976 0.953952 3
numberofLines = len(arrayoLines)
returnMat = zeros((numberofLines, 3)) # 1000行 3列
classLabelVector = []
index = 0
for line in arrayoLines:
line = line.strip() # 去除\r\n
listFromLine = line.split('\t') # 得到一个list 储存这一行的4个数据
returnMat[index, :] = listFromLine[0: 3] # 拿一到三个数据到index行
classLabelVector.append(int(listFromLine[-1])) # [-1]是取最后一个数据
index += 1
return returnMat, classLabelVector
def autoNorm(dataSet):
minVals = dataSet.min(0)
maxVals = dataSet.max(0)
ranges = maxVals - minVals
normDataSet = zeros((shape(dataSet))) # 一千行,三列,全零元素
m = dataSet.shape[0] # m = 1000
tmp = tile(minVals, (m, 1)) # minVal是个3元素行矩阵,tile函数将该矩阵扩展成3列1000行的矩阵,每行都是minVal
normDataSet = dataSet - tile(minVals, (m, 1))
normDataSet = normDataSet / tile(ranges, (m, 1)) # 在numpy中/表示矩阵中对应元素相除,linalg.solve(A,B)表示矩阵除法
return normDataSet, ranges, minVals
def datingClassTest():
hoRatio = 0.05
datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
normMat, ranges, minVals = autoNorm(datingDataMat)
m = normMat.shape[0]
numTestVecs = int(m * hoRatio)
errorCount = 0.0
for i in range(numTestVecs):
classfierResult = classify(normMat[i, :], normMat[numTestVecs:m, :], datingLabels[numTestVecs:m], 3)
print "the classifier came back with :%d , the real answer is :%d " % (classfierResult, datingLabels[i])
if (classfierResult != datingLabels[i]): errorCount += 1.0
print "total error is %f" % (errorCount / float(numTestVecs))
def img2vector(filename):
returnVect = zeros((1,1024))
fr = open(filename)
for i in range(32):
lineStr = fr.readline()
for j in range (32):
returnVect[0, 32*i+j] = int(lineStr[j])
return returnVect
def handwritingClassTest():
hwLabels = []
trainingFileList = listdir('trainingDigits')
m = len(trainingFileList)
trainingMat = zeros((m , 1024))
for i in range(m):
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('_')[0])
hwLabels.append(classNumStr)
trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)
testFileList = listdir('testDigits')
errorCount = 0.0
mTest = len(testFileList)
for j in range(mTest):
fileNameStr = testFileList[j]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('_')[0])
vectorUnderTest = img2vector('testDigits/%s' %fileNameStr)
classfyResult = classify(vectorUnderTest, trainingMat , hwLabels ,3)
print "the classfier comes back with %d ,the right answer is %d" %(classfyResult, classNumStr)
if(classfyResult != classNumStr):
errorCount += 1.0
print "\nthe total error is %d" %errorCount
print "\nthe error rate is %f" %(errorCount/float(mTest))
if __name__ == '__main__':
handwritingClassTest()
<file_sep># MachineLearning
Some machine learn algorithms implemented by me using Python
| c15977e1961141f0ebe3a6ee0810d4c8eff228df | [
"Markdown",
"Python"
] | 3 | Markdown | fredliao123/MachineLearning | 28c1d3961421481561dfeb8d94d10655f883341f | a4036a668a78cc411bcbf13230136b012c9b00d5 |
refs/heads/master | <repo_name>silcam/helpdesk<file_sep>/db/migrate/20170724074916_add_description_solution_at_job.rb
class AddDescriptionSolutionAtJob < ActiveRecord::Migration[5.1]
def change
add_column :job_requests, :description_solution, :string
add_column :job_requests, :time_spent, :integer
add_column :job_requests, :date_return, :date_return
add_column :job_requests, :statut, :string
end
end
<file_sep>/app/controllers/connexion_controller.rb
class ConnexionController < ApplicationController
def index
@users = User.all
end
def create
@current_user = User.where(login: params[:login], password: params[:password]).first
if @current_user
flash[:info]= " Welcome #{@current_user.last_name} "
session[:id] = @current_user.id
redirect_to "/connexion/new"
else
flash[:info]= "Error: verify your login and/or password"
session[:id] = nil
redirect_to "/"
end
end
def destroy
session[:id]= nil
flash[:info]="Good Bye!!! You are deconnected"
redirect_to "/"
end
def new
@jobs= JobRequest.all
@users = User.all
@departments = Departement.all
@sales = Sale.all
@devices = Device.all
@jobs_solve = JobRequest.where(statut: "ok")
@jobs_not_solve = JobRequest.where(statut: "not")
#@devices_stock_warning = Device.where(stock: < 6)
#@devices_stock_low = Device.where(stock: < 2)
#devices_stock_ok = Device.where(stock: >= 6)
@session = session[:id]
@current_user = User.find(session[:id])
end
end
<file_sep>/app/models/departement.rb
class Departement < ApplicationRecord
end
<file_sep>/app/models/dept.rb
class Dept < ApplicationRecord
end
<file_sep>/app/controllers/job_requests_controller.rb
class JobRequestsController < ApplicationController
def log_in
if session[:id] == nil
flash[:info]="Enter you login and password"
redirect_to "/"
else
@current_user = User.find(session[:id])
end
end
def index
log_in
@jobs = JobRequest.all
@users = User.all
@solutions = Solution.all
end
def create
JobRequest.create job_params
redirect_to '/job_requests/new'
end
def new
log_in
@job_request = JobRequest.new
@departments = Departement.all
@session = session[:id]
end
def show
log_in
@job = JobRequest.find(params[:id])
end
def destroy
JobRequest.find(params[:id]).destroy
redirect_to '/job_requests'
end
def update
JobRequest.find(params[:id]).update description_solution: params[:description_solution], time_spent: params[:timp_spent], date_return: params[:date_return], statut: params[:statut]
redirect_to "/job_requests/#{params[:id]}"
end
def job_params
params.require(:job_request).permit(:name_customer, :department, :email, :telephone, :priority, :account_charge, :cash, :device_name, :model, :parts_atteched, :description_problem, :date_arrive, :user_id,:description_solution, :timp_spent, :date_return, :statut)
end
end
<file_sep>/test/controllers/job_requests_controller_test.rb
require 'test_helper'
class JobRequestsControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get job_requests_index_url
assert_response :success
end
end
<file_sep>/app/controllers/sales_controller.rb
class SalesController < ApplicationController
def log_in
if session[:id] == nil
flash[:info]="Enter you login and password"
redirect_to "/"
else
@current_user = User.find(session[:id])
end
end
def index
log_in
@users = User.all
end
end
<file_sep>/test/controllers/solutions_controller_test.rb
require 'test_helper'
class SolutionsControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get solutions_index_url
assert_response :success
end
end
<file_sep>/db/migrate/20170724222551_add_stock_in_table_device.rb
class AddStockInTableDevice < ActiveRecord::Migration[5.1]
def change
add_column :devices, :stock, :integer
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
def log_in
if session[:id] == nil
flash[:info]="Enter you login and password"
redirect_to "/"
else
@current_user = User.find(session[:id])
end
end
def index
log_in
@users = User.all
end
def create
@user_admin = User.where(password: params[:password]).first
if (@user_admin and (@user_admin.privilege == "root"))
redirect_to '/users/new'
else
redirect_to '/users'
end
end
def show
log_in
@user = User.find(params[:id])
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :users
resources :devices
resources :sales
resources :job_requests
resources :solutions
resources :connexion
resources :admins
get '/job_requests/jobs_solve'
root 'connexion#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
<file_sep>/db/migrate/20170719112854_table_depts.rb
class TableDepts < ActiveRecord::Migration[5.1]
def change
create_table :depts
add_column :depts, :name, :string
end
end
<file_sep>/app/controllers/devices_controller.rb
class DevicesController < ApplicationController
def log_in
if session[:id] == nil
flash[:info]="Enter you login and password"
redirect_to "/"
else
@current_user = User.find(session[:id])
end
end
def index
log_in
@users = User.all
@devices = Device.all
end
def show
log_in
@users = User.all
@device = Device.find(params[:id])
end
def new
log_in
@users = User.all
@devices_hard = Device.where(category: "hardware")
@devices_net = Device.where(category: "network")
@devices_soft = Device.where(category: "software")
@devices_electro = Device.where(category: "electronic")
@devices_electri = Device.where(category: "electricity")
end
def update
Device.find(params[:id]).update stock: somme(params[:stock], params[:last_stock])
redirect_to '/devices/#{params[:id]}'
end
def create
Device.create(name: params[:name], category: params[:category], model: params[:model], description: params[:description], user_id: params[:user_id], stock: params[:stock])
redirect_to '/devices'
end
def somme a , b
return a.to_i + b.to_i
end
end
<file_sep>/app/models/job_request.rb
class JobRequest < ApplicationRecord
end
| 814ffeb4579f64c031ab2efe5336d62832e20583 | [
"Ruby"
] | 14 | Ruby | silcam/helpdesk | 0e197aec680eabeaecb835641f9c0a49e38494b3 | 12b8e58c14e7ee2e107bf47d984921b27cec1ebc |
refs/heads/master | <file_sep>import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'home', loadChildren: () => import('./pages/home/home.module').then( m => m.HomePageModule)},
{ path: 'story-point', loadChildren: () => import('./pages/story-point/story-point.module').then( m => m.StoryPointPageModule)},
{ path: 'story-detail/:id', loadChildren: () => import('./pages/story-detail/story-detail.module').then(m => m.StoryDetailPageModule) },
{ path: 'login', loadChildren: () => import('./pages/login/login.module').then( m => m.LoginPageModule)},
{ path: 'story-listing', loadChildren: () => import('./pages/story-listing/story-listing.module').then( m => m.StoryListingPageModule)},
{ path: 'view-story-point', loadChildren: './pages/view-story-point/view-story-point.module#ViewStoryPointPageModule' },
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import * as _ from 'lodash';
import { Router } from '@angular/router';
@Component({
selector: 'app-story-point',
templateUrl: './story-point.page.html',
styleUrls: ['./story-point.page.scss'],
})
export class StoryPointPage implements OnInit {
dataArr:any;
constructor(private router: Router) { }
ngOnInit() {
let data = this.getFibonacciSeries(10);
this.dataArr = _.uniq(data);
}
getFibonacciSeries (n) {
if (n===1) {
return [0, 1];
} else {
let s = this.getFibonacciSeries(n - 1);
s.push(s[s.length - 1] + s[s.length - 2]);
return s;
}
};
goToStoryDetailPage(i) {
this.router.navigate(['story-detail', i]);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataFeederService {
constructor(private http: HttpClient) { }
addStoryPoint(body) {
return this.http.post('http://localhost:9000/addStoryPoint', body);
}
getStoryPoint() {
return this.http.get('http://localhost:9000/getStoryPoint');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ActionSheetController } from '@ionic/angular';
@Component({
selector: 'app-story-listing',
templateUrl: './story-listing.page.html',
styleUrls: ['./story-listing.page.scss'],
})
export class StoryListingPage implements OnInit {
storyList = [
{
'number': 'ORANGE-21873',
'title': 'MFA feature flag lift'
},
{
'number': 'ORANGE-21875',
'title': 'Reset MFA'
}
]
constructor(
private router: Router,
public actionSheetController: ActionSheetController
) { }
ngOnInit() {
}
async presentActionSheet(story) {
localStorage.setItem('story',story.number)
const actionSheet = await this.actionSheetController.create({
header: 'Actions',
buttons: [{
text: 'Do story pointing',
handler: () => {
this.goToStoryPointing();
}
}, {
text: 'View Story points',
handler: () => {
this.goToAllStoryPoint();
}
}, {
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
}]
});
await actionSheet.present();
}
goToStoryPointing() {
this.router.navigate(['story-point']);
}
goToAllStoryPoint() {
this.router.navigate(['view-story-point']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DataFeederService } from 'src/app/services/data-feeder.service';
@Component({
selector: 'app-story-detail',
templateUrl: './story-detail.page.html',
styleUrls: ['./story-detail.page.scss'],
})
export class StoryDetailPage implements OnInit {
storyPoint;
userStoryPoint = {"name":"","story":"","point":""}
constructor(
private router:Router,
private dataFeederService: DataFeederService
) { }
ngOnInit() {
this.storyPoint = this.router.url.split('/').pop();
this.userStoryPoint.point = this.storyPoint;
this.userStoryPoint.name = localStorage.getItem('name');
this.userStoryPoint.story = localStorage.getItem('story');
this.dataFeederService.addStoryPoint(this.userStoryPoint).subscribe(res=>{console.log(res)});
}
goToViewStoryPoints() {
this.router.navigate(['view-story-point']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { DataFeederService } from 'src/app/services/data-feeder.service';
import { debug } from 'util';
@Component({
selector: 'app-view-story-point',
templateUrl: './view-story-point.page.html',
styleUrls: ['./view-story-point.page.scss'],
})
export class ViewStoryPointPage implements OnInit {
storyPointList;
story;
constructor(private dataFeederService: DataFeederService) { }
ngOnInit() {
this.story = localStorage.getItem('story');
this.getData();
}
getData() {
this.dataFeederService.getStoryPoint().subscribe(res=>{
console.log(res);
debugger;
this.storyPointList= res['record'].filter((item) => {
if(item.story === this.story) {
return item;
}
});
console.log(this.storyPointList)
})
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { DataFeederService } from './data-feeder.service';
describe('DataFeederService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: DataFeederService = TestBed.get(DataFeederService);
expect(service).toBeTruthy();
});
});
<file_sep>## Ng Scrum Assist
## Goal
The Goal is to achieve effective refinement with story poiting.
## Functionality
- All team member will access the application by entering name
- PO/ Scrum master can enter story to be refined
- User can select the story and it will redirect user to story point page
- Team member can select the story point and we will have summary of user and story Map
## Techonology
- Angular8
- Ionic 5
- Node Js
- Sass
## Future Scope
- Integrating with Jira to update the story point
- Provide uploding csv file to upload story list.
## Team Member
- Asween
- Mahil
- Poornesh
- Lavanya
- Yoga
| bc1fca6d2056177a1ede8540e9ff36a5f6a83ca7 | [
"Markdown",
"TypeScript"
] | 8 | TypeScript | asweenravi/scrum | a98b8269815f34b910ea6f0f4b4fd265c0d4c3aa | cedd26cf835000a99ab0da178a58fadc8200a6c7 |
refs/heads/master | <file_sep>
import os
from sklearn.cluster import KMeans
from sklearn.neighbors import NearestNeighbors
from sklearn.svm import SVC
from gensim.models import Doc2Vec
import numpy as np
import matplotlib.pyplot as plt
import pickle
docvecmodel=Doc2Vec.load(os.getcwd()+'/models/docvecmodel.model')
docvectors=np.asarray(docvecmodel.docvecs)
dim_reduc_method='PCA'
labels=['dem','dem','repub','repub']
data=docvectors
SVC_classifier=SVC()
#SVC_classifier.fit(docvectors,labels)
print('start KMeans...')
docvec_kmeans=KMeans(n_clusters=3, random_state=0).fit(docvectors)
print('Kmeans complete!')
lowddoc2vec=pickle.load(open(os.getcwd()+'/graphs/low_D_doc2vec/doc2vec_2d_'+dim_reduc_method,'rb'))
for i in range(0,lowddoc2vec.shape[0]):
if docvec_kmeans.labels_[i]==0:
plt.plot(lowddoc2vec[i,0],lowddoc2vec[i,1],'ok')
elif docvec_kmeans.labels_[i]==1:
plt.plot(lowddoc2vec[i,0],lowddoc2vec[i,1],'or')
elif docvec_kmeans.labels_[i]==2:
plt.plot(lowddoc2vec[i,0],lowddoc2vec[i,1],'ob')
plt.show()
<file_sep>
from sklearn.decomposition import NMF,LatentDirichletAllocation
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
#from gensim.models import LdaModel
import pickle
import os
import numpy as np
import math
import wordcloud
from wordcloud import WordCloud,STOPWORDS
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time
from sklearn.manifold import TSNE,MDS
from sklearn.decomposition import PCA
import random
##########Options########################
train_model=False
train_dim_red=True
dim_red_method='TSNE'#TSNE, MDS or PCA
num_dim=2#number of dimensions to reduce to in the dimensionality reduction
##########Options########################
##########Global Parameters########################
add_stopwords=['permalink','set','default','input','value','video','filter','output','frame','options','stream','new','click','window','share','subscribe','embed','reply','gold','save']
stopwords=list(set(STOPWORDS))
stopwords=stopwords+add_stopwords
no_top_words = 10
no_features=1000
no_topics=100
##########Global Parameters########################
def train_test_split_data(data,labels):
shufflevar=list(zip(data,labels))
random.shuffle(shufflevar)
data,labels=zip(*shufflevar)
train=data[0:11000]#finished here
test=data[11000:]
trainlabels=labels[0:11000]
testlabels=labels[0:11000]
pickle.dump(train,open(os.getcwd()+'/train_test_split/train_data','wb'))
pickle.dump(test,open(os.getcwd()+'/train_test_split/test_data','wb'))
pickle.dump(trainlabels,open(os.getcwd()+'/train_test_split/train_labels','wb'))
pickle.dump(testlabels,open(os.getcwd()+'/train_test_split/test_labels','wb'))
return train,trainlabels,test,testlabels
def runSKLearnLDA(doc_collection,docidentifiers):
print('Start SKLearnLDA...')
tf_vec=CountVectorizer(max_df=0.95,min_df=2,max_features=no_features,stop_words='english')
termfreq=tf_vec.fit_transform(doc_collection)
#Run LDA using scitkit learn
print('Constructing LDA model...')
startlda=time.time()
ldamodel=LatentDirichletAllocation(n_components=no_topics, max_iter=5, learning_method='online', learning_offset=50.,random_state=0).fit(termfreq,docidentifiers)
print('LDA Model Construction Took:'+str((time.time()-startlda)/60)+' minutes.')
startldavecs=time.time()
print('Constructing LDA vectors...')
#ldavecs = LatentDirichletAllocation(n_components=no_topics, max_iter=5, learning_method='online', learning_offset=50.,random_state=0).fit_transform(termfreq,docidentifiers)
ldavecs=ldamodel.transform(termfreq)
print('LDA Vector Construction Took:'+str((time.time()-startldavecs)/60)+' minutes.')
print('Completed SKLearnLDA!')
pickle.dump(ldavecs,open(os.getcwd()+'/models/LDA/ldavectors','wb'))
pickle.dump(ldamodel,open(os.getcwd()+'/models/LDA/ldamodel','wb'))
pickle.dump(termfreq,open(os.getcwd()+'/models/LDA/term_frequency','wb'))
return termfreq,ldamodel,ldavecs
def display_topics(model, feature_names, no_top_words):
for topic_idx, topic in enumerate(model.components_):
print("Topic %d:" % (topic_idx))
print(" ".join([feature_names[i] for i in topic.argsort()[:-no_top_words - 1:-1]]))
def jaccard_similarity(query, document):
intersection = set(query).intersection(set(document))
union = set(query).union(set(document))
return float(len(intersection))/float(len(union))
def display_reduced_dim(data,dim_reduc_type,docidentifiers):
if train_dim_red:
print('Starting '+dim_reduc_type+' embedding...')
startembed=time.time()
if dim_reduc_type=='TSNE':
model_embedded=TSNE(n_components=num_dim).fit_transform(data)
elif dim_reduc_type=='MDS':
model_embedded=MDS(n_components=num_dim).fit_transform(data)
elif dim_reduc_type=='PCA':
model_embedded=PCA(n_components=num_dim).fit_transform(data)
else:
print('Error: dimensionality reduction method not supported (use TSNE, MDS or PCA)')
print(dim_reduc_type+' embedding took: '+str((time.time()-startembed)/60)+' minutes.')
else:
print('Loading reduced dimension representation of data....')
model_embedded=pickle.load(open(os.getcwd()+'/graphs/low_D_doc2vec/LDAvec_2d_'+dim_reduc_type,'rb'))
print('Loaded!')
if num_dim==2:
print('Length of DocSentiment='+str(len(docidentifiers)))
print('Length of model_embedded='+str(len(model_embedded)))
pickle.dump(model_embedded,open(os.getcwd()+'/graphs/low_D_doc2vec/LDAvec_2d_'+dim_reduc_type,'wb'))
for ii in range(0,model_embedded.shape[0]):
print('plotted point '+str(ii))
if docidentifiers[ii]==0:# in ['conservative','republican','libertarian']
plt.plot(model_embedded[ii,0],model_embedded[ii,1],'or')
elif docidentifiers[ii]==1:# in ['liberal','democrats','socialism']
plt.plot(model_embedded[ii,0],model_embedded[ii,1],'ob')
elif docidentifiers[ii]==2:# in ['moderatepolitics','politics']
plt.plot(model_embedded[ii,0],model_embedded[ii,1],'ok')
plt.show()
elif num_dim==3:
pickle.dump(model_embedded,open(os.getcwd()+'/graphs/low_D_doc2vec/LDAvec_3d'+dim_reduc_type,'wb'))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(model_embedded[:,0],model_embedded[:,1],model_embedded[:,2],c='r',marker='o')
plt.show()
else:
print('Error: Please use either 2 or 3 dimensions for dimensionality reduction!')
return model_embedded
#subreds=['conservative','liberal']
'''
wordcloudtext=str()
for i in documents:
wordcloudtext=wordcloudtext+' '+i
'''
'''
#NMF is able to use tf-idf
tfidf_vectorizer=TfidfVectorizer(max_df=0.95,min_df=2,max_features=no_features,stop_words='english')
tfidf=tfidf_vectorizer.fit_transform(documents)
tfidf_feature_names=tfidf_vectorizer.get_feature_names()
# Run NMF
nmf = NMF(n_components=no_topics, random_state=1, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf)
'''
#LDA can only use raw term counts for LDA because it is a probabilitstic graphical model
#tf_vectorizer=CountVectorizer(max_df=0.95,min_df=2,max_features=no_features,stop_words='english')
#tf=tf_vectorizer.fit_transform(documents)
loaddata=pickle.load(open(os.getcwd()+'/data/postdata2.pickle','rb'))
urls=loaddata.url
documents=list()
docsentiment=list()
docIDs=list()
for i,j,k in zip(loaddata.websitetext,loaddata.submissionID,loaddata.subreddit):
if (type(i) is str):
documents.append(i)
docIDs.append(j)
if k in ['conservative','republican','libertarian','the_congress']:
docsentiment.append(0)#conservative
elif k in ['liberal','democrats','politics','socialism']:
docsentiment.append(1)#liberal
elif k=='moderatepolitics':
docsentiment.append(2)#neutral
else:
docsentiment.append(3)#unclassified
traindocs,trainlabels,testdocs,testlabels=train_test_split_data(documents,docsentiment)
if train_model:
tf_train, lda_train, ldavectors_train = runSKLearnLDA(traindocs+testdocs,trainlabels+testlabels)
else:
#tf=pickle.load(open(os.getcwd()+'/models/LDA/term_frequency','rb'))
lda_train=pickle.load(open(os.getcwd()+'/models/LDA/ldamodel','rb'))
ldavectors_train=pickle.load(open(os.getcwd()+'/models/LDA/ldavectors','rb'))
display_reduced_dim(ldavectors_train,dim_red_method,trainlabels)
<file_sep>
from sklearn.decomposition import NMF,LatentDirichletAllocation
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
#from gensim.models import LdaModel
import pickle
import os
import numpy as np
import math
import wordcloud
from wordcloud import WordCloud,STOPWORDS
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time
from sklearn.manifold import TSNE,MDS
from sklearn.decomposition import PCA
import random
##########Options########################
docvectype='tfidf'
train_model=True
train_dim_red=True
dim_red_method='TSNE'#TSNE, MDS or PCA
num_dim=2#number of dimensions to reduce to in the dimensionality reduction
##########Options########################
##########Global Parameters########################
##########Global Parameters########################
def train_test_split_data(data,labels):
shufflevar=list(zip(data,labels))
random.shuffle(shufflevar)
data,labels=zip(*shufflevar)
train=data[3000:]#finished here
test=data[0:3000]
trainlabels=np.asarray(labels[3000:])
testlabels=np.asarray(labels[0:3000])
pickle.dump(train,open(os.getcwd()+'/train_test_split/train_data','wb'))
pickle.dump(test,open(os.getcwd()+'/train_test_split/test_data','wb'))
pickle.dump(trainlabels,open(os.getcwd()+'/train_test_split/train_labels','wb'))
pickle.dump(testlabels,open(os.getcwd()+'/train_test_split/test_labels','wb'))
return train,trainlabels,test,testlabels
def vectorize_docs(doc_collection,model):
if docvectype=='LDA':
tf_vec=CountVectorizer(max_df=maxdfval,min_df=2,max_features=no_features,stop_words=stopwords)
termfreq=tf_vec.fit_transform(doc_collection)
return model.transform(termfreq)
elif docvectype=='NMF':
tfidf_vec=TfidfVectorizer(max_df=maxdfval,min_df=2,max_features=no_features,stop_words=stopwords)
termfreqidf=tfidf_vec.fit_transform(doc_collection)
return model.transform(termfreqidf)
def runSKLearnLDA(doc_collection,docidentifiers):
print('Start SKLearnLDA...')
tf_vec=CountVectorizer(max_df=maxdfval,min_df=2,max_features=no_features,stop_words=stopwords)
termfreq=tf_vec.fit_transform(doc_collection)
#Run LDA using scitkit learn
print('Constructing LDA model...')
startlda=time.time()
ldamodel=LatentDirichletAllocation(n_components=no_topics, max_iter=10, learning_method='online', learning_offset=50.,random_state=0).fit(termfreq,docidentifiers)#
print('LDA Model Construction Took:'+str((time.time()-startlda)/60)+' minutes.')
startldavecs=time.time()
print('Constructing LDA vectors...')
#ldavecs = LatentDirichletAllocation(n_components=no_topics, max_iter=5, learning_method='online', learning_offset=50.,random_state=0).fit_transform(termfreq,docidentifiers)
ldavecs=ldamodel.transform(termfreq)
print('LDA Vector Construction Took:'+str((time.time()-startldavecs)/60)+' minutes.')
print('Completed SKLearnLDA!')
pickle.dump(ldavecs,open(os.getcwd()+'/models/LDA/ldavectors','wb'))
pickle.dump(ldamodel,open(os.getcwd()+'/models/LDA/ldamodel','wb'))
pickle.dump(termfreq,open(os.getcwd()+'/models/LDA/term_frequency','wb'))
return termfreq,ldamodel,ldavecs
def runSKLearnNMF(doc_collection,docidentifiers):
print('Start SKLearnNMF...')
#NMF is able to use tf-idf
startnmfvecs=time.time()
tfidf_vectorizer=TfidfVectorizer(max_df=maxdfval,min_df=2,max_features=no_features,stop_words=stopwords)
tfidf=tfidf_vectorizer.fit_transform(doc_collection)
#tfidf_feature_names=tfidf_vectorizer.get_feature_names()
# Run NMF
nmfmodel = NMF(n_components=no_topics, random_state=1, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf)
nmfvecs=nmfmodel.transform(tfidf)
print('NMF Vector Construction Took:'+str((time.time()-startnmfvecs)/60)+' minutes.')
print('Completed SKLearnNMF!')
pickle.dump(nmfvecs,open(os.getcwd()+'/models/NMF/nmfvectors','wb'))
pickle.dump(nmfmodel,open(os.getcwd()+'/models/NMF/nmfmodel','wb'))
pickle.dump(tfidf,open(os.getcwd()+'/models/NMF/tfidf','wb'))
return tfidf,nmfmodel,nmfvecs
def display_topics(model, feature_names, no_top_words):
for topic_idx, topic in enumerate(model.components_):
print("Topic %d:" % (topic_idx))
print(" ".join([feature_names[i] for i in topic.argsort()[:-no_top_words - 1:-1]]))
def jaccard_similarity(query, document):
intersection = set(query).intersection(set(document))
union = set(query).union(set(document))
return float(len(intersection))/float(len(union))
def display_reduced_dim(data,dim_reduc_type,docidentifiers):
if train_dim_red:
print('Length of data: '+str(data.shape[0]))
print('Length of doc identifiers: '+str(len(docidentifiers)))
print('Starting '+dim_reduc_type+' embedding...')
startembed=time.time()
if dim_reduc_type=='TSNE':
model_embedded=TSNE(n_components=num_dim).fit_transform(data)
elif dim_reduc_type=='MDS':
model_embedded=MDS(n_components=num_dim).fit_transform(data)
elif dim_reduc_type=='PCA':
model_embedded=PCA(n_components=num_dim).fit_transform(data)
else:
print('Error: dimensionality reduction method not supported (use TSNE, MDS or PCA)')
print(dim_reduc_type+' embedding took: '+str((time.time()-startembed)/60)+' minutes.')
else:
print('Loading reduced dimension representation of data....')
model_embedded=pickle.load(open(os.getcwd()+'/graphs/low_D_doc2vec/LDAvec_2d_'+dim_reduc_type,'rb'))
print('Loaded!')
if num_dim==2:
print('Length of DocSentiment='+str(len(docidentifiers)))
print('Length of model_embedded='+str(len(model_embedded)))
pickle.dump(model_embedded,open(os.getcwd()+'/graphs/low_D_doc2vec/LDAvec_2d_'+dim_reduc_type,'wb'))
for ii in range(0,model_embedded.shape[0]):
print('plotted point '+str(ii))
if docidentifiers[ii]==0:# in ['conservative','republican','libertarian']
plt.plot(model_embedded[ii,0],model_embedded[ii,1],'or')
elif docidentifiers[ii]==1:# in ['liberal','democrats','socialism']
plt.plot(model_embedded[ii,0],model_embedded[ii,1],'ob')
elif docidentifiers[ii]==2:# in ['moderatepolitics','politics']
plt.plot(model_embedded[ii,0],model_embedded[ii,1],'ok')
plt.axis('off')
plt.savefig('foo.png')
elif num_dim==3:
pickle.dump(model_embedded,open(os.getcwd()+'/graphs/low_D_doc2vec/LDAvec_3d'+dim_reduc_type,'wb'))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(model_embedded[:,0],model_embedded[:,1],model_embedded[:,2],c='r',marker='o')
plt.axis('off')
plt.savefig('foo.png')
plt.show()
else:
print('Error: Please use either 2 or 3 dimensions for dimensionality reduction!')
return model_embedded
#subreds=['conservative','liberal']
'''
wordcloudtext=str()
for i in documents:
wordcloudtext=wordcloudtext+' '+i
'''
'''
#NMF is able to use tf-idf
tfidf_vectorizer=TfidfVectorizer(max_df=0.95,min_df=2,max_features=no_features,stop_words='english')
tfidf=tfidf_vectorizer.fit_transform(documents)
tfidf_feature_names=tfidf_vectorizer.get_feature_names()
# Run NMF
nmf = NMF(n_components=no_topics, random_state=1, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf)
'''
#LDA can only use raw term counts for LDA because it is a probabilitstic graphical model
#tf_vectorizer=CountVectorizer(max_df=0.95,min_df=2,max_features=no_features,stop_words='english')
#tf=tf_vectorizer.fit_transform(documents)
if train_model:
if docvectype=='LDA':
loaddata=pickle.load(open(os.getcwd()+'/data/postdata2.pickle','rb'))
urls=loaddata.url
documents=list()
docsentiment=list()
docIDs=list()
for i,j,k in zip(loaddata.websitetext,loaddata.submissionID,loaddata.subreddit):
if k is not 'moderatepolitics':
if (type(i) is str):
print('::::::::::::Doc Type: '+str(k))
documents.append(i)
docIDs.append(j)
if k in ['conservative','republican','libertarian','the_congress']:
docsentiment.append(0)#conservative
elif k in ['liberal','democrats','politics','socialism']:
docsentiment.append(1)#liberal
traindocs,trainlabels,testdocs,testlabels=train_test_split_data(documents,docsentiment)
tf_train, lda_train, ldavectors_train = runSKLearnLDA(traindocs,trainlabels)
pickle.dump(ldavectors_train,open(os.getcwd()+'/models/LDA/ldavectors_train','wb'))
pickle.dump(tf_train,open(os.getcwd()+'/models/LDA/tf_train','wb'))
pickle.dump(np.asarray(trainlabels),open(os.getcwd()+'/models/LDA/trainlabels','wb'))
pickle.dump(vectorize_docs(testdocs,lda_train),open(os.getcwd()+'/models/LDA/ldavectors_test','wb'))
pickle.dump(np.asarray(testlabels),open(os.getcwd()+'/models/LDA/testlabels','wb'))
elif docvectype=='NMF':
loaddata=pickle.load(open(os.getcwd()+'/data/postdata2.pickle','rb'))
urls=loaddata.url
documents=list()
docsentiment=list()
docIDs=list()
for i,j,k in zip(loaddata.websitetext,loaddata.submissionID,loaddata.subreddit):
if k is not 'moderatepolitics':
if (type(i) is str):
documents.append(i)
docIDs.append(j)
if k in ['conservative','republican','libertarian','the_congress']:
docsentiment.append(0)#conservative
elif k in ['liberal','democrats','politics','socialism']:
docsentiment.append(1)#liberal
traindocs,trainlabels,testdocs,testlabels=train_test_split_data(documents,docsentiment)
tfidf_train, nmf_train, nmfvectors_train = runSKLearnNMF(traindocs,trainlabels)
pickle.dump(nmfvectors_train,open(os.getcwd()+'/models/NMF/nmfvectors_train','wb'))
pickle.dump(np.asarray(trainlabels),open(os.getcwd()+'/models/NMF/trainlabels','wb'))
pickle.dump(vectorize_docs(testdocs,nmf_train),open(os.getcwd()+'/models/NMF/nmfvectors_test','wb'))
pickle.dump(np.asarray(testlabels),open(os.getcwd()+'/models/NMF/testlabels','wb'))
pickle.dump(tfidf_train,open(os.getcwd()+'/models/NMF/testlabels','wb'))
else:
if docvectype=='LDA':
#tf=pickle.load(open(os.getcwd()+'/models/LDA/term_frequency','rb'))
lda=pickle.load(open(os.getcwd()+'/models/LDA/ldamodel','rb'))
ldavectors_train=pickle.load(open(os.getcwd()+'/models/LDA/ldavectors_train','rb'))
trainlabels=pickle.load(open(os.getcwd()+'/models/LDA/trainlabels','rb'))
elif docvectype=='NMF':
#tf=pickle.load(open(os.getcwd()+'/models/LDA/term_frequency','rb'))
nmf=pickle.load(open(os.getcwd()+'/models/NMF/nmfmodel','rb'))
nmfvectors_train=pickle.load(open(os.getcwd()+'/models/NMF/nmfvectors_train','rb'))
trainlabels=pickle.load(open(os.getcwd()+'/models/NMF/trainlabels','rb'))
#display_reduced_dim(ldavectors_train,dim_red_method,trainlabels)
| 26c0aa96e5366fa5c42d70cc040a0a8adf76b164 | [
"Python"
] | 3 | Python | bensuutari/lda_word_vecs | a74f47fd0b371f9f6d4a0ea436c57679b7e9d18b | f678413610e760865d272545236109c8b04bce73 |
refs/heads/master | <repo_name>dkarathanas/computer-networks<file_sep>/relay_node.py
import socket
import platform
import subprocess
import urllib2
import time
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_PSS
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
from Crypto import Random
#### Functions ####
#
# Pings at server number_of_iteration times
#
def ping(server, number_of_iterations):
# Change param depending on operating system
param = '-n' if platform.system().lower() == 'windows' else '-c'
# Create command for pinging
command = ['ping', param, str(number_of_iterations), server]
# Run command
return subprocess.check_output(command)
#
# Calculate mean latency of ping
#
def calculate_mean_latency(ping_output):
ping_output_split = ping_output.split('\n')
latency_times = []
for line in ping_output_split:
time_index = line.find("time=")
if time_index != -1:
ms_index = line.find("ms")
latency_times.append(float(line[time_index+5:ms_index-1]))
return sum(latency_times)/len(latency_times)
#
# Checks if a string is a number or not
#
def is_number(s):
try:
int(s)
return True
except:
return False
#
# Run traceroute to given server and return number_of_hops
#
def traceroute(server):
# Change param depending on operating system
param = 'tracert' if platform.system().lower() == 'windows' else 'traceroute'
# Create command for pinging
command = [param, server]
# Run command
traceroute_output = subprocess.check_output(command)
traceroute_output_split = traceroute_output.split('\n')
number_of_hops = 0
for line in traceroute_output_split:
if is_number(line[0:2]):
number_of_hops += 1
return number_of_hops
#
# Generate RSA pair keys
#
def generate_RSA_pair():
key = RSA.generate(2048, e=65537)
return key
#
# Verify publickey sent from other
#
def verify_publickey(publickey_message):
begin_index = publickey_message.find("-----BEGIN PUBLIC KEY-----")
signature_str = publickey_message[0:begin_index]
publickey_str = publickey_message[begin_index:]
publickey_hash = SHA256.new(publickey_str).digest()
signature_tuple = eval(signature_str)
publickey = RSA.importKey(publickey_str)
if publickey.verify(publickey_hash, signature_tuple):
return publickey
else:
print " >> Error: Can not verify public key."
exit()
#
# Class for AES Encryption
#
class AES_encryption:
def __init__(self, key):
self.key = key
def pad(self, message):
return message + b"\0" * (AES.block_size - len(message) % AES.block_size)
def encrypt(self, message, key, key_size = 256):
message = self.pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
def decrypt(self, cipher_text, key):
iv = cipher_text[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plain_text = cipher.decrypt(cipher_text[AES.block_size:])
return plain_text.rstrip(b"\0")
def rsa_decrypt(cipher, priv_key):
decrypted_message = PKCS1_OAEP.new(priv_key)
return decrypted_message.decrypt(cipher)
def verify(message, signature, pub_key):
hash = SHA256.new()
hash.update(message)
verifier = PKCS1_PSS.new(pub_key)
return verifier.verify(hash, signature)
#### Get my hostname and my ip address ####
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
#### Read port from file ####
file_port = open("relay_nodes.txt", "r")
for line in file_port:
words = line.split()
if(words[0] == hostname):
if(words[1] != IPAddr):
print "Error: this is not my IP Address!"
port = int(words[2])
break
file_port.close()
print "=========================================="
print "|| My name is: " + hostname + "\t\t\t||"
print "|| My IP Address is: " + IPAddr + "\t||"
print "|| My port is: " + str(port) + "\t\t\t||"
print "=========================================="
#### Generate keys ####
key = generate_RSA_pair()
public_key = key.publickey()
while True:
#### Establish TCP socket and wait for client ####
relay_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
relay_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
while True:
try:
relay_socket.bind(('', port))
break
except:
print " >> Port not available. Trying again in 5 seconds"
time.sleep(5)
relay_socket.listen(1)
print "\n==================================="
print "I'm ready to take action."
connection_socket = relay_socket.accept()[0]
#### Reading, verifying client's public key ####
clients_publickey_message = connection_socket.recv(2048)
clients_publickey = verify_publickey(clients_publickey_message)
#### Send signed public key to relay ####
public_key_str = public_key.exportKey("PEM")
hash = SHA256.new(public_key_str).digest()
signature = key.sign(hash, '')
signature_str = str(signature)
signed_publickey_message = signature_str + public_key_str
connection_socket.send(signed_publickey_message)
#### Get aes key ####
aes_key_message = connection_socket.recv(2048)
decrypted_message1 = rsa_decrypt(aes_key_message[0:256], key)
decrypted_message2 = rsa_decrypt(aes_key_message[256:], key)
decrypted_message = decrypted_message1 + decrypted_message2
aes_key = decrypted_message[0:32]
signature = decrypted_message[32:]
if verify(aes_key, signature, clients_publickey) == False:
print "Error: Verifying message including client's public key failed."
connection_socket.close()
exit()
aes_obj = AES_encryption(aes_key)
print "Just got aes key"
#### Receive hostname and number of pings ####
cipher = connection_socket.recv(2048)
try:
plaintext = aes_obj.decrypt(cipher, aes_key)
except:
continue
mode = plaintext
print("Command from client: " + plaintext)
if mode != "offline":
plaintext = plaintext.split(" ")
end_server = plaintext[0]
number_of_iterations = plaintext[1]
#### Perform measurements and send response to client ####
try:
ping_output = ping(end_server, number_of_iterations)
mean_latency = calculate_mean_latency(ping_output)
except:
mean_latency = -1
try:
number_of_hops = traceroute(end_server)
except:
number_of_hops = -1
response = str(mean_latency) + " " + str(number_of_hops)
cipher = aes_obj.encrypt(response, aes_key)
connection_socket.send(cipher)
connection_socket.close()
else:
cipher = aes_obj.encrypt("ok", aes_key)
connection_socket.send(cipher)
#### Wait for client to send file to download ####
port_unusable = 0
if mode != "offline":
relay_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
relay_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
while True:
try:
relay_socket.bind(('', port + 1))
print "Ready for phase 2"
break
except:
print " >> Port not available. Trying again in 5 seconds"
time.sleep(5)
# port_unusable = 1
# break
# if port_unusable == 1:
# continue
relay_socket.listen(1)
connection_socket = relay_socket.accept()[0]
cipher = connection_socket.recv(2048)
try:
message = aes_obj.decrypt(cipher, aes_key)
except:
continue
if message == 'close':
print "I'm not the chosen one. ;("
else:
print "File to download: " + message
filedata = urllib2.urlopen(message)
data_to_write = filedata.read()
cipher = aes_obj.encrypt(data_to_write, aes_key)
cipher_len = str(len(cipher))
encrypted_cipher_len = aes_obj.encrypt(cipher_len, aes_key)
connection_socket.send(encrypted_cipher_len)
cipher_ok = connection_socket.recv(2048)
message = aes_obj.decrypt(cipher_ok, aes_key)
if message != 'ok':
connection_socket.close()
exit()
data_len = len(cipher)
chunks = data_len/1000
remainder = data_len % 1000
for i in range(0, chunks + 1):
if i == chunks:
start = i * 1000
end = start + remainder
else:
start = i * 1000
end = start + 1000
connection_socket.send(cipher[start:end])
#### Terminate connection with client ####
connection_socket.close()<file_sep>/README.md
# computer-networks
The project's description is at project-hy335b.pdf.
The report is CS-335 Project Report and the presentation is CS335 - Presentation file.
Best project of the semester among 30 teams.
Awarded as with a 3-month scholarship at the Telecommunications and Networks laborotary, FORTH Greece.
Developed alongside <NAME>.
<file_sep>/client.py
import sys
import socket
import platform
import subprocess
import os
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_PSS
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
from Crypto import Random
import urllib2
import threading
import time
import csv
import datetime
import pandas
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
import random
import matplotlib.pyplot as plt
import numpy as np
#### Functions ####
#
# Pings at server number_of_iteration times
#
def ping(server, number_of_iterations):
# Change param depending on operating system
param = '-n' if platform.system().lower() == 'windows' else '-c'
# Create command for pinging
command = ['ping', param, str(number_of_iterations), server]
# Run command
return subprocess.check_output(command)
#
# Calculate mean latency of ping
#
def calculate_mean_latency(ping_output):
ping_output_split = ping_output.split('\n')
latency_times = []
for line in ping_output_split:
time_index = line.find("time=")
if time_index != -1:
ms_index = line.find("ms")
latency_times.append(float(line[time_index+5:ms_index]))
return sum(latency_times)/len(latency_times)
#
# Checks if a string is a number or not
#
def is_number(s):
try:
int(s)
return True
except:
return False
#
# Run traceroute to given server and return number_of_hops
#
def traceroute(server):
# Change param depending on operating system
if platform.system().lower() == 'windows':
command = ["tracert", "-d", "-w", "100", server]
else:
command = ["traceroute", server]
# Run command
traceroute_output = subprocess.check_output(command)
traceroute_output_split = traceroute_output.split('\n')
number_of_hops = 0
for line in traceroute_output_split:
if is_number(line[0:3]):
number_of_hops += 1
return number_of_hops
#
# Verify publickey sent from other
#
def verify_publickey(publickey_message):
begin_index = publickey_message.find("-----BEGIN PUBLIC KEY-----")
signature_str = publickey_message[0:begin_index]
publickey_str = publickey_message[begin_index:]
publickey_hash = SHA256.new(publickey_str).digest()
signature_tuple = eval(signature_str)
publickey = RSA.importKey(publickey_str)
if publickey.verify(publickey_hash, signature_tuple):
return publickey
else:
print " >> Error: Can not verify public key."
exit()
#
# Initiate client-relay and relay-end host communication using threads
#
def initiate(relay_nodes_list, hostname, number_of_pings):
threads_relay_to_end = []
threads_client_to_relay = []
direct_thread = threading.Thread( target = direct_func, args = (hostname, number_of_pings))
direct_thread.start()
for i in relay_nodes_list:
t1 = threading.Thread( target = relay_to_end, args = (hostname, i, number_of_pings))
t2 = threading.Thread( target = client_to_relay, args = (hostname, i, number_of_pings))
threads_relay_to_end.append(t1)
threads_client_to_relay.append(t2)
for i in threads_client_to_relay:
i.start()
for i in threads_relay_to_end:
i.start()
for i in threads_client_to_relay:
i.join()
for i in threads_relay_to_end:
i.join()
direct_thread.join()
# print "All threads for measurements joined!"
#
# Initiate threads to download file from relay using TCP Sockets
#
def download_threads(url, chosen_relay, data_to_write, mode):
threads = []
if mode == "online":
for relay in relay_nodes_list:
command = url if relay.relay_name == chosen_relay else 'close'
curr_thread = threading.Thread( target = download_file_online, args = (relay, command, data_to_write))
threads.append(curr_thread)
elif mode == "offline":
for relay in relay_nodes_list:
command = url if relay.relay_name == chosen_relay else 'close'
curr_thread = threading.Thread( target = download_file_offline, args = (relay, command, data_to_write))
threads.append(curr_thread)
for i in threads:
i.start()
for i in threads:
i.join()
# print "All threads for downloading image joined!"
#
# Open TCP Socket and send command to relay.
# Exchange RSA key pair
# Exchange AES
# Send command to download file
#
def download_file_offline(relay, command, data_to_write):
relay_name = relay.relay_name
relay_ip = relay.ip
relay_port = relay.port
#### Generate AES key and object ####
aes_key = generate_aes_key()
aes_obj = AES_encryption(aes_key)
try:
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.connect((relay_ip , relay_port))
#### Exchange public keys ####
clientSocket.send(signed_publickey_message)
relays_publickey = clientSocket.recv(2048)
relays_publickey = verify_publickey(relays_publickey)
#### Send AES key ####
signature = sign(aes_key, key)
signature_str = str(signature)
signed_message = aes_key + signature_str
cipher1 = rsa_encrypt(signed_message[0:200], relays_publickey)
cipher2 = rsa_encrypt(signed_message[200:], relays_publickey)
cipher = cipher1 + cipher2
clientSocket.send(cipher)
relay.aes_key = aes_key
#### Send offline-mode announcement command ####
message = "offline"
cipher = aes_obj.encrypt(message, aes_key)
clientSocket.send(cipher)
cipher = clientSocket.recv(2048)
plaintext = aes_obj.decrypt(cipher, aes_key)
if plaintext != "ok":
print " >> Error: Did not receive ok from relay in offline-mode"
clientSocket.close()
return
#### Send command to download file ####
cipher = aes_obj.encrypt(command, aes_key)
clientSocket.send(cipher)
if command == 'close':
clientSocket.close()
return
#### Receive length of file ####
cipher = clientSocket.recv(2048)
plaintext = aes_obj.decrypt(cipher, aes_key)
file_size = int(plaintext)
# print "File's size to receive is: " + plaintext
cipher = aes_obj.encrypt("ok", aes_key)
clientSocket.send(cipher)
#### Receive, decrypt and save file ####
cipher = ""
iter = 0
while 1:
iter += 1
cipher += clientSocket.recv(2048)
# print "Length of cipher: " + str(len(cipher))
if len(cipher) == file_size or iter == 30:
break
message = aes_obj.decrypt(cipher, aes_key)
# print "Length of message: " + str(len(message))
data_to_write.append(message)
except:
clientSocket.close()
return
#
# Open TCP Socket and send command to relay(download file if this is chosen relay)
#
def download_file_online(relay, command, data_to_write):
relay_name = relay.relay_name
relay_ip = relay.ip
relay_port = relay.port + 1
#### Create AES object with previous aes key ####
aes_key = relay.aes_key
aes_obj = AES_encryption(aes_key)
try:
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.connect((relay_ip , relay_port))
#### Send command ####
cipher = aes_obj.encrypt(command, aes_key)
clientSocket.send(cipher)
if command == 'close':
clientSocket.close()
return
#### Receive length of file ####
cipher = clientSocket.recv(2048)
plaintext = aes_obj.decrypt(cipher, aes_key)
file_size = int(plaintext)
# print "File's size to receive is: " + plaintext
cipher = aes_obj.encrypt("ok", aes_key)
clientSocket.send(cipher)
#### Receive, decrypt and save file ####
cipher = ""
iter = 0
while 1:
iter += 1
cipher += clientSocket.recv(2048)
# print "Length of cipher: " + str(len(cipher))
if len(cipher) == file_size or iter == 30:
break
message = aes_obj.decrypt(cipher, aes_key)
# print "Length of message: " + str(len(message))
data_to_write.append(message)
except:
clientSocket.close()
return
#
# Send order to relay to execute measurements from relay to end-users
#
def relay_to_end(hostname, relay, number_of_pings):
relay_name = relay.relay_name
relay_ip = relay.ip
relay_port = relay.port
connection_failed = 0
#### Generate AES key and object ####
aes_key = generate_aes_key()
aes_obj = AES_encryption(aes_key)
try:
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.connect((relay_ip , relay_port))
#### Exchange public keys ####
clientSocket.send(signed_publickey_message)
relays_publickey = clientSocket.recv(2048)
relays_publickey = verify_publickey(relays_publickey)
#### Send AES key ####
signature = sign(aes_key, key)
signature_str = str(signature)
signed_message = aes_key + signature_str
cipher1 = rsa_encrypt(signed_message[0:200], relays_publickey)
cipher2 = rsa_encrypt(signed_message[200:], relays_publickey)
cipher = cipher1 + cipher2
clientSocket.send(cipher)
#### Send hostname and number of pings to relay ####
sentence = hostname+" "+number_of_pings
cipher = aes_obj.encrypt(sentence, aes_key)
clientSocket.send(cipher)
#### Get measurements from relay ####
cipher = clientSocket.recv(1024)
plaintext = aes_obj.decrypt(cipher, aes_key)
plaintext = plaintext.split(" ")
#### Close connection with relay ####
relay.aes_key = aes_key
clientSocket.close()
except:
connection_failed = 1
#### Save data ####
if connection_failed == 0:
results_relay_to_end_dict[relay_name] = log(float(plaintext[0]), int(plaintext[1]))
else:
results_relay_to_end_dict[relay_name] = log(-1, -1)
#
# Execute pings and traceroute from client to each relay
#
def client_to_relay(hostname, relay_nodes_list, number_of_pings):
ping_output = ping(relay_nodes_list.ip, number_of_pings)
mean_latency = calculate_mean_latency(ping_output)
number_of_hops = traceroute(relay_nodes_list.ip)
results_client_to_relay_dict[relay_nodes_list.relay_name] = log(mean_latency,number_of_hops)
#
# Execute direct client-end pings and traceroute
#
def direct_func(hostname, number_of_pings):
try:
direct_ping_output = ping(hostname, number_of_pings)
direct_mean_latency = calculate_mean_latency(direct_ping_output)
direct_number_of_hops = traceroute(hostname)
except:
print " >> Warning: End server is not reachable via direct path."
globals()["direct_path"] = log(-1, -1)
return
globals()["direct_path"] = log(direct_mean_latency,direct_number_of_hops)
#
# Results object definition
#
class log(object):
def __init__(self, latency, number_of_hops):
self.latency = latency
self.number_of_hops = number_of_hops
#
# Generate RSA pair keys
#
def generate_RSA_pair(key_size = 2048):
random_generator = Random.new().read
key = RSA.generate(key_size, e=65537)
return key
#
# Relay node object definition
#
class relay_node(object):
def __init__(self, relay_name, ip, port):
self.relay_name = relay_name
self.ip = ip
self.port = port
self.aes_key = -1
#
# Class used for coloring
#
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#
# Class for AES Encryption
#
class AES_encryption:
def __init__(self, key):
self.key = key
def pad(self, message):
return message + b"\0" * (AES.block_size - len(message) % AES.block_size)
def encrypt(self, message, key, key_size = 256):
message = self.pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
def decrypt(self, cipher_text, key):
iv = cipher_text[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plain_text = cipher.decrypt(cipher_text[AES.block_size:])
return plain_text.rstrip(b"\0")
#
# Generate a key for AES CBC 256 encryption
#
def generate_aes_key(length = 32):
return os.urandom(length)
#
# RSA Padding and encrypting
#
def rsa_encrypt(message, public_key):
cipher = PKCS1_OAEP.new(public_key)
return cipher.encrypt(message)
#
# RSA Padding and decrypting
#
def rsa_decrypt(cipher, priv_key):
decrypted_message = PKCS1_OAEP.new(priv_key)
return decrypted_message.decrypt(cipher)
#
# RSA signing
#
def sign(message, priv_key):
hash = SHA256.new()
hash.update(message)
signer = PKCS1_PSS.new(priv_key)
return signer.sign(hash)
#
# RSA verifying signature
#
def verify(message, signature, pub_key):
hash = SHA256.new()
hash.update(message)
verifier = PKCS1_PSS.new(public_key)
return verifier.verify(hash, signature)
#
# Creating log file entry
#
def insert_to_log_file(hour, best_path, file_size, url):
relay_names_list = ["direct"]
url_list = []
for i in relay_nodes_list:
relay_names_list.append(i.relay_name)
for i in files2download:
url_list.append(files2download[i])
# print relay_names_list
# print url_list
counter = 1
for i in relay_names_list:
if best_path == i:
best_path_label = counter
break
counter += 1
#### Decide end_user based on url ####
counter = 1
for i in url_list:
if url == i:
end_user_label = counter
break
counter += 1
#### Decide time by splitting the day into 4 parts ####
if 0 <= hour <= 5:
hour_entry = 1
elif 6 <= hour <= 11:
hour_entry = 2
elif 12 <= hour <= 17:
hour_entry = 3
else:
hour_entry = 4
#### Decide label for criteria ####
if criteria == 'latency':
criteria_label = 1
else:
criteria_label = 2
#### Writing to logfile ####
row = [hour_entry, end_user_label, file_size, criteria_label, best_path_label]
print "Logfile entry: " + str(row)
if os.path.isfile('logFile.csv') == False:
with open('logFile.csv', 'a+') as logFile:
writer = csv.writer(logFile)
header = ["Hour", "Endserver", "Filesize", "Criteria", "Path"]
writer.writerow(header)
with open('logFile.csv', 'a+') as logFile:
writer = csv.writer(logFile)
writer.writerow(row)
logFile.close()
#
# Class used for analysis when reading from csv
#
class log_file_entry:
def __init__(self, hour, end_server, file_size, criteria, path):
self.hour = hour
self.end_server = end_server
self.file_size = file_size
self.criteria = criteria
self.path = path
#
# Class used for analysis when reading from csv
#
class path_analysis:
def __init__(self, name, selected_latency, selected_number_of_hops):
self.name = name
self.selected_latency = selected_latency
self.selected_number_of_hops = selected_number_of_hops
#
# Function for generating labels for every rect in the plot
#
def autolabel(rects, xpos='center'):
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0, 'right': 1, 'left': -1}
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(offset[xpos]*3, 3), # use 3 points offset
textcoords="offset points", # in both directions
ha=ha[xpos], va='bottom')
#### Read servers and relay nodes from file ####
end_servers = dict()
relay_nodes_list = []
files2download = dict()
results = dict()
results_relay_to_end_dict = dict()
results_client_to_relay_dict = dict()
end_servers_list = []
if sys.argv[1] == "-e" and sys.argv[3] == "-r":
try:
with open(sys.argv[2]) as file:
data = file.readline()
while data:
data = data.split(',')
data[1] = data[1].strip()
end_servers[data[1]] = data[0]
end_servers_list.append(data[0])
data = file.readline()
except:
print " >> Error: Couldn't open end servers file."
exit()
try:
with open(sys.argv[4]) as file:
data = file.readline()
while data:
data = data.split(' ')
relay_nodes_list.append(relay_node(data[0],data[1],int(data[2])))
data = file.readline()
except:
print " >> Error: Couldn't open relay nodes file."
exit()
else :
print " >> Error: Wrong arguments, possible call is:"
print " > python client.py -e endservers.txt -r relaynodes.txt"
exit()
#### Generate RSA keys pair ####
key = generate_RSA_pair()
public_key = key.publickey()
#### Create public key signed message ####
public_key_str = public_key.exportKey("PEM")
hash = SHA256.new(public_key_str).digest()
signature = key.sign(hash, '')
signature_str = str(signature)
signed_publickey_message = signature_str + public_key_str
#### Select mode ####
print "[1] Default"
print "[2] Offline"
print "[3] Train"
print "[4] Analysis"
while True:
input = raw_input("Please select one of the modes above (1-4): ")
if is_number(input) == False:
continue
input = int(input)
if input < 1 or input > 4:
continue
elif input == 1:
mode = "default"
print "\n ## Default mode ## \n"
elif input == 2:
mode = "offline"
print "\n ## Offline mode ## \n"
elif input == 3:
mode = "train"
print "\n ## Train mode ## \n"
else:
mode = "analysis"
print "\n ## Analysis mode ## \n"
break
#### Offline-mode ####
correct_input = 0
if mode == 'offline':
print "Please choose which file you want to download:"
with open("files2download.txt") as file:
counter = 1
for f in file:
files2download[counter] = f.rstrip()
print "[" + str(counter) + "]\t" + f
counter = counter + 1
while True:
input = raw_input("Enter number from 1-%d:\n" %len(files2download))
if is_number(input) == False or int(input) < 1 or int(input) > len(files2download):
continue
break
end_user_label = int(input)
url = files2download[end_user_label]
file = urllib2.urlopen(url)
meta = file.info()
file_size = meta.getheaders("Content-Length")[0]
while True:
input = raw_input("\nPlease enter (l)atency or number_of_(h)ops to pick your criteria: ")
if input == 'l' or input == 'L':
criteria_label = 1
break
elif input == 'h' or input == 'H':
criteria_label = 2
break
hour = datetime.datetime.now().hour
if 0 <= hour <= 5:
hour_entry = 1
elif 6 <= hour <= 11:
hour_entry = 2
elif 12 <= hour <= 17:
hour_entry = 3
else:
hour_entry = 4
#### Create relays list to match indexes ####
relay_names_list = ["direct"]
for i in relay_nodes_list:
relay_names_list.append(i.relay_name)
#### Machine learning algorithm ####
df_base = pandas.read_csv("logFile.csv", header=0)
df = df_base.dropna(how='any')
X = df.iloc[:, :-1]
y = df.iloc[:, -1]
clf_0 = SVC(gamma='auto').fit(X, y)
# clf_1 = LogisticRegression().fit(X, y)
# clf_2 = RandomForestClassifier().fit(X, y)
# print "Score of LR: " + str(clf_1.score(X,y))
# print "Score of RF: " + str(clf_2.score(X,y))
ML_result = clf_0.predict([[hour, end_user_label, file_size, criteria_label]])
#### Translate ML_result ####
ML_result_int = int(ML_result[0])
if ML_result_int == 1:
best_path = "direct"
else:
ML_result_int -= 1
best_path = relay_names_list[ML_result_int]
scores = cross_val_score(clf_0, X, y, cv=5)
print "\nMachine Learning"
print "=================="
# print "ML_result = " + str(ML_result)
print "Best path: " + str(best_path)
print "Score: " + str(scores.mean())
#### Download file ####
t0 = time.time()
file_name_list = url.split('/')
file_name = file_name_list[len(file_name_list) - 1]
path_to_save = './' + file_name
data_to_write = []
if best_path == "direct":
try:
filedata = urllib2.urlopen(url)
except:
print " >> Error: Couldn't download file."
exit()
data_to_write.append(filedata.read())
download_threads(url, best_path, data_to_write, "offline")
else:
download_threads(url, best_path, data_to_write, "offline")
t1 = time.time()
total_time_for_download = t1-t0
print "\nTotal time to download image is: %.2f seconds" %total_time_for_download
try:
with open(path_to_save, 'wb') as f:
f.write(data_to_write[0])
except:
print " >> Error: Couldn't save file."
exit()
#### Training mode ####
if mode == "train":
while True:
input = raw_input("Please enter number of iterations: ")
if is_number(input):
break
iterations = int(input)
mode = "train"
for z in range(0, iterations):
#### Decide Randomly ####
hostname_rand = random.randint(0,len(end_servers) - 1)
number_of_pings = random.randint(1, 20)
criteria = random.randint(1,2)
if criteria == 1:
criteria = "latency"
else:
criteria = "number_of_hops"
#### Get hostname and url ####
hostname = end_servers_list[hostname_rand]
print "\n===================================================================="
print "Random: " + hostname + " " + str(number_of_pings) + " " + criteria
#### Inititate threads for measurements ####
initiate(relay_nodes_list, hostname, str(number_of_pings))
#### Calculate results ####
for i in relay_nodes_list:
log1 = results_client_to_relay_dict[i.relay_name]
log2 = results_relay_to_end_dict[i.relay_name]
if log2.latency == -1:
results[i.relay_name] = log(-1, -1)
else:
results[i.relay_name] = log(log1.latency + log2.latency, log1.number_of_hops + log2.number_of_hops)
results["direct"] = log(direct_path.latency, direct_path.number_of_hops)
print "\nPATH\t" + " Latency\t" + " Number of hops"
print "========================================="
for i in results:
if results[i].latency == -1:
continue
print str(i) + "\t" + str(results[i].latency) + "\t\t" + str(results[i].number_of_hops)
#### Find best baths ####
min_latency_path = "none"
min_number_of_hops_path = "none"
min_latency = -1
min_number_of_hops = -1
for i in results:
if results[i].latency == -1:
continue
if min_latency == -1:
min_latency = results[i].latency
min_latency_path = i
elif results[i].latency == min_latency:
if results[i].number_of_hops < results[min_latency_path].number_of_hops:
min_latency_path = i
elif results[i].latency < min_latency:
min_latency = results[i].latency
min_latency_path = i
if min_number_of_hops == -1:
min_number_of_hops = results[i].number_of_hops
min_number_of_hops_path = i
elif results[i].number_of_hops == min_number_of_hops:
if results[i].latency < results[min_number_of_hops_path].latency:
min_number_of_hops_path = i
elif results[i].number_of_hops < min_number_of_hops:
min_number_of_hops = results[i].number_of_hops
min_number_of_hops_path = i
#### Choose best path based on criteria ####
best_path = "none"
if min_latency_path == "none":
print "Sorry no paths found"
if criteria == "latency":
best_path = min_latency_path
else:
best_path = min_number_of_hops_path
print "\nBased on " + criteria + " best path is: " + best_path + "\n"
#### Choose file to download ####
data_to_write = []
with open("files2download.txt") as file:
counter = 1
for f in file:
files2download[counter] = f.rstrip()
counter = counter + 1
url = files2download[hostname_rand + 1]
download_threads(url, "none", data_to_write, "online")
if best_path == "none":
continue
#### Get size of file ####
file = urllib2.urlopen(url)
meta = file.info()
file_size = meta.getheaders("Content-Length")[0]
#### Create entry ####
hour = datetime.datetime.now().hour
insert_to_log_file(hour, best_path, file_size, url)
exit()
#### Analysis mode ####
if mode == "analysis":
#### Read logfile, create list with entries ####
log_file_entries = []
line_count = 0
with open('logfile.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
if line_count == 0:
line_count += 1
continue
elif len(row) == 0:
continue
log_file_entries.append(log_file_entry(int(row[0]), int(row[1]), int(row[2]), int(row[3]), int(row[4])))
line_count += 1
#### Count for paths ####
paths_analysis_list = []
paths_analysis_list.append(path_analysis('direct', 0, 0))
for i in relay_nodes_list:
paths_analysis_list.append(path_analysis(i.relay_name, 0, 0))
for i in log_file_entries:
if i.criteria == 1:
paths_analysis_list[i.path - 1].selected_latency += 1
else:
paths_analysis_list[i.path - 1].selected_number_of_hops += 1
#### Find top selected path ####
max_selected_latency_path = 0
max_selected_hops_path = 0
max_selected_path = 0
index_counter = 0
for i in paths_analysis_list:
# print str(i.selected_latency) + " < " + str(paths_analysis_list[max_selected_latency_path].selected_latency)
if i.selected_latency > paths_analysis_list[max_selected_latency_path].selected_latency:
max_selected_latency_path = index_counter
# print str(i.selected_number_of_hops) + " < " + str(paths_analysis_list[max_selected_latency_path].selected_number_of_hops)
if i.selected_number_of_hops > paths_analysis_list[max_selected_hops_path].selected_number_of_hops:
max_selected_hops_path = index_counter
# print str(i.selected_number_of_hops + i.selected_latency) + " < " + str(paths_analysis_list[max_selected_path].selected_latency + paths_analysis_list[max_selected_path].selected_number_of_hops)
if i.selected_number_of_hops + i.selected_latency > paths_analysis_list[max_selected_path].selected_latency + paths_analysis_list[max_selected_path].selected_number_of_hops:
max_selected_path = index_counter
index_counter += 1
print "Name\t" + "#Latency\t" + "#Hops"
print "======================================="
for i in paths_analysis_list:
print i.name + "\t" + str(i.selected_latency) + "\t\t" + str(i.selected_number_of_hops)
print "\nTop selected path regarding latency is: " + paths_analysis_list[max_selected_latency_path].name
print "Top selected path regarding number of hops is: " + paths_analysis_list[max_selected_hops_path].name
print "Top selected path in general is: " + paths_analysis_list[max_selected_path].name
print "Number of entries: " + str(line_count)
#### Need for plotting ####
paths_names_list = []
for i in paths_analysis_list:
paths_names_list.append(i.name)
paths_scores_latency_list = []
for i in paths_analysis_list:
paths_scores_latency_list.append(i.selected_latency)
paths_scores_hops_list = []
for i in paths_analysis_list:
paths_scores_hops_list.append(i.selected_number_of_hops)
paths_scores_percent_list = []
for i in paths_analysis_list:
sum_score = i.selected_number_of_hops + i.selected_latency
paths_scores_percent_list.append((sum_score * 100) / line_count)
# print (i.selected_number_of_hops + i.selected_latency) / line_count
#### Plotting Bars ####
ind = np.arange(len(paths_analysis_list))
width = 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, paths_scores_latency_list, width, label='Selected Latency')
rects2 = ax.bar(ind + width/2, paths_scores_hops_list, width, label='Selected Number of Hops')
ax.set_ylabel('Scores')
ax.set_title("Scores by Path")
ax.set_xticks(ind)
ax.set_xticklabels(paths_names_list)
ax.legend()
autolabel(rects1, "left")
autolabel(rects2, "right")
fig.tight_layout()
# plt.show()
#### Plotting Pie ####
labels = paths_names_list
sizes = paths_scores_percent_list
# explode =
fig1, ax1 = plt.subplots()
wedges, texts, autotexts = ax1.pie(sizes, autopct = '', pctdistance=1.1, labeldistance=1.2, shadow=False, startangle=90, radius=0.1)
ax1.legend(wedges, labels, title="Paths", loc="upper left", bbox_to_anchor=(-0.1,1.15))
ax1.set_title("Path's Selection Percentage")
ax1.axis('equal')
plt.show()
exit()
#### Read server, number_of_pings, criteria from user ####
while correct_input != 1:
input = raw_input("Please enter 'endserver' 'number_of_pings' 'criteria':\n")
input = input.split()
try:
hostname = end_servers.get(input[0])
number_of_pings = input[1]
criteria = input[2]
correct_input = 1
except:
print " >> Error: Wrong arguments, example input:"
print " google 10 latency"
continue
if is_number(number_of_pings) == False:
correct_input = 0
print " >> Error: number_of_pings is not a number."
if criteria.lower() != "latency" and criteria.lower() != "number_of_hops":
correct_input = 0
print " >> Error: Criteria is not valid. Please enter 'latency' or 'number_of_hops'."
if hostname == None:
correct_input = 0
print " >> Error: Hostname is not valid."
#### Inititate threads for direct path, client to relay and relay to end measurements ####
initiate(relay_nodes_list, hostname, number_of_pings)
#### Print results sent from relays ####
for i in relay_nodes_list:
log1 = results_client_to_relay_dict[i.relay_name]
log2 = results_relay_to_end_dict[i.relay_name]
if log2.latency == -1:
results[i.relay_name] = log(-1, -1)
else:
results[i.relay_name] = log(log1.latency + log2.latency, log1.number_of_hops + log2.number_of_hops)
results["direct"] = log(direct_path.latency, direct_path.number_of_hops)
print "\nPATH\t" + " Latency\t" + " Number of hops"
print "========================================="
for i in results:
if results[i].latency == -1:
continue
print str(i) + "\t" + str(results[i].latency) + "\t\t" + str(results[i].number_of_hops)
#### Find best baths ####
min_latency_path = "none"
min_number_of_hops_path = "none"
min_latency = -1
min_number_of_hops = -1
for i in results:
if results[i].latency == -1:
continue
if min_latency == -1:
min_latency = results[i].latency
min_latency_path = i
elif results[i].latency == min_latency:
if results[i].number_of_hops < results[min_latency_path].number_of_hops:
min_latency_path = i
elif results[i].latency < min_latency:
min_latency = results[i].latency
min_latency_path = i
if min_number_of_hops == -1:
min_number_of_hops = results[i].number_of_hops
min_number_of_hops_path = i
elif results[i].number_of_hops == min_number_of_hops:
if results[i].latency < results[min_number_of_hops_path].latency:
min_number_of_hops_path = i
elif results[i].number_of_hops < min_number_of_hops:
min_number_of_hops = results[i].number_of_hops
min_number_of_hops_path = i
#print "Min number of hops: " + min_number_of_hops_path + " " + str(min_number_of_hops)
#print "Min latency: " + min_latency_path + " " + str(min_latency)
#### Choose best path based on criteria ####
best_path = "none"
if min_latency_path == "none":
print "Sorry no paths found"
exit()
if criteria == "latency":
best_path = min_latency_path
else:
best_path = min_number_of_hops_path
print "\nBased on " + criteria + " best path is: " + best_path + "\n"
#### Choose file to download ####
print "Please choose which file you want to download:"
with open("files2download.txt") as file:
counter = 1
for f in file:
files2download[counter] = f.rstrip()
print "[" + str(counter) + "]\t" + f
counter = counter + 1
while True:
input = raw_input("Enter number from 1-%d:\n" %len(files2download))
if is_number(input) == False or int(input) < 1 or int(input) > len(files2download):
continue
break
#### Download file choosen ####
image_index = int(input)
url = files2download[image_index]
file_name_list = url.split('/')
file_name = file_name_list[len(file_name_list) - 1]
path_to_save = './' + file_name
data_to_write = []
t0 = time.time()
if best_path == "direct":
try:
filedata = urllib2.urlopen(url)
except:
print " >> Error: Couldn't download file."
exit()
data_to_write.append(filedata.read())
download_threads(url, best_path, data_to_write, "online")
else:
download_threads(url, best_path, data_to_write, "online")
t1 = time.time()
total_time_for_download = t1-t0
print "\nTotal time to download image is: %.2f seconds\n" %total_time_for_download
with open(path_to_save, 'wb') as f:
f.write(data_to_write[0])
#### Log file creation ####
file_size = len(data_to_write[0])
#print "file size = " + str(file_size/1000)
hour = datetime.datetime.now().hour
#print "hour = " + str(hour)
insert_to_log_file(hour, best_path, file_size, url)
| e2f49f1ec148c34a8cc0a56b4b97eef7d3b1918b | [
"Markdown",
"Python"
] | 3 | Python | dkarathanas/computer-networks | ad6bf6409fdbcddc57f5617987ec9ae4de8904d5 | fe58db66441adf26f2fae3b81e192d6263e2208c |
refs/heads/main | <repo_name>FHenriqueZiimer/codeBy-challenge<file_sep>/src/Pages/Cart/Cart.js
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import styles from './styles.module.css';
function Cart() {
const [totalizers, setTotalizers] = useState('');
const [error, setErro] = useState(null);
const [products, setProducts] = useState([]);
const [isLoaded, setIsLoaded] = useState(false);
const [isFreeShipping, setIsFreeShipping] = useState(false);
const shipping = sessionStorage.getItem('endpoint');
const history = useHistory();
if (shipping === null) {
history.push('/');
}
useEffect(() => {
fetch(`http://localhost:3001/${shipping}`)
.then((res) => res.json())
.then((res) => {
const totalPrice = Math.round((res.data.totalizers[0].value + res.data.totalizers[1].value) * 1) / 100;
if (totalPrice > 10.0) {
setIsFreeShipping(true);
}
setTotalizers(totalPrice.toLocaleString('pt-br', {
style: 'currency',
currency: 'BRL',
}));
setProducts(res.data.items);
setIsLoaded(true);
}).catch(err => setErro(true));
}, [shipping]);
if(error) {
return (
<div>
<div className='model'>
<h1>Ops...<br></br>Algum erro foi ocorrido. Você inicou a API?</h1>
</div>
</div>
)
}
if (!isLoaded) {
return (
<div>
<div className='model'>
<h1>
LOADING<span>...</span>
</h1>
</div>
</div>
);
}
return (
<body>
<div className='model'>
<div className='header-model'>
<h1>Meu carrinho</h1>
</div>
<ul className={styles.cartProducts}>
{products.map((product) => (
<>
<li key={product.uniqueId} className={styles.product}>
<img src={product.imageUrl} alt='bombom' />
<div className={styles.productDetails}>
<p>{product.name}</p>
<p style={{ color: 'gray', fontSize: '0.8em' }}>
{(Math.round(product.price * 1) / 100).toLocaleString('pt-br', {
style: 'currency', currency: 'BRL'
}
)}
</p>
<p>
{(
Math.round(product.sellingPrice * 1) / 100).toLocaleString('pt-br', {
style: 'currency',
currency: 'BRL',
}
)}
</p>
</div>
</li>
</>
))}
</ul>
<div className={styles.footerModel}>
<div className={styles.totalPrice}>
<h1>Total</h1>
<span>{totalizers}</span>
</div>
{isFreeShipping === true && (
<div className={styles.FreeShippingAlert}>
<p>Parabéns, sua compra tem frete grátis!</p>
</div>
)}
</div>
<button className={'primary-btn'}>Finalizar Compra</button>
</div>
</body>
);
}
export default Cart;
<file_sep>/src/Pages/Home/Home.js
import React from 'react';
import { useHistory } from 'react-router-dom';
function Home () {
const history = useHistory();
return (
<body>
<div style={{ marginTop: '20vh', height: '50vh' }} className='model'>
<div className='header-model'>
<h1>Selecione uma opção</h1>
</div>
<div className='content-model'>
<button className={'primary-btn'} onClick={e => { sessionStorage.setItem('endpoint', 'products/freeshipping'); history.push('/cart') }}>CARRINHO COM FRETE GRÁTIS</button>
<button className={'primary-btn'} onClick={e => { sessionStorage.setItem('endpoint', 'products/'); history.push('/cart') }}>CARRINHO COM FRETE</button>
</div>
</div>
</body>
)
}
export default Home;<file_sep>/api/routes/productsRoutes.js
const express = require ('express');
const router = express.Router();
const productsController = require('../controllers/productsController');
router.route('/products/freeshipping')
.get(productsController.getFreeShippingCart)
router.route('/products/')
.get(productsController.getCart)
module.exports = router
<file_sep>/README.md
# Teste Carrinho
## Primeiro passo para inicar o projeto :rocket:
Clone o repositório em sua máquina e acesse a pasta raiz do projeto e rodar o comando:
```shell
npm i
```
O gerenciador de pacotes irá instalar todas as dependências seguindo o arquivo package.json. :package:
Após estar com todos os pacotes instalados, execute o comando:
```shell
npm start
```
Pronto! A pagina irá iniciar localmente :rocket:
# API
## Primeiro passo
Entre na pasta `api` e execute o comando:
```shell
npm i
```
O gerenciador de pacotes irá instalar todas as dependências seguindo o arquivo package.json. :package:
Após estar com todos os pacotes instalados, execute o comando:
```shell
npm start
```
Pronto! A api estará rodando e sendo consumida pela pagina.
## Objetivos:
- Desenvolver um “Carrinho de compras” usando uma API.
- Listar os produtos, exibir o total da compra e exibir uma mensagem informando se o pedido possui frete grátis.
## **Prazo:**
- 3 dias corridos.
## **Requisitos mínimos:**
- Listar os produtos provenientes da API.
- Os produtos devem ter imagem, nome e preço.
- Exibir ao fim da lista o valor total de todos os produtos.
- Exibir o texto de frete grátis dependendo do valor do carrinho.
- O texto de frete grátis deverá aparecer apenas se o valor for acima de **R$ 10,00.**
- Seguir o layout.
- Usar Flex-Box CSS.
- Você poderá usar Vanilla JS, React, Vue ou outro framework. Sinta-se a vontade para usar a ferramenta que preferir.
- Enviar o link do teste no github.
| 6d5bd4c588e784173e8b48135dc94638e5f533f2 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | FHenriqueZiimer/codeBy-challenge | 1908af2edb1b3c7d76d55e42e657d7af63bd2e44 | c6028e5cbc8a7c458f880982a4d99863e448c0cb |
refs/heads/master | <file_sep># 搭建一个简单的问答系统
## 一、问答系统任务介绍
### 1. 模块介绍
  问答系统所需要的数据已经提供,对于每一个问题都可以找得到相应的答案,所以可以理解为每一个样本数据是 ``<问题、答案>``。 那系统的核心是当用户输入一个问题的时候,首先要找到跟这个问题最相近的已经存储在库里的问题,然后直接返回相应的答案即可(但实际上也可以抽取其中的实体或者关键词)。 举一个简单的例子:
假设我们的库里面已有存在以下几个<问题,答案>:
- <"贪心学院主要做什么方面的业务?”, “他们主要做人工智能方面的教育”>
- <“国内有哪些做人工智能教育的公司?”, “贪心学院”>
- <"人工智能和机器学习的关系什么?", "其实机器学习是人工智能的一个范畴,很多人工智能的应用要基于机器学习的技术">
- <"人工智能最核心的语言是什么?", ”Python“>
假设一个用户往系统中输入了问题 “贪心学院是做什么的?”, 那这时候系统先去匹配最相近的“已经存在库里的”问题。 那在这里很显然是 “贪心学院是做什么的”和“贪心学院主要做什么方面的业务?”是最相近的。 所以当我们定位到这个问题之后,直接返回它的答案 “他们主要做人工智能方面的教育”就可以了。 所以这里的核心问题可以归结为**计算两个问句(query)之间的相似度**。
### 2. 数据介绍
  问答系统项目涉及的模块包括:
- 文本的读取: 需要从相应的文件里读取```(问题,答案)```
- 文本预处理: 清洗文本很重要,需要涉及到```停用词过滤```等工作
- 文本的表示: 如果表示一个句子是非常核心的问题,这里会涉及到```tf-idf```, ```Glove```以及```BERT Embedding```
- 文本相似度匹配: 在基于检索式系统中一个核心的部分是计算文本之间的```相似度```,从而选择相似度最高的问题然后返回这些问题的答案
- 倒排表: 为了加速搜索速度,我们需要设计```倒排表```来存储每一个词与出现的文本
- 词义匹配:直接使用倒排表会忽略到一些意思上相近但不完全一样的单词,我们需要做这部分的处理。我们需要提前构建好```相似的单词```然后搜索阶段使用
- 拼写纠错:我们不能保证用户输入的准确,所以第一步需要做用户输入检查,如果发现用户拼错了,我们需要及时在后台改正,然后按照修改后的在库里面搜索
- 文档的排序: 最后返回结果的排序根据文档之间```余弦相似度```有关,同时也跟倒排表中匹配的单词有关
### 3. 项目工具介绍
  在本次项目中,你将会用到以下几个工具:
- ```sklearn```。具体安装请见:http://scikit-learn.org/stable/install.html sklearn包含了各类机器学习算法和数据处理工具,包括本项目需要使用的词袋模型,均可以在sklearn工具包中找得到。
- ```jieba```,用来做分词。具体使用方法请见 https://github.com/fxsjy/jieba
- ```bert embedding```: https://github.com/imgarylai/bert-embedding
- ```nltk```:https://www.nltk.org/index.html
## 二、搭建问答系统
### 1. 文本读取
  需要从文本中读取数据,此处需要读取的文件是```train-v2.0.json```,并把读取的文件存入一个列表里(list)
### 2. 可视化分析
  对于给定的样本数据,做一些可视化分析来更好地理解数据
### 3. 文本预处理
  对于问题本身需要做一些停用词过滤等文本方面的处理
#### 3.1 无用符号过滤
  去掉一些无用的符号: 比如连续的感叹号!!!, 或者一些奇怪的单词。
#### 3.2 停用词过滤
  去网上搜一下 “english stop words list”,会出现很多包含停用词库的网页,或者直接使用NLTK自带的
#### 3.3 去掉低频率的词
  比如出现次数少于10,20… (合理选择阈值)
#### 3.4 处理数字
  对于数字的处理: 分词完只有有些单词可能就是数字比如44,415,把所有这些数字都看成是一个单词,这个新的单词我们可以定义为 “#number”
### 4.文本表示
#### 4.1 使用tf-idf表示向量
  把```qlist```中的每一个问题的字符串转换成```tf-idf```向量, 转换之后的结果存储在```X```矩阵里。``X``的大小是: ``N* D``的矩阵。 这里``N``是问题的个数(样本个数),``D``是词典库的大小。
>词袋模型常用TF-IDF来计算权重,公式为:
>$TF-IDF(t,d)=TF(t,d)×IDF(t)$
其中TF(t,d)为单词t在文档d中出现的频率,IDF(t)是逆文档频率,用来衡量单词t对表达语义所起的重要性,表示为
$IDF(t)=log{[(文章总数)/(句含单词t的文章总数+1)]}$
直观的解释是,如果一个单词在非常多的文章里面都出现,那么它可能是一个比较通用的词汇,对于区分某篇文章特殊语义的贡献较小,因此对权重做一定惩罚。
#### 4.2 使用wordvec + average pooling
  wordvec本质上是通过前馈神经网络的训练参数。从表现上来看,wordvec表征能力比TF-IDF表征能力强很多。词向量方面需要下载: https://nlp.stanford.edu/projects/glove/ (请下载``glove.6B.zip``),并使用``d=200``的词向量(200维),我资源里面也传了一份。这样获得的词向量是已经训练好的词向量。 每个词向量获取完之后,即可以得到一个句子的向量。 我们通过``average pooling``来实现句子的向量。
#### 4.3 使用BERT + average pooling
  BERT与wordvec非常相似,只不过BERT是基于Transformer的深层神经网络来训练得到向量的表示,学到的效果比浅层的神经网络效果好。我们不做任何的训练,而是直接使用已经训练好的BERT embedding. 为了获取BERT-embedding,可以直接下载已经训练好的模型,从而获得每一个单词的向量。可以从这里获取: https://github.com/imgarylai/bert-embedding ,请使用```bert_12_768_12``` 当然,你也可以从其他source获取也没问题,只要是合理的词向量。
### 5.相似度匹配与搜索
  在这部分里,我们需要把用户每一个输入跟知识库里的每一个问题做一个相似度计算,从而得出最相似的问题。但对于这个问题,时间复杂度其实很高,所以我们需要结合倒排表来获取相似度最高的问题,从而获得答案。下面介绍几种最常见的相似度匹配算法的设计。
#### 5.1 tf-idf + 余弦相似度
  我们可以直接基于计算出来的``tf-idf``向量,计算用户最新问题与库中存储的问题之间的相似度,从而选择相似度最高的问题的答案。这个方法的复杂度为``O(N)``, ``N``是库中问题的个数。
#### 5.2 倒排索引表的创建
  倒排表可以用于加快匹配的过程。**倒排表**的创建其实很简单,最简单的方法就是循环所有的单词一遍,然后记录每一个单词所出现的文档,然后把这些文档的ID保存成list即可。我们可以定义一个类似于```hash_map```, 比如 ``inverted_index = {}``, 然后存放包含每一个关键词的文档出现在了什么位置,也就是,通过关键词的搜索首先来判断包含这些关键词的文档(比如出现至少一个),然后对于candidates问题做相似度比较。
>倒排索引表基于一个强假设:两个句子包含的相同的词越多,两个句子越相似。实际上会漏掉一些句子,相同的词不多,但是句子相似。
#### 5.3 语义相似度
  语义的相似度,可以这么理解: 两个单词比如car, auto这两个单词长得不一样,但从语义上还是类似的。如果只是使用倒排表,我们不能考虑到这些单词之间的相似度,这就导致如果我们搜索句子里包含了``car``, 则我们没法获取到包含auto的所有的文档。所以我们希望把这些信息也存下来。那这个问题如何解决呢? 其实也不难,可以提前构建好相似度的关系,比如对于``car``这个单词,一开始就找好跟它意思上比较类似的单词比如top 10,这些都标记为``related words``。所以最后我们就可以创建一个保存``related words``的一个``map``. 比如调用``related_words['car']``即可以调取出跟``car``意思上相近的TOP 10的单词。那这个``related_words``又如何构建呢? 在这里我们仍然使用``Glove``向量,然后计算一下俩俩的相似度(余弦相似度)。之后对于每一个词,存储跟它最相近的top 10单词,最终结果保存在``related_words``里面。 这个计算需要发生在离线,因为计算量很大,复杂度为``O(V*V)``, V是单词的总数。这个结果保存在``related_words.txt``里。 我们在使用的时候直接从文件里读取就可以了,不用再重复计算。
#### 5.4 利用倒排索引表进行搜索
  在这里,我们使用倒排表先获得一批候选问题,然后再通过余弦相似度做精准匹配,这样一来可以节省大量的时间。搜索过程分成两步:
1. 使用倒排表把候选问题全部提取出来。首先,对输入的新问题做分词等必要的预处理工作,然后对于句子里的每一个单词,从``related_words``里提取出跟它意思相近的top 10单词, 然后根据这些top词从倒排表里提取相关的文档,把所有的文档返回。 这部分可以放在下面的函数当中,也可以放在外部。
2. 然后针对于这些文档做余弦相似度的计算,最后排序并选出最好的答案。
### 6.拼写纠错
  这一部分并不是文本匹配的后续部分,但在问答系统中是经常用到的,这是因为考虑到用户输入是不一定正确的。这个额外的技术手段用来保证query的正确性。其实用户在输入问题的时候,不能期待他一定会输入正确,有可能输入的单词的拼写错误的。这个时候我们需要后台及时捕获拼写错误,并进行纠正,然后再通过修正之后的结果再跟库里的问题做匹配。这里我们需要实现一个简单的拼写纠错的代码,然后自动去修复错误的单词。
这里使用的拼写纠错方法是使用`noisy channel model`。 我们回想一下它的表示:
$$c^* = \text{argmax}_{c\in candidates} ~~p(c|s) = \text{argmax}_{c\in candidates} ~~p(s|c)p(c)$$
这里的```candidates```指的是针对于错误的单词的候选集,这部分我们可以假定是通过`edit_distance`来获取的(比如生成跟当前的词距离为1/2的所有的valid 单词。 valid单词可以定义为存在词典里的单词。 ```c```代表的是正确的单词, ```s```代表的是用户错误拼写的单词。 所以我们的目的是要寻找出在``candidates``里让上述概率最大的正确写法``c``。 $p(s|c)$,这个概率我们可以通过历史数据来获得,也就是对于一个正确的单词$c$, 有百分之多少人把它写成了错误的形式1,形式2... 这部分的数据可以从``spell_errors.txt``里面找得到。但在这个文件里,我们并没有标记这个概率,所以可以使用`uniform probability`来表示。这个也叫做`channel probability`。 $p(c)$,这一项代表的是语言模型,也就是假如我们把错误的$s$,改造成了$c$, 把它加入到当前的语句之后有多通顺?在本次项目里我们使用bigram来评估这个概率。
>举个例子: 假如有两个候选 $c_1, c_2$, 然后我们希望分别计算出这个语言模型的概率。 由于我们使用的是``bigram``, 我们需要计算出两个概率,分别是当前词前面和后面词的``bigram``概率。 用一个例子来表示:
给定: ``We are go to school tomorrow``, 对于这句话我们希望把中间的``go``替换成正确的形式,假如候选集里有个,分别是``going``, ``went``, 这时候我们分别对这俩计算如下的概率:$p(going|are)p(to|going)$和 $p(went|are)p(to|went)$, 然后把这个概率当做是$p(c)$的概率。 然后再跟``channel probability``结合给出最终的概率大小。那这里的$p(are|going)$这些bigram概率又如何计算呢?答案是训练一个语言模型! 但训练一个语言模型需要一些文本数据,这个数据怎么找? 在这次项目里我们会用到``nltk``自带的``reuters``的文本类数据来训练一个语言模型。当然,如果你有资源你也可以尝试其他更大的数据。最终目的就是计算出``bigram``概率。
#### 6.1 训练一个语言模型
  在这里,我们使用``nltk``自带的``reuters``数据来训练一个语言模型。 使用``add-one smoothing``。
#### 6.2 计算channel probability
  这个概率我们可以通过历史数据来获得,也就是对于一个正确的单词$c$, 有百分之多少人把它写成了错误的形式1,形式2... 这部分的数据可以从``spell_errors.txt``里面找得到。但在这个文件里,我们并没有标记这个概率,所以可以使用`uniform probability`来表示。这个也叫做`channel probability`。下面基于``spell_errors.txt``文件构建``channel probability``, 其中$channel[c][s]$表示正确的单词$c$被写错成$s$的概率。
#### 6.3 根据错别字生成所有候选集合
  给定一个错误的单词,首先生成跟这个单词距离为1或者2的所有的候选集合。
#### 6.4 给定一个输入,如果有错误给予纠正
  给定一个输入``query``, 如果这里有些单词是拼错的,就需要把它纠正过来。这部分的实现可以简单一点: 对于``query``分词,然后把分词后的每一个单词在词库里面搜一下,假设搜不到的话可以认为是拼写错误的! 如果拼写错误了再通过``channel``和``bigram``来计算最适合的候选。
#### 6.5 基于拼写纠错算法,实现用户输入自动矫正
  首先有了用户的输入``query``, 然后做必要的处理把句子转换成tokens的形状,然后对于每一个token比较是否是valid, 如果不是的话就进行下面的修正过程。
博客链接:https://blog.csdn.net/weixin_46649052/article/details/118573356
<file_sep>#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: admin
@file: FAQ.py
@time: 2021/07/08
@desc:
"""
import json
# ### 第一部分:对于训练数据的处理:读取文件和预处理
# - ```文本的读取```: 需要从文本中读取数据,此处需要读取的文件是```dev-v2.0.json```,并把读取的文件存入一个列表里(list)
# - ```文本预处理```: 对于问题本身需要做一些停用词过滤等文本方面的处理
# - ```可视化分析```: 对于给定的样本数据,做一些可视化分析来更好地理解数据
# #### 1.1节: 文本的读取
# 把给定的文本数据读入到```qlist```和```alist```当中,这两个分别是列表,其中```qlist```是问题的列表,```alist```是对应的答案列表
def read_corpus():
"""
读取给定的语料库,并把问题列表和答案列表分别写入到 qlist, alist 里面。 在此过程中,不用对字符换做任何的处理(这部分需要在 Part 2.3里处理)
qlist = ["问题1", “问题2”, “问题3” ....]
alist = ["答案1", "答案2", "答案3" ....]
务必要让每一个问题和答案对应起来(下标位置一致)
"""
# 问题列表
qlist = []
# 答案列表
alist = []
# 文件名称
filename = 'data/train-v2.0.json'
# 加载json文件
datas = json.load(open(filename, 'r'))
data = datas['data']
for d in data:
paragraph = d['paragraphs']
for p in paragraph:
qas = p['qas']
for qa in qas:
# 处理is_impossible为True时answers空
if (not qa['is_impossible']):
qlist.append(qa['question'])
alist.append(qa['answers'][0]['text'])
# 如果它的条件返回错误,则终止程序执行
# 这行代码是确保长度一样
assert len(qlist) == len(alist)
return qlist, alist
# 读取给定的语料库,并把问题列表和答案列表分别写入到 qlist, alist
qlist, alist = read_corpus()
# ### 1.2 理解数据(可视化分析/统计信息)
# 统计一下在qlist中总共出现了多少个单词? 总共出现了多少个不同的单词(unique word)?
# 这里需要做简单的分词,对于英文我们根据空格来分词即可,其他过滤暂不考虑(只需分词)
words_qlist = dict()
for q in qlist:
# 以空格为分词,都转为小写
words = q.strip().split(' ')
for w in words:
if w.lower() in words_qlist:
words_qlist[w.lower()] += 1
else:
words_qlist[w.lower()] = 1
word_total = len(words_qlist)
print(word_total)
# 统计一下qlist中出现1次,2次,3次... 出现的单词个数, 然后画一个plot. 这里的x轴是单词出现的次数(1,2,3,..), y轴是单词个数。
# 从左到右分别是 出现1次的单词数,出现2次的单词数,出现3次的单词数
import matplotlib.pyplot as plt
import numpy as np
# counts:key出现N次,value:出现N次词有多少
counts = dict()
for w, c in words_qlist.items():
if c in counts:
counts[c] += 1
else:
counts[c] = 1
# 以histogram画图
fig, ax = plt.subplots()
ax.hist(counts.values(), bins=np.arange(0, 250, 25), histtype='step', alpha=0.6, label="counts")
ax.legend()
ax.set_xlim(0, 250)
ax.set_yticks(np.arange(0, 500, 50))
plt.show()
# #### 1.3 文本预处理
# 此部分需要做文本方面的处理。 以下是可以用到的一些方法:
#
# - 1. 停用词过滤 (去网上搜一下 "english stop words list",会出现很多包含停用词库的网页,或者直接使用NLTK自带的)
# - 2. 转换成lower_case: 这是一个基本的操作
# - 3. 去掉一些无用的符号: 比如连续的感叹号!!!, 或者一些奇怪的单词。
# - 4. 去掉出现频率很低的词:比如出现次数少于10,20.... (想一下如何选择阈值)
# - 5. 对于数字的处理: 分词完只有有些单词可能就是数字比如44,415,把所有这些数字都看成是一个单词,这个新的单词我们可以定义为 "#number"
# - 6. lemmazation: 在这里不要使用stemming, 因为stemming的结果有可能不是valid word。
import nltk
from nltk.corpus import stopwords
import codecs
import re
# 去掉一些无用的符号
def tokenizer(ori_list):
# 利用正则表达式去掉无用的符号
# compile 函数用于编译正则表达式,[]用来表示一组字符
# \s匹配任意空白字符,等价于 [\t\n\r\f]。
SYMBOLS = re.compile('[\s;\"\",.!?\\/\[\]\{\}\(\)-]+')
new_list = []
for q in ori_list:
# split 方法按照能够匹配的子串将字符串分割后返回列表
words = SYMBOLS.split(q.lower().strip())
new_list.append(' '.join(words))
return new_list
# 去掉question的停用词
def removeStopWord(ori_list):
new_list = []
# nltk中stopwords包含what等,但是在QA问题中,这算关键词,所以不看作关键词
restored = ['what', 'when', 'which', 'how', 'who', 'where']
# nltk中自带的停用词库
english_stop_words = list(
set(stopwords.words('english'))) # ['what','when','which','how','who','where','a','an','the']
# 将在QA问答系统中不算停用词的词去掉
for w in restored:
english_stop_words.remove(w)
for q in ori_list:
# 将每个问句的停用词去掉
sentence = ' '.join([w for w in q.strip().split(' ') if w not in english_stop_words])
# 将去掉停用词的问句添加至列表中
new_list.append(sentence)
return new_list
def removeLowFrequence(ori_list, vocabulary, thres=10):
"""
去掉低频率的词
:param ori_list: 预处理后的问题列表
:param vocabulary: 词频率字典
:param thres: 频率阈值,可以基于数据实际情况进行调整
:return: 新的问题列表
"""
# 根据thres筛选词表,小于thres的词去掉
new_list = []
for q in ori_list:
sentence = ' '.join([w for w in q.strip().split(' ') if vocabulary[w] >= thres])
new_list.append(sentence)
return new_list
def replaceDigits(ori_list, replace='#number'):
"""
将数字统一替换为replace,默认#number
:param ori_list: 预处理后的问题列表
:param replace:
:return:
"""
# 编译正则表达式:匹配1个或多个数字
DIGITS = re.compile('\d+')
new_list = []
for q in ori_list:
# re.sub用于替换字符串中的匹配项,相当于在q中查找连续的数字替换为#number
q = DIGITS.sub(replace, q)
# 将处理后的问题字符串添加到新列表中
new_list.append(q)
return new_list
def createVocab(ori_list):
"""
创建词表,统计所有单词总数与每个单词总数
:param ori_list:预处理后的列表
:return:所有单词总数与每个单词总数
"""
count = 0
vocab_count = dict()
for q in ori_list:
words = q.strip().split(' ')
count += len(words)
for w in words:
if w in vocab_count:
vocab_count[w] += 1
else:
vocab_count[w] = 1
return vocab_count, count
def writeFile(oriList, filename):
"""
将处理后的问题列表写入到文件中
:param oriList: 预处理后的问题列表
:param filename: 文件名
"""
with codecs.open(filename, 'w', 'utf8') as Fout:
for q in oriList:
Fout.write(q + u'\n')
def writeVocab(vocabulary, filename):
"""
将词表写入到文件中
:param vocabulary: 词表
:param filename: 文件名
"""
sortedList = sorted(vocabulary.items(), key=lambda d: d[1])
with codecs.open(filename, 'w', 'utf8') as Fout:
for (w, c) in sortedList:
Fout.write(w + u':' + str(c) + u'\n')
# 去掉一些无用的符号
new_list = tokenizer(qlist)
# 停用词过滤
new_list = removeStopWord(new_list)
# 数字处理-将数字替换为#number
new_list = replaceDigits(new_list)
# 创建词表并统计所有单词数目
vocabulary, count = createVocab(new_list)
# 去掉低频率的词
new_list = removeLowFrequence(new_list, vocabulary, 5)
# 重新统计词频
vocab_count, count = createVocab(new_list)
# 将词表写入到文件“train.vocab”中
writeVocab(vocab_count, "train.vocab")
qlist = new_list
# ### 第二部分: 文本的表示
# 文本处理完之后,我们需要做文本表示,这里有3种方式:
#
# - 1. 使用```tf-idf vector```
# - 2. 使用embedding技术如```word2vec```, ```bert embedding```等
# #### 2.1 使用tf-idf表示向量
# 把```qlist```中的每一个问题的字符串转换成```tf-idf```向量, 转换之后的结果存储在```X```矩阵里。
# # ``X``的大小是: ``N* D``的矩阵。 这里``N``是问题的个数(样本个数),``D``是词典库的大小
import numpy as np
def computeTF(vocab, c):
"""
计算每个词的词频
:param vocab: 词频字典:键是单词,值是所有问句中单词出现的次数
:param c: 单词总数
:return: TF
"""
# 初始化TF
TF = np.ones(len(vocab))
# 词频字典
word2id = dict()
# 单词字典
id2word = dict()
for word, fre in vocab.items():
# 计算TF值:每个单词出现的个数/总的单词个数
TF[len(word2id)] = 1.0 * fre / c
id2word[len(word2id)] = word
word2id[word] = len(word2id)
return TF, word2id, id2word
def computeIDF(word2id, qlist):
"""
计算IDF:log[问句总数/(包含单词t的问句总数+1)]
:param word2id:单词字典
:param qlist:问句列表
:return:
"""
IDF = np.ones(len(word2id))
for q in qlist:
# 去重
words = set(q.strip().split())
for w in words:
# 统计单词出现在问句中的总数
IDF[word2id[w]] += 1
# 计算IDF
IDF /= len(qlist)
IDF = -1.0 * np.log2(IDF)
return IDF
def computeSentenceEach(sentence, tfidf, word2id):
"""
给定句子,计算句子TF-IDF,tfidf是一个1*M的矩阵,M为词表大小
:param sentence:句子
:param tfidf:TF-IDF向量
:param word2id:词表
:return:
"""
sentence_tfidf = np.zeros(len(word2id))
# 将问句以空格进行分割
for w in sentence.strip().split(' '):
if w not in word2id:
continue
# 碰到在词表word2id中的单词
sentence_tfidf[word2id[w]] = tfidf[word2id[w]]
return sentence_tfidf
def computeSentence(qlist, word2id, tfidf):
"""
把```qlist```中的每一个问题的字符串转换成```tf-idf```向量, 转换之后的结果存储在```X```矩阵里
:param qlist: 问题列表
:param word2id: 词表(字典形式)
:param tfidf: TF-IDF(与词表中的键一一对应)
:return: X矩阵
"""
# 对所有句子分别求tfidf
X_tfidf = np.zeros((len(qlist), len(word2id)))
for i, q in enumerate(qlist):
X_tfidf[i] = computeSentenceEach(q, tfidf, word2id)
# print(X_tfidf[i])
return X_tfidf
# 计算每个词的TF,词表字典
TF, word2id, id2word = computeTF(vocab_count, count)
# 计算IDF:log[问句总数/(包含单词t的问句总数+1)]
IDF = computeIDF(word2id, qlist)
# 用TF,IDF计算最终的tf-idf,定义一个tf-idf的vectorizer
vectorizer = np.multiply(TF, IDF)
# 把```qlist```中的每一个问题的字符串转换成```tf-idf```向量, 转换之后的结果存储在```X```矩阵里
X_tfidf = computeSentence(qlist, word2id, vectorizer)
# #### 2.2 使用wordvec + average pooling
# 词向量方面需要下载: https://nlp.stanford.edu/projects/glove/ (请下载``glove.6B.zip``),并使用``d=200``的词向量(200维)。
# 国外网址如果很慢,可以在百度上搜索国内服务器上的。 每个词向量获取完之后,即可以得到一个句子的向量。 我们通过``average pooling``来实现句子的向量。
# 基于Glove向量获取句子向量
from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
def loadEmbedding(filename):
"""
加载glove模型,转化为word2vec,再加载到word2vec模型
这两种模型形式上是一样的,在数据的保存形式上有略微的差异
:param filename: glove文件
:return: word2vec模型
"""
word2vec_temp_file = 'word2vec_temp.txt'
# 加载glove模型,转化为word2vec
glove2word2vec(filename, word2vec_temp_file)
# 再加载到word2vec模型
model = KeyedVectors.load_word2vec_format(word2vec_temp_file)
return model
def computeGloveSentenceEach(sentence, embedding):
"""
:param sentence:问题
:param embedding:wordvec模型
:return:
"""
# 查找句子中每个词的embedding,将所有embedding进行加和求均值
emb = np.zeros(200)
words = sentence.strip().split(' ')
for w in words:
# 如果单词是新词,则重命名为'unknown'
if w not in embedding:
# 没有lookup的即为unknown
w = 'unknown'
# 将所有embedding进行加和求均值
emb += embedding.get_vector(w)
# emb += embedding[w]
return emb / len(words)
def computeGloveSentence(qlist, embedding):
"""
对每一个句子来构建句子向量
:param qlist:问题列表
:param embedding:word2vec模型
:return:
"""
# 对每一个句子进行求均值的embedding
X_w2v = np.zeros((len(qlist), 200))
for i, q in enumerate(qlist):
# 编码每一个问题
X_w2v[i] = computeGloveSentenceEach(q, embedding)
# print(X_w2v)
return X_w2v
# 加载到word2vec模型
# 这是 D*H的矩阵,这里的D是词典库的大小, H是词向量的大小。 这里面我们给定的每个单词的词向量,
emb = loadEmbedding('data/glove.6B.200d.txt')
# 初始化完emb之后就可以对每一个句子来构建句子向量了,这个过程使用average pooling来实现
X_w2v = computeGloveSentence(qlist, emb)
# #### 2.3 使用BERT + average pooling
# 我们不做任何的训练,而是直接使用已经训练好的BERT embedding. 为了获取BERT-embedding,
# 可以直接下载已经训练好的模型从而获得每一个单词的向量。可以从这里获取: https://github.com/imgarylai/bert-embedding ,
# 请使用```bert_12_768_12``` 当然,你也可以从其他source获取也没问题,只要是合理的词向量。
# TODO 基于BERT的句子向量计算
from bert_embedding import BertEmbedding
sentence_embedding = np.ones((len(qlist), 768))
# 加载Bert模型,model,dataset_name,须指定
bert_embedding = BertEmbedding(model='bert_12_768_12', dataset_name='wiki_multilingual_cased')
# 查询所有句子的Bert embedding
all_embedding = bert_embedding(qlist, 'sum')
for q in qlist:
for i in range(len(all_embedding)):
print(all_embedding[i][1])
# 将每一个句子中每一个词的向量进行拼接求平均得到句子向量
sentence_embedding[i] = np.sum(all_embedding[i][1], axis=0) / len(q.strip().split(' '))
if i == 0:
print(sentence_embedding[i])
# 每一个句子的向量结果存放在X_bert矩阵里。行数为句子的总个数,列数为一个句子embedding大小。
X_bert = sentence_embedding
# ### 第三部分: 相似度匹配以及搜索
# 在这部分里,我们需要把用户每一个输入跟知识库里的每一个问题做一个相似度计算,从而得出最相似的问题。但对于这个问题,时间复杂度其实很高,所以我们需要结合倒排表来获取相似度最高的问题,从而获得答案。
# In[ ]:
# #### 3.1 tf-idf + 余弦相似度
# 我们可以直接基于计算出来的``tf-idf``向量,计算用户最新问题与库中存储的问题之间的相似度,从而选择相似度最高的问题的答案。
# 这个方法的复杂度为``O(N)``, ``N``是库中问题的个数。
import queue as Q
# 优先级队列实现大顶堆Heap,每次输出都是相似度最大值
que = Q.PriorityQueue()
def cosineSimilarity(vec1, vec2):
# 定义余弦相似度,余弦相似度越大,两个向量越相似
return np.dot(vec1, vec2.T) / (np.sqrt(np.sum(vec1 ** 2)) * np.sqrt(np.sum(vec2 ** 2)))
def get_top_results_tfidf_noindex(query):
"""
给定用户输入的问题 query, 返回最有可能的TOP 5问题。
:param query:用户新问题
:return:
"""
"""
给定用户输入的问题 query, 返回最有可能的TOP 5问题。这里面需要做到以下几点:
1. 对于用户的输入 query 首先做一系列的预处理(上面提到的方法),然后再转换成tf-idf向量(利用上面的vectorizer)
2. 计算跟每个库里的问题之间的相似度
3. 找出相似度最高的top5问题的答案
"""
top = 5
# 将用户输入的新问题用tf-idf来表示
query_tfidf = computeSentenceEach(query.lower(), vectorizer, word2id)
for i, vec in enumerate(X_tfidf):
# 计算原问题与用户输入的新问题的相似度
result = cosineSimilarity(vec, query_tfidf)
# print(result)
# 存放到大顶堆里面
que.put((-1 * result, i))
i = 0
top_idxs = []
while (i < top and not que.empty()):
# top_idxs存放相似度最高的(存在qlist里的)问题的下标
top_idxs.append(que.get()[1])
i += 1
print(top_idxs)
# 返回相似度最高的问题对应的答案,作为TOP5答案
return np.array(alist)[top_idxs]
# 给定用户输入的问题 query, 返回最有可能的TOP 5问题的答案。
results = get_top_results_tfidf_noindex('In what city and state did Beyonce grow up')
print(results)
# #### 3.2 倒排表的创建
# 倒排表的创建其实很简单,最简单的方法就是循环所有的单词一遍,然后记录每一个单词所出现的文档,然后把这些文档的ID保存成list即可。我们可以定义一个类似于```hash_map```, 比如 ``inverted_index = {}``, 然后存放包含每一个关键词的文档出现在了什么位置,也就是,通过关键词的搜索首先来判断包含这些关键词的文档(比如出现至少一个),然后对于candidates问题做相似度比较。
word_doc = dict()
# key:word,value:包含该词的句子序号的列表
for i, q in enumerate(qlist):
words = q.strip().split(' ')
for w in set(words):
if w not in word_doc:
# 没在word_doc中的,建立一个空listi
word_doc[w] = set([])
word_doc[w] = word_doc[w] | set([i])
# 定一个一个简单的倒排表,是一个map结构。 循环所有qlist一遍就可以
inverted_idx = word_doc
# #### 3.3 语义相似度
# 读取语义相关的单词
import codecs
def get_related_words(filename):
"""
从预处理的相似词的文件加载相似词信息
文件格式w1 w2 w3..w11,其中w1为原词,w2-w11为w1的相似词
:param filename: 文件名
:return:
"""
related_words = {}
with codecs.open(filename, 'r', 'utf8') as Fin:
lines = Fin.readlines()
for line in lines:
words = line.strip().split(' ')
# 键为原词,值为相似词
related_words[words[0]] = words[1:]
return related_words
# 从预处理的相似词的文件加载相似词信息
related_words = get_related_words('data/related_words.txt')
# #### 3.4 利用倒排表搜索
# 在这里,我们使用倒排表先获得一批候选问题,然后再通过余弦相似度做精准匹配,这样一来可以节省大量的时间。搜索过程分成两步:
# - 使用倒排表把候选问题全部提取出来。首先,对输入的新问题做分词等必要的预处理工作,然后对于句子里的每一个单词,从``related_words``里提取出跟它意思相近的top 10单词, 然后根据这些top词从倒排表里提取相关的文档,把所有的文档返回。 这部分可以放在下面的函数当中,也可以放在外部。
# - 然后针对于这些文档做余弦相似度的计算,最后排序并选出最好的答案。
import queue as Q
def cosineSimilarity(vec1, vec2):
# 定义余弦相似度
return np.dot(vec1, vec2.T) / (np.sqrt(np.sum(vec1 ** 2)) * np.sqrt(np.sum(vec2 ** 2)))
def getCandidate(query):
"""
根据查询句子中每个词及其10个相似词所在的序号列表,求交集
:param query: 问题
:return:
"""
searched = set()
for w in query.strip().split(' '):
# 如果单词不在word2id中或者不在倒排表中
if w not in word2id or w not in inverted_idx:
continue
# 搜索原词所在的序号列表
if len(searched) == 0:
searched = set(inverted_idx[w])
else:
searched = searched & set(inverted_idx[w])
# 搜索相似词所在的列表
if w in related_words:
for similar in related_words[w]:
searched = searched & set(inverted_idx[similar])
return searched
def get_top_results_tfidf(query):
"""
基于TF-IDF,给定用户输入的问题 query, 返回最有可能的TOP 5问题。
这里面需要做到以下几点:
1. 利用倒排表来筛选 candidate (需要使用related_words).
2. 对于候选文档,计算跟输入问题之间的相似度
3. 找出相似度最高的top5问题的答案
"""
top = 5
# 计算给定句子的TF-IDF
query_tfidf = computeSentenceEach(query, vectorizer, word2id)
# 优先级队列实现大顶堆Heap,每次输出都是相似度最大值
results = Q.PriorityQueue()
# 利用倒排索引表获取相似问题
searched = getCandidate(query)
# print(len(searched))
for candidate in searched:
# 计算candidate与query的余弦相似度
result = cosineSimilarity(query_tfidf, X_tfidf[candidate])
# 优先级队列中保存相似度和对应的candidate序号
# -1保证降序
results.put((-1 * result, candidate))
i = 0
# top_idxs存放相似度最高的(存在qlist里的)问题的索引
top_idxs = []
# hint: 利用priority queue来找出top results.
while i < top and not results.empty():
top_idxs.append(results.get()[1])
i += 1
# 返回相似度最高的问题对应的答案,作为TOP5答案
return np.array(alist)[top_idxs]
def get_top_results_w2v(query):
"""
基于word2vec,给定用户输入的问题 query, 返回最有可能的TOP 5问题。
这里面需要做到以下几点:
1. 利用倒排表来筛选 candidate (需要使用related_words).
2. 对于候选文档,计算跟输入问题之间的相似度
3. 找出相似度最高的top5问题的答案
"""
# embedding用glove
top = 5
# 利用glove将问题进行编码
query_emb = computeGloveSentenceEach(query, emb)
# 优先级队列实现大顶堆Heap,每次输出都是相似度最大值
results = Q.PriorityQueue()
# 利用倒排索引表获取相似问题
searched = getCandidate(query)
for candidate in searched:
# 计算candidate与query的余弦相似度
result = cosineSimilarity(query_emb, X_w2v[candidate])
# 优先级队列中保存相似度和对应的candidate序号
# -1保证降序
results.put((-1 * result, candidate))
# top_idxs存放相似度最高的(存在qlist里的)问题的索引
top_idxs = []
i = 0
# hint: 利用priority queue来找出top results.
while i < top and not results.empty():
top_idxs.append(results.get()[1])
i += 1
# 返回相似度最高的问题对应的答案,作为TOP5答案
return np.array(alist)[top_idxs]
def get_top_results_bert(query):
"""
给定用户输入的问题 query, 返回最有可能的TOP 5问题。
这里面需要做到以下几点:
1. 利用倒排表来筛选 candidate (需要使用related_words).
2. 对于候选文档,计算跟输入问题之间的相似度
3. 找出相似度最高的top5问题的答案
"""
top = 5
# embedding用Bert embedding
query_emb = np.sum(bert_embedding([query], 'sum')[0][1], axis=0) / len(query.strip().split())
# 优先级队列实现大顶堆Heap,每次输出都是相似度最大值
results = Q.PriorityQueue()
# 利用倒排索引表获取相似问题
searched = getCandidate(query)
for candidate in searched:
# 计算candidate与query的余弦相似度
result = cosineSimilarity(query_emb, X_bert[candidate])
# 优先级队列中保存相似度和对应的candidate序号
# -1保证降序
results.put((-1 * result, candidate))
# top_idxs存放相似度最高的(存在qlist里的)问题的索引
top_idxs = []
i = 0
# hint: 利用priority queue来找出top results.
while i < top and not results.empty():
top_idxs.append(results.get()[1])
i += 1
# 返回相似度最高的问题对应的答案,作为TOP5答案
return np.array(alist)[top_idxs]
# ### 4. 拼写纠错
# 4.1 训练一个语言模型
# 在这里,我们使用``nltk``自带的``reuters``数据来训练一个语言模型。 使用``add-one smoothing``
from nltk.corpus import reuters
import numpy as np
import codecs
# 读取语料库的数据
categories = reuters.categories()
corpus = reuters.sents(categories=categories)
# 循环所有的语料库并构建bigram probability.
# bigram[word1][word2]: 在word1出现的情况下下一个是word2的概率。
new_corpus = []
for sent in corpus:
# 句子前后加入<s>,</s>表示开始和结束
new_corpus.append(['<s> '] + sent + [' </s>'])
print(new_corpus[0])
word2id = dict()
id2word = dict()
# 构建word2id与id2word
for sent in new_corpus:
for w in sent:
w = w.lower()
if w in word2id:
continue
id2word[len(word2id)] = w
word2id[w] = len(word2id)
# 词表尺寸
vocab_size = len(word2id)
# 初始化
# 统计单个词出现的概率
count_uni = np.zeros(vocab_size)
# 统计两个词相邻出现的概率
count_bi = np.zeros((vocab_size, vocab_size))
for sent in new_corpus:
for i, w in enumerate(sent):
w = w.lower()
count_uni[word2id[w]] += 1
if i < len(sent) - 1:
count_bi[word2id[w], word2id[sent[i + 1].lower()]] += 1
print("unigram done")
# 建立bigram模型
bigram = np.zeros((vocab_size, vocab_size))
# 计算bigram LM
# 有bigram统计值的加一除以|vocab|+uni统计值,没有统计值,1 除以 |vocab|+uni统计值
for i in range(vocab_size):
for j in range(vocab_size):
if count_bi[i, j] == 0:
bigram[i, j] = 1.0 / (vocab_size + count_uni[i])
else:
bigram[i, j] = (1.0 + count_bi[i, j]) / (vocab_size + count_uni[i])
# 得到bigram概率
def checkLM(word1, word2):
if word1.lower() in word2id and word2.lower() in word2id:
return bigram[word2id[word1.lower()], word2id[word2.lower()]]
else:
return 0.0
# #### 4.2 构建Channel Probs
# 基于``spell_errors.txt``文件构建``channel probability``, 其中$channel[c][s]$表示正确的单词$c$被写错成$s$的概率。
channel = {}
# 读取文件,格式为w1:w2,w3..
# w1为正确词,w2,w3...为错误词
# 没有给出不同w2-wn的概率,暂时按等概率处理
for line in open('spell-errors.txt'):
# 按':'为分隔符进行分割
(correct, error) = line.strip().split(':')
# 错误单词按照‘,’进行分割
errors = error.split(',')
errorProb = dict()
for e in errors:
# 键:错误单词;值:错误概率
errorProb[e.strip()] = 1.0 / len(errors)
# 键:正确单词,值:错误字典
channel[correct.strip()] = errorProb
# print(channel)
# #### 4.3 根据错别字生成所有候选集合
# 给定一个错误的单词,首先生成跟这个单词距离为1或者2的所有的候选集合。
def filter(words):
# 将不在词表中的词过滤
new_words = []
for w in words:
if w in word2id:
new_words.append(w)
return set(new_words)
def generate_candidates1(word):
# 生成DTW距离为1的词,
# 对于英语来说,插入,替换,删除26个字母
chars = 'abcdefgh<KEY>'
words = set([])
# insert 1
words = set(word[0:i] + chars[j] + word[i:] for i in range(len(word)) for j in range(len(chars)))
# sub 1
words = words | set(word[0:i] + chars[j] + word[i + 1:] for i in range(len(word)) for j in range(len(chars)))
# delete 1
words = words | set(word[0:i] + word[i + 1:] for i in range(len(chars)))
# 交换相邻
# print(set(word[0:i - 1] + word[i] + word[i - 1] + word[i + 1:] for i in range(1,len(word))))
words = words | set(word[0:i - 1] + word[i] + word[i - 1] + word[i + 1:] for i in range(1, len(word)))
# 将不在词表中的词去掉
words = filter(words)
# 去掉word本身
if word in words:
words.remove(word)
return words
def generate_candidates(word):
# 基于拼写错误的单词,生成跟它的编辑距离为1或者2的单词,并通过词典库的过滤,只留写法上正确的单词。
words = generate_candidates1(word)
words2 = set([])
for word in words:
# 将距离为1词,再分别计算距离为1的词,
# 作为距离为2的词候选
words2 = generate_candidates1(word)
# 过滤掉不在词表中的词
words2 = filter(words)
# 距离为1,2的词合并列表
words = words | words2
return words
# 生成候选集合
words = generate_candidates('strat')
print(words)
# #### 4.4 给定一个输入,如果有错误需要纠正
# 给定一个输入``query``, 如果这里有些单词是拼错的,就需要把它纠正过来。这部分的实现可以简单一点: 对于``query``分词,然后把分词后的每一个单词在词库里面搜一下,假设搜不到的话可以认为是拼写错误的! 人如果拼写错误了再通过``channel``和``bigram``来计算最适合的候选。
import numpy as np
import queue as Q
def word_corrector(word, context):
"""
在候选词中基于上下文找到概率最大的词
:param word:
:param context:
:return:
"""
word = word.lower()
# 生成跟这个单词距离为1或者2的所有的候选集合
candidate = generate_candidates(word)
if len(candidate) == 0:
return word
# 优先级队列实现大顶堆Heap,每次输出都是相似度最大值
correctors = Q.PriorityQueue()
# 通过``channel``和``bigram``来计算最适合的候选
for w in candidate:
# 如果候选单词在channel中并且正确单词在它的错误单词字典中,候选单词,文本的第一个第二个单词均在词表中
if w in channel and word in channel[w] and w in word2id and context[0].lower() in word2id and context[
1].lower() in word2id:
# 相乘转化为log是相加
# $c^* = \text{argmax}_{c\in candidates} ~~p(c|s) = \text{argmax}_{c\in candidates} ~~p(s|c)p(c)$
# 其中channel部分是p(c),bigram部分是p(s|c)
probility = np.log(channel[w][word] + 0.0001) + np.log(
bigram[word2id[context[0].lower()], word2id[w]]) + np.log(
bigram[word2id[context[1].lower()], word2id[w]])
# 加入大顶堆
correctors.put((-1 * probility, w))
if correctors.empty():
return word
# 返回最大概率的候选词
return correctors.get()[1]
word = word_corrector('strat', ('to', 'in'))
print(word)
def spell_corrector(line):
"""
对拼写错误进行修正
1. 首先做分词,然后把``line``表示成``tokens``
2. 循环每一token, 然后判断是否存在词库里。如果不存在就意味着是拼写错误的,需要修正。
修正的过程就使用上述提到的``noisy channel model``, 然后从而找出最好的修正之后的结果。
:param line:
:return:
"""
new_words = []
words = ['<s>'] + line.strip().lower().split(' ') + ['</s>']
for i, word in enumerate(words):
# 如果索引是尾部索引为break,因为尾部是'</s>'
if i == len(words) - 1:
break
word = word.lower()
if word not in word2id:
# 认为错误,需要修正,句子前后加了<s>,</s>
# 不在词表中词,肯定位于[1,len - 2]之间
# 如果单词不在词表中,则说明需要修正,将修正后的词添加到new_words中
new_words.append(word_corrector(word, (words[i - 1].lower(), words[i + 1].lower())))
else:
new_words.append(word)
# 修正后的结果
newline = ' '.join(new_words[1:])
# 返回修正之后的结果,假如用户输入没有问题,那这时候``newline = line``
return newline
sentence = spell_corrector('When did Beyonce strat becoming popular')
print(sentence)
# #### 4.5 基于拼写纠错算法,实现用户输入自动矫正
# 首先有了用户的输入``query``, 然后做必要的处理把句子转换成tokens的形状,然后对于每一个token比较是否是valid, 如果不是的话就进行下面的修正过程。
test_query1 = "When did Beyonce strat becoming popular" # 拼写错误的
# result:in the late 1990s
test_query2 = "What counted for more of the poplation change" # 拼写错误的
# result:births and deaths
test_query1 = spell_corrector(test_query1)
test_query2 = spell_corrector(test_query2)
print(test_query1)
print(test_query2)
| 008d77bf4d9a80d0c2a3d5574abfede88c8f8f5f | [
"Markdown",
"Python"
] | 2 | Markdown | Libra-1023/QA | e6a4398ac98aaf579115571fd36477821835ba66 | 16399794b7a5d37e7cd892ae84e38b5320c377ff |
refs/heads/master | <repo_name>ChathurangaSandun/UnityArchitecture<file_sep>/UnityArchitecture.DAL/Repository/CustomerRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityArchitecture.DAL.Common;
using UnityArchitecture.DAL.Interfaces;
using UnityArchitecture.DomainModel.Models;
namespace UnityArchitecture.DAL.Repository
{
public class CustomerRepository : GenericRepository<Customer>, ICustomerRepository
{
public CustomerRepository(UnityDbContext context) : base(context)
{
}
public Customer TopCustomer(int count)
{
return dbSet.First(o => o.Id == 1);
}
}
}
<file_sep>/README.md
# UnityArchitecture
this is full n-tier architectural unity DI base pilet project
https://jasenhk.wordpress.com/2013/06/11/unit-of-work-and-repository-pattern-with-unity-dependency-injection/
https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
<file_sep>/UnityArchitecture.DAL/UnityDbContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityArchitecture.DomainModel.Models;
namespace UnityArchitecture.DAL
{
public class UnityDbContext : DbContext
{
public UnityDbContext() : base("UnityDbContext")
{
}
private DbSet<Customer> Customers { get; set; }
}
}
//Enable-Migrations -ProjectName UnityArchitecture.Migrations -StartUpProjectName UnityArchitecture -ContextProjectName UnityArchitecture.DAL -ContextTypeName UnityDbContext
//Add-Migration -ProjectName UnityArchitecture.Migrations addcustomer_m1
//Update-Database -ProjectName UnityArchitecture.Migrations -verbose
<file_sep>/UnityArchitecture.DAL/Interfaces/ICustomerRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityArchitecture.DAL.Common;
using UnityArchitecture.DomainModel.Models;
namespace UnityArchitecture.DAL.Interfaces
{
public interface ICustomerRepository : IGenericRepository<Customer>
{
Customer TopCustomer(int count);
}
}
<file_sep>/UnityArchitecture.BAL/Services/CustomerService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityArchitecture.BAL.Interfaces;
using UnityArchitecture.DAL.Common;
using UnityArchitecture.DAL.Interfaces;
using UnityArchitecture.DomainModel.Models;
namespace UnityArchitecture.BAL.Services
{
public class CustomerService : ICustomerService
{
private IUnitOfWork _unitOfWork;
private readonly ICustomerRepository _customerRepository;
public CustomerService(IUnitOfWork unitOfWork, ICustomerRepository customerRepository)
{
_unitOfWork = unitOfWork;
_customerRepository = customerRepository;
}
public virtual Customer GetTop(int id)
{
return _customerRepository.TopCustomer(1);
}
}
}
<file_sep>/UnityArchitecture.BAL/Interfaces/ICustomerService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityArchitecture.DomainModel.Models;
namespace UnityArchitecture.BAL.Interfaces
{
public interface ICustomerService
{
Customer GetTop(int id);
}
}
<file_sep>/UnityArchitecture/App_Start/UnityIocContainer.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using UnityArchitecture.BAL.Interfaces;
using UnityArchitecture.BAL.Services;
using UnityArchitecture.DAL;
using UnityArchitecture.DAL.Common;
using UnityArchitecture.DAL.Interfaces;
using UnityArchitecture.DAL.Repository;
using UnityArchitecture.DependencyService;
namespace UnityArchitecture.App_Start
{
public static class UnityIocContainer
{
public static void ConfigIocContainer()
{
IUnityContainer container = new UnityContainer();
RegisterService(container);
DependencyResolver.SetResolver(new UnityResolver(container));
}
private static void RegisterService(IUnityContainer container)
{
container.RegisterType<IUnitOfWork, UnitOfWork>();
container.RegisterType<ICustomerRepository, CustomerRepository>();
container.RegisterType<DbContext,UnityDbContext>();
container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));
container.RegisterType<ICustomerService, CustomerService>();
}
}
}<file_sep>/UnityArchitecture/Controllers/CustomerController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UnityArchitecture.BAL.Interfaces;
using UnityArchitecture.DomainModel.Models;
namespace UnityArchitecture.Controllers
{
public class CustomerController : Controller
{
private readonly ICustomerService _customerService;
public CustomerController(ICustomerService customerService)
{
_customerService = customerService;
}
// GET: Customer
public ActionResult Index()
{
Customer c = _customerService.GetTop(1);
return View();
}
}
} | 4fc26ba64747fc501e6072327fafa512a8870785 | [
"Markdown",
"C#"
] | 8 | C# | ChathurangaSandun/UnityArchitecture | 3b505a25d8048354379ba5048c3c12335e28d9c2 | faff0ae530edec2d064ff2c9152c218ab0a6b3b3 |
refs/heads/master | <file_sep>/**
* 322. 零钱兑换(暴力递归超时)
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
if (amount === 0) return 0
let min = Number.MAX_SAFE_INTEGER
for (let i = 0, len = coins.length; i < len; i++) {
if (coins[i] > amount) continue
let res = coinChange(coins, amount - coins[i])
if (res === -1) continue
min = Math.min(min, res + 1)
}
return min === Number.MAX_SAFE_INTEGER ? -1 : min
}
/**
* 322. 零钱兑换(备忘录递归通过)
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
let obj = {},
len = coins.length
function change(amount) {
if (amount === 0) return 0
let min = Number.MAX_SAFE_INTEGER
for (let i = 0; i < len; i++) {
if (coins[i] > amount) continue
if (!obj.hasOwnProperty(amount - coins[i])) {
obj[amount - coins[i]] = change(amount - coins[i])
}
if (obj[amount - coins[i]] === -1) continue
min = Math.min(min, 1 + obj[amount - coins[i]])
}
return min === Number.MAX_SAFE_INTEGER ? -1 : min
}
return change(amount)
}
/**
* 322. 零钱兑换(动态规划通过)
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
let arr = new Array(amount + 1)
arr.fill(-1)
arr[0] = 0
for (let i = 1; i <= amount; i++) {
let min = Number.MAX_SAFE_INTEGER
for (let j = 0, len = coins.length; j < len; j++) {
if (i < coins[j]) continue
let res = arr[i - coins[j]]
if (res === -1) continue
min = Math.min(min, res + 1)
}
if (min !== Number.MAX_SAFE_INTEGER) {
arr[i] = min
}
}
return arr[amount]
}
/**
* 53. 最大子序和(暴力循环)
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function (nums) {
let max = Number.MIN_SAFE_INTEGER
for (let i = 0, len = nums.length; i < len; i++) {
let res = 0
for (let j = i; j < len; j++) {
res += nums[j]
max = Math.max(max, res)
}
}
return max
}
/**
* 53. 最大子序和(动态规划)
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function (nums) {
let res = nums[0],
last = nums[0]
for (let i = 1, len = nums.length; i < len; i++) {
last = Math.max(last + nums[i], nums[i])
res = Math.max(last, res)
}
return res
}
/**
* 198. 打家劫舍(动态规划)
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
if (nums.length === 0) return 0
if (nums.length === 1) return nums[0]
if (nums.length === 2) return Math.max(nums[0], nums[1])
let arr = [nums[0], nums[1]],
pMax = arr[0],
max = arr[1]
for (let i = 2, len = nums.length; i < len; i++) {
arr.push(pMax + nums[i])
pMax = Math.max(pMax, arr[i - 1])
max = Math.max(max, arr[i])
}
return max
}
/**
* 70. 爬楼梯(动态规划)
* @param {number} n
* @return {number}
*/
var climbStairs = function (n) {
if (n === 1) return 1
let a = 1,
b = 2
for (let i = 3; i <= n; i++) {
let temp = a + b
a = b
b = temp
}
return b
}
/**
* 5. 最长回文子串(暴力循环超时)
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
let max = ''
for (let i = 0, len = s.length; i < len; i++) {
let temp = '',
ans = ''
for (let j = i; j < len; j++) {
temp += s[j]
if (temp === temp.split('').reverse().join('')) {
ans = temp
}
}
if (ans.length > max.length) max = ans
}
return max
}
/**
* 300. 最长上升子序列
* @param {number[]} nums
* @return {number}
*/
var lengthOfLIS = function (nums) {
if (!nums.length) return 0
let dp = new Array(nums.length)
dp.fill(1)
for (let i = 0, len = nums.length; i < len; i++) {
let max = 1
for (let j = 0; j < i; j++) {
let temp = 1
if (nums[i] > nums[j]) temp += dp[j]
max = Math.max(max, temp)
}
dp[i] = max
}
return Math.max(...dp)
}
/**
* 64. 最小路径和
* @param {number[][]} grid
* @return {number}
*/
var minPathSum = function (grid) {
const dp = new Array(grid.length)
dp.fill(new Array(grid[0].length))
let temp1 = 0,
temp2 = grid[0][0]
for (let i = 0, len = grid.length; i < len; i++) {
for (let j = 0, len = grid[0].length; j < len; j++) {
if (i === 0) {
temp1 += grid[i][j]
dp[i][j] = temp1
continue
}
if (j === 0) {
temp2 += grid[i][j]
dp[i][j] = temp2
continue
}
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
}
}
return dp[grid.length - 1][grid[0].length - 1]
}
/**
* 509. 斐波那契数
* @param {number} N
* @return {number}
*/
var fib = function (N) {
if (N === 0) return 0
if (N === 1) return 1
let a = 0,
b = 1
for (let i = 2; i <= N; i++) {
let temp = a + b
a = b
b = temp
}
return b
}
/**
* 416. 分割等和子集(动态规划,01背包问题)
* @param {number[]} nums
* @return {boolean}
*/
var canPartition = function (nums) {
if (nums.length === 0) return true
let sum = 0,
n = nums.length
for (let i = 0; i < n; i++) {
sum += nums[i]
}
if (sum % 2 !== 0) return false
let c = sum / 2
let dp = new Array(c + 1)
dp.fill(false)
dp[nums[0]] = true
for (let i = 1; i < n; i++) {
for (let j = c; j >= nums[i]; j--) {
dp[j] = dp[j] || dp[j - nums[i]]
}
}
return dp[c]
}
/**
* 1049. 最后一块石头的重量 II(动态规划,01背包问题)
* @param {number[]} stones
* @return {number}
*/
var lastStoneWeightII = function (stones) {
let sum = 0,
n = stones.length
for (let i = 0; i < n; i++) {
sum += stones[i]
}
let max = Math.floor(sum / 2)
let dp = new Array(max + 1)
dp.fill(0)
for (let i = 0; i < n; i++) {
let cur = stones[i]
for (let j = max; j >= cur; j--) {
dp[j] = Math.max(dp[j], dp[j - cur] + cur)
}
}
return sum - dp[max] * 2
}
/**
* 474. 一和零(动态规划,01背包问题)
* @param {string[]} strs
* @param {number} m
* @param {number} n
* @return {number}
*/
var findMaxForm = function (strs, m, n) {
let len = strs.length
// m为0的个数, n为1的个数
let dp = new Array(m + 1)
for (let i = 0; i <= m; i++) {
dp[i] = new Array(n + 1)
dp[i].fill(0)
}
for (let i = 0; i < len; i++) {
let cur = strs[i],
zero = 0,
one = 0
for (let char = 0; char < cur.length; char++) {
if (cur[char] === '0') zero++
}
one = cur.length - zero
for (let j = m; j >= zero; j--) {
for (let k = n; k >= one; k--) {
dp[j][k] = Math.max(dp[j][k], 1 + dp[j - zero][k - one])
}
}
}
return dp[m][n]
}
/**
* 139. 单词拆分(动态规划,01背包问题)
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function (s, wordDict) {
let n = s.length
let dp = new Array(n + 1)
dp.fill(false)
dp[0] = true
for (let i = 1; i <= n; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && wordDict.indexOf(s.slice(j, i)) !== -1) {
dp[i] = true
break
}
}
}
return dp[n]
}
/**
* 322. 零钱兑换(动态规划,完全背包)
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
let len = coins.length
let dp = new Array(amount + 1)
dp.fill(-1)
dp[0] = 0
for (let i = 1; i <= amount; i++) {
let temp = Number.MAX_SAFE_INTEGER
for (let j = 0; j < len; j++) {
if (i - coins[j] >= 0 && dp[i - coins[j]] !== -1)
temp = Math.min(temp, 1 + dp[i - coins[j]])
}
if (temp !== Number.MAX_SAFE_INTEGER) dp[i] = temp
}
return dp[amount]
}
/**
* 518. 零钱兑换 II(动态规划,完全背包)
* @param {number} amount
* @param {number[]} coins
* @return {number}
*/
var change = function (amount, coins) {
let dp = new Array(amount + 1)
dp.fill(0)
dp[0] = 1
for (let i = 0, len = coins.length; i < len; i++) {
for (let j = coins[i]; j <= amount; j++) {
dp[j] += dp[j - coins[i]]
}
}
return dp[amount]
}
/**
* 198. 打家劫舍(动态规划,01背包问题)
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
if (!nums.length) return 0
let prev1 = 0,
prev2 = nums[0]
for (let i = 1, len = nums.length; i < len; i++) {
let temp = prev2
prev2 = Math.max(nums[i] + prev1, temp)
prev1 = temp
}
return prev2 > prev1 ? prev2 : prev1
}
/**
* 213. 打家劫舍 II(动态规划,01背包问题)
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
if (!nums.length) return 0
let prev1 = 0,
prev2 = nums[0]
for (let i = 1, len = nums.length - 1; i < len; i++) {
let temp = prev2
prev2 = Math.max(temp, prev1 + nums[i])
prev1 = temp
}
let prev3 = 0,
prev4 = nums[nums.length - 1]
for (let i = nums.length - 2; i > 0; i--) {
let temp = prev4
prev4 = Math.max(prev3 + nums[i], temp)
prev3 = temp
}
return prev4 > prev2 ? prev4 : prev2
}
/**
* 70. 爬楼梯(动态规划,斐波那契数列)
* @param {number} n
* @return {number}
*/
var climbStairs = function (n) {
let i = 1,
j = 1
for (let k = 2; k <= n; k++) {
let temp = j
j = i + temp
i = temp
}
return j
}
/**
* 300. 最长上升子序列(动态规划)
* @param {number[]} nums
* @return {number}
*/
var lengthOfLIS = function (nums) {
let len = nums.length,
dp = new Array(len)
dp.fill(1)
for (let i = 1; i < len; i++) {
let count = 1
for (let j = 0; j < i; j++) {
if (nums[i] - nums[j] > 0) count = Math.max(count, dp[j] + 1)
}
dp[i] = count
}
let res = 0
for (let i = 0; i < len; i++) {
res = Math.max(dp[i], res)
}
return res
}
/**
* 72. 编辑距离(暴力递归)
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var minDistance = function (word1, word2) {
function dp(i, j) {
if (i === -1 && j === -1) return 0
if (i === -1) return j + 1
if (j === -1) return i + 1
if (word1[i] === word2[j]) return dp(i - 1, j - 1)
let res = 1 + Math.min(dp(i, j - 1), dp(i - 1, j), dp(i - 1, j - 1))
return res
}
return dp(word1.length - 1, word2.length - 1)
}
/**
* 72. 编辑距离(动态规划)
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var minDistance = function (word1, word2) {
let len1 = word1.length,
len2 = word2.length
let dp = new Array(len1 + 1)
for (let i = 0; i <= len1; i++) {
dp[i] = new Array(len2)
dp[i][0] = i
}
for (let j = 0; j <= len2; j++) {
dp[0][j] = j
}
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
if (word2[j - 1] === word1[i - 1]) {
dp[i][j] = dp[i - 1][j - 1]
} else {
dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], dp[i][j - 1], dp[i - 1][j])
}
}
}
return dp[len1][len2]
}
/**
* 1143. 最长公共子序列(暴力递归)
* @param {string} text1
* @param {string} text2
* @return {number}
*/
var longestCommonSubsequence = function (text1, text2) {
function dp(i, j) {
if (i === -1 || j === -1) return 0
if (text2[j] === text1[i]) return 1 + dp(i - 1, j - 1)
return Math.max(dp(i, j - 1), dp(i - 1, j))
}
return dp(text1.length - 1, text2.length - 1)
}
/**
* 1143. 最长公共子序列(动态规划)
* @param {string} text1
* @param {string} text2
* @return {number}
*/
var longestCommonSubsequence = function (text1, text2) {
let len1 = text1.length,
len2 = text2.length
let dp = new Array(len1 + 1)
for (let i = 0; i <= len1; i++) {
dp[i] = new Array(len2 + 1)
dp[i][0] = 0
}
for (let i = 0; i <= len2; i++) {
dp[0][i] = 0
}
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
if (text1[i - 1] === text2[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1]
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[len1][len2]
}
/**
* 516. 最长回文子序列(暴力递归)
* @param {string} s
* @return {number}
*/
var longestPalindromeSubseq = function (s) {
function dp(n, str) {
if (n === -1)
return str === str.split('').reverse().join('') ? str.length : 0
return Math.max(dp(n - 1, str + s[n]), dp(n - 1, str))
}
return dp(s.length - 1, '')
}
/**
* 516. 最长回文子序列(暴力递归Ⅱ)
* @param {string} s
* @return {number}
*/
var longestPalindromeSubseq = function (s) {
function dp(i, j) {
if (i === j) return 1
if (s[i] === s[j]) return j - i > 1 ? dp(i + 1, j - 1) + 2 : 2
return Math.max(dp(i + 1, j), dp(i, j - 1))
}
return dp(0, s.length)
}
/**
* 435. 无重叠区间(贪心算法)
* @param {number[][]} intervals
* @return {number}
*/
var eraseOverlapIntervals = function (intervals) {
if (intervals.length === 0) return 0
intervals.sort((a, b) => a[1] - b[1])
let end = intervals[0][1],
count = 0
for (let i = 1; i < intervals.length; i++) {
let cur = intervals[i]
if (end > cur[0]) {
count++
} else {
end = cur[1]
}
}
return count
}
/**
* 452. 用最少数量的箭引爆气球(贪心算法)
* @param {number[][]} points
* @return {number}
*/
var findMinArrowShots = function (points) {
if (!points.length) return 0
points.sort((a, b) => a[1] - b[1])
let end = points[0][1],
count = 1
for (let i = 0, len = points.length; i < len; i++) {
let cur = points[i]
if (end < cur[0]) {
count++
end = cur[1]
}
}
return count
}
/**
* 121. 买卖股票的最佳时机(动态规划)
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
if (prices.length === 0) return 0
let len = prices.length
let dp = new Array(len)
for (let i = 0; i < len; i++) {
dp[i] = new Array(2)
}
for (let i = 0; i < len; i++) {
if (i === 0) {
dp[i][0] = 0
dp[i][1] = -prices[i]
} else {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i])
dp[i][1] = Math.max(dp[i - 1][1], -prices[i])
}
}
return dp[len - 1][0]
}
/**
* 122. 买卖股票的最佳时机 II(动态规划)
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
if (prices.length === 0) return 0
let len = prices.length,
dp = new Array(len)
for (let i = 0; i < len; i++) {
dp[i] = new Array(2)
}
for (let i = 0; i < len; i++) {
if (i === 0) {
dp[i][0] = 0
dp[i][1] = -prices[i]
} else {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i])
dp[i][1] = Math.max(dp[i - 1][0] - prices[i], dp[i - 1][1])
}
}
return dp[len - 1][0]
}
/**
* 198. 打家劫舍(暴力递归)
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
function dp(i) {
if (i < 0) return 0
if (i === 0) return nums[i]
return Math.max(nums[i] + dp(i - 2), dp(i - 1))
}
return dp(nums.length - 1)
}
/**
* 198. 打家劫舍(动态规划)
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
let len = nums.length,
dp = new Array(len + 1)
;(dp[0] = 0), (dp[1] = nums[0])
for (let i = 2; i <= len; i++) {
dp[i] = Math.max(nums[i - 1] + dp[i - 2], dp[i - 1])
}
return dp[len]
}
/**
* 337. 打家劫舍 III(暴力递归)
* @param {TreeNode} root
* @return {number}
*/
var rob = function (root) {
function dp(node) {
if (!node) return 0
let left = node.left ? dp(node.left.left) + dp(node.left.right) : 0,
right = node.right ? dp(node.right.left) + dp(node.right.right) : 0
return Math.max(node.val + left + right, dp(node.left) + dp(node.right))
}
return dp(root)
}
/**
* 338. 比特位计数
* @param {number} num
* @return {number[]}
*/
var countBits = function (num) {
if (num === 0) return [0]
let res = [0, 1],
mul = 2
for (let i = 2; i <= num; i++) {
if (i % mul === 0) {
res[i] = 1
mul *= 2
} else {
res[i] = res[mul / 2] + res[i - mul / 2]
}
}
return res
}
/**
* 416. 分割等和子集
* @param {number[]} nums
* @return {boolean}
*/
var canPartition = function (nums) {
const len = nums.length
if (!len) return false
let sum = 0
for (let i = 0; i < len; i++) sum += nums[i]
if (sum % 2 !== 0) return false
const half = sum >> 1
const dp = new Array(half + 1)
dp.fill(false)
dp[0] = true
for (let i = 0; i < len; i++) {
for (let j = half; j >= nums[i]; j--) {
dp[j] = dp[j] || dp[j - nums[i]]
}
}
return dp[half]
}
/**
* 115. 不同的子序列
* @param {string} s
* @param {string} t
* @return {number}
*/
var numDistinct = function (s, t) {
const lenS = s.length,
lenT = t.length
const dp = new Array(lenS + 1)
for (let i = 0; i <= lenS; i++) {
dp[i] = new Array(lenT + 1)
dp[i].fill(0)
dp[i][lenT] = 1
}
for (let i = lenS - 1; i >= 0; i--) {
for (let j = lenT - 1; j >= 0; j--) {
if (s[i] === t[j]) {
dp[i][j] = dp[i + 1][j + 1] + dp[i + 1][j]
} else {
dp[i][j] = dp[i + 1][j]
}
}
}
return dp[0][0]
}
/**
* 956. 最高的广告牌
* @param {number[]} rods
* @return {number}
*/
var tallestBillboard = function (rods) {
const len = rods.length
let res = 0
let sum = 0
for (let i = 0; i < len; i++) sum += rods[i]
rods.sort((a, b) => b - a)
function dp(i, l, r, remain) {
if (Math.abs(l - r) > remain || (l + r + remain) >> 1 <= res) return
if (l === r) res = Math.max(res, l)
if (i >= len) return
dp(i + 1, l + rods[i], r, remain - rods[i])
dp(i + 1, l, r + rods[i], remain - rods[i])
dp(i + 1, l, r, remain - rods[i])
}
dp(0, 0, 0, sum)
return res
}
/**
* 1155. 掷骰子的N种方法
* @param {number} d
* @param {number} f
* @param {number} target
* @return {number}
*/
var numRollsToTarget = function (d, f, target) {
// 暴力递归
// function dp(d,remain){
// if(d === 0 && remain === 0) return 1
// if(remain < 0 || d === 0 || remain > d*f) return 0
// let res = 0
// for(let i = 1;i<=f;i++){
// res += dp(d-1,remain-i)
// }
// return res
// }
// return dp(d,target)
const dp = new Array(d + 1)
for (let i = 0; i <= d; i++) {
dp[i] = new Array(target + 1)
dp[i].fill(0)
}
dp[0][0] = 1
for (let i = 1; i <= d; i++) {
for (let j = 1; j <= target; j++) {
let res = 0
for (let k = 1; k <= f; k++) {
res += dp[i - 1][j - k] ? dp[i - 1][j - k] : 0
}
dp[i][j] = res % 1000000007
}
}
return dp[d][target]
}
/**
* 553. 最优除法
* @param {number[]} nums
* @return {string}
*/
var optimalDivision = function (nums) {
if (nums.length === 1) return nums.toString()
if (nums.length === 2) return nums.join('/')
let ans = nums[0] + '/' + '('
for (let i = 1, len = nums.length; i < len; i++) {
ans += nums[i]
if (i !== len - 1) ans += '/'
}
ans += ')'
return ans
}
/**
* 1217. 玩筹码
* @param {number[]} chips
* @return {number}
*/
var minCostToMoveChips = function (chips) {
let ans1 = 0,
ans2 = 0
for (let i = 0, len = chips.length; i < len; i++) {
if (chips[i] % 2 === 0) {
ans1++
} else {
ans2++
}
}
return Math.min(ans1, ans2)
}
/**
* 115. 不同的子序列
* @param {string} s
* @param {string} t
* @return {number}
*/
var numDistinct = function (s, t) {
const lenS = s.length,
lenT = t.length
const dp = new Array(lenT + 1)
dp.fill(0)
dp[lenT] = 1
for (let i = lenS - 1; i >= 0; i--) {
let prev = dp[lenT]
for (let j = lenT - 1; j >= 0; j--) {
let temp = dp[j]
const charS = s[i],
charT = t[j]
if (charS === charT) {
dp[j] = prev + dp[j]
} else {
dp[j] = dp[j]
}
prev = temp
}
}
return dp[0]
}
/**
* 300. 最长上升子序列
* @param {number[]} nums
* @return {number}
*/
var lengthOfLIS = function (nums) {
const len = nums.length
const dp = new Array(len)
if (!len) return 0
dp.fill(1)
let max = 1
for (let i = 1; i < len; i++) {
for (let j = 0; j < i; j++) {
if (nums[i] > nums[j]) dp[i] = Math.max(dp[j] + 1, dp[i])
}
max = Math.max(max, dp[i])
}
return max
}
/**
* 646. 最长数对链
* @param {number[][]} pairs
* @return {number}
*/
var findLongestChain = function (pairs) {
if (!pairs.length) return 0
pairs.sort((a, b) => a[0] - b[0])
const len = pairs.length
const dp = new Array(len)
dp.fill(1)
let max = 1
for (let i = 1; i < len; i++) {
for (let j = 0; j < i; j++) {
if (pairs[i][0] > pairs[j][1]) dp[i] = Math.max(dp[j] + 1, dp[i])
}
max = Math.max(dp[i], max)
}
return max
}
/**
* 354. 俄罗斯套娃信封问题
* @param {number[][]} envelopes
* @return {number}
*/
var maxEnvelopes = function (envelopes) {
envelopes.sort((a, b) => a[1] - b[1])
const len = envelopes.length
if (!len) return 0
const dp = new Array(len)
dp.fill(1)
let max = 1
for (let i = 1; i < len; i++) {
for (let j = 0; j < i; j++) {
if (
envelopes[i][0] > envelopes[j][0] &&
envelopes[i][1] !== envelopes[j][1]
) {
dp[i] = Math.max(dp[i], dp[j] + 1)
}
}
max = Math.max(max, dp[i])
}
return max
}
/**
* 877. 石子游戏
* @param {number[]} piles
* @return {boolean}
*/
var stoneGame = function (piles) {
const len = piles.length
const dp = new Array(len)
for (let i = 0; i < len; i++) {
dp[i] = new Array(len)
for (let j = 0; j < len; j++) {
dp[i][j] = [0, 0]
dp[i][i] = [piles[i], 0]
}
}
for (let l = 1; l < len; l++) {
for (let i = 0; i < len - l; i++) {
let j = i + l
const left = piles[i] + dp[i + 1][j][1]
const right = piles[j] + dp[i][j - 1][1]
if (left > right) {
dp[i][j][0] = left
dp[i][j][1] = dp[i + 1][j][0]
} else {
dp[i][j][0] = right
dp[i][j][1] = dp[i][j - 1][0]
}
}
}
return dp[len - 1][len - 1][0] > dp[len - 1][len - 1][1]
}
/**
* 446. 等差数列划分 II - 子序列
* @param {number[]} A
* @return {number}
*/
var numberOfArithmeticSlices = function (A) {
let ans = 0
const len = A.length,
dp = new Array(len)
for (let i = 0; i < len; i++) {
dp[i] = new Map()
for (let j = 0; j < i; j++) {
const diff = A[i] - A[j]
const sum = dp[j].get(diff) || 0
ans += sum
dp[i].set(diff, (dp[i].get(diff) || 0) + sum + 1)
}
}
return ans
}
/**
* 940. 不同的子序列 II
* @param {string} S
* @return {number}
*/
var distinctSubseqII = function (S) {
const len = S.length,
mod = 1000000007
const dp = new Array(len + 1)
dp[0] = 1
for (let i = 0; i < len; i++) {
dp[i + 1] = 2 * dp[i]
let j = i - 1
while (j >= 0 && S[j] !== S[i]) j--
if (j >= 0) dp[i + 1] -= dp[j]
dp[i + 1] %= mod
}
if (dp[len] < 0) dp[len] += mod
return dp[len] - 1
}
/**
* 1425. 带限制的子序列和
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var constrainedSubsetSum = function (nums, k) {
const dequeue = [],
len = nums.length,
dp = new Array(len)
let ans = Number.MIN_SAFE_INTEGER
for (let i = 0; i < len; i++) {
const pre_max = dequeue.length ? dp[dequeue[0]] : 0
dp[i] = Math.max(pre_max + nums[i], nums[i])
ans = Math.max(ans, dp[i])
while (dequeue.length && dp[dequeue[dequeue.length - 1]] < dp[i])
dequeue.pop()
dequeue.push(i)
if (dequeue.length > 1 && dequeue[dequeue.length - 1] - dequeue[0] >= k)
dequeue.shift()
}
return ans
}
/**
* 123. 买卖股票的最佳时机 III
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
// function dfs(i,k){
// if(i < 0 || k === 0) return [0,Number.MIN_SAFE_INTEGER]
// const status_0 = Math.max(dfs(i-1,k)[0],dfs(i-1,k)[1]+prices[i])
// const status_1 = Math.max(dfs(i-1,k)[1],dfs(i-1,k-1)[0]-prices[i])
// return [status_0,status_1]
// }
// return dfs(prices.length-1,2)[0]
const len = prices.length,
dp = new Array(len)
for (let i = 0; i < len; i++) {
dp[i] = new Array(3)
dp[i][0] = [0, Number.MIN_SAFE_INTEGER]
}
dp[-1] = new Array(3)
dp[-1].fill([0, Number.MIN_SAFE_INTEGER])
for (let i = 0; i < len; i++) {
for (let j = 1; j < 3; j++) {
const status_0 = Math.max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i])
const status_1 = Math.max(
dp[i - 1][j][1],
dp[i - 1][j - 1][0] - prices[i]
)
dp[i][j] = [status_0, status_1]
}
}
return dp[len - 1][2][0]
}
/**
* 546. 移除盒子
* @param {number[]} boxes
* @return {number}
*/
var removeBoxes = function (boxes) {
const len = boxes.length
const dp = new Array(len)
for (let i = 0; i < len; i++) {
dp[i] = new Array(len)
for (let j = 0; j < len; j++) {
dp[i][j] = new Array(len)
dp[i][j].fill(0)
}
}
function dfs(l, r, k) {
if (l > r) return 0
if (dp[l][r][k]) return dp[l][r][k]
while (l < r && boxes[r] === boxes[r - 1]) {
k++
r--
}
dp[l][r][k] = dfs(l, r - 1, 0) + (k + 1) * (k + 1)
for (let i = l; i < r; i++) {
if (boxes[i] === boxes[r]) {
dp[l][r][k] = Math.max(
dp[l][r][k],
dfs(l, i, k + 1) + dfs(i + 1, r - 1, 0)
)
}
}
return dp[l][r][k]
}
return dfs(0, len - 1, 0)
}
/**
* 312. 戳气球
* @param {number[]} nums
* @return {number}
*/
var maxCoins = function (nums) {
const len = nums.length
nums.push(1)
nums.unshift(1)
const dp = new Array(len + 2)
for (let i = 0; i < len + 2; i++) {
dp[i] = new Array(len + 2)
dp[i].fill(0)
}
function dfs(l, r) {
if (r - l === 1) return 0
if (dp[l][r]) return dp[l][r]
for (let i = l + 1; i < r; i++) {
dp[l][r] = Math.max(
dp[l][r],
nums[i] * nums[l] * nums[r] + dfs(l, i) + dfs(i, r)
)
}
return dp[l][r]
}
return dfs(0, len + 1)
}
/**
* 87. 扰乱字符串
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var isScramble = function (s1, s2) {
if (s1.length !== s2.length) return false
const len = s1.length
const dp = new Array(len)
for (let i = 0; i < len; i++) {
dp[i] = new Array(len)
for (let j = 0; j < len; j++) {
dp[i][j] = new Array(len)
dp[i][j].fill(-1)
}
}
function dfs(i1, j1, i2) {
if (dp[i1][j1][i2] !== -1) return dp[i1][j1][i2]
if (s1.slice(i1, j1 + 1) === s2.slice(i2, i2 + (j1 - i1) + 1))
dp[i1][j1][i2] = true
for (let i = i1; i < j1; i++) {
if (
(dfs(i1, i, i2) && dfs(i + 1, j1, i2 + (i - i1) + 1)) ||
(dfs(i1, i, i2 + j1 - i) && dfs(i + 1, j1, i2))
) {
dp[i1][j1][i2] = true
break
}
}
if (dp[i1][j1][i2] === -1) dp[i1][j1][i2] = false
return dp[i1][j1][i2]
}
return dfs(0, len - 1, 0)
}
/**
* 1092. 最短公共超序列
* @param {string} str1
* @param {string} str2
* @return {string}
*/
var shortestCommonSupersequence = function (str1, str2) {
const len1 = str1.length,
len2 = str2.length
const dp = new Array(len1 + 1)
for (let i = 0; i <= len1; i++) {
dp[i] = new Array(len2 + 1)
dp[i].fill(-1)
}
function dfs(i, j) {
if (i === len1 || j === len2) return ''
if (dp[i][j] !== -1) return dp[i][j]
if (str1[i] === str2[j]) {
if (dp[i + 1][j + 1] === -1) dp[i + 1][j + 1] = dfs(i + 1, j + 1)
return str1[i] + dp[i + 1][j + 1]
} else {
if (dp[i + 1][j] === -1) dp[i + 1][j] = dfs(i + 1, j)
if (dp[i][j + 1] === -1) dp[i][j + 1] = dfs(i, j + 1)
return dp[i + 1][j].length > dp[i][j + 1].length
? dp[i + 1][j]
: dp[i][j + 1]
}
}
let ans = ''
const lcs = dfs(0, 0)
let i = 0,
j = 0
for (let k = 0, len = lcs.length; k < len; k++) {
while (i < len1 && str1[i] !== lcs[k]) ans += str1[i++]
while (j < len2 && str2[j] !== lcs[k]) ans += str2[j++]
ans += lcs[k]
i++
j++
}
return ans + str1.slice(i) + str2.slice(j)
}
<file_sep>/**
* 101. 对称二叉树
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function (root) {
if (!root) return true
function compare(root1, root2) {
if (!root1 && !root2) return true
if ((root1 && !root2) || (!root1 && root2)) return false
if (root1.val !== root2.val) return false
return compare(root1.left, root2.right) && compare(root1.right, root2.left)
}
return compare(root.left, root.right)
}
/**
* 938. 二叉搜索树的范围和
* @param {TreeNode} root
* @param {number} L
* @param {number} R
* @return {number}
*/
var rangeSumBST = function (root, L, R) {
let arr = []
//哈哈哈我疯了中序遍历把每个值保存进数组
function midOrderTraversal(root) {
if (!root) return
midOrderTraversal(root.left)
arr.push(root.val)
midOrderTraversal(root.right)
}
midOrderTraversal(root)
let result = 0
for (let i = 0, len = arr.length; i < len; i++) {
if (arr[i] >= L && arr[i] <= R) {
result += arr[i]
}
}
return result
}
/**
* 653. 两数之和 IV - 输入 BST
* @param {TreeNode} root
* @param {number} k
* @return {boolean}
*/
var findTarget = function (root, k) {
//思路就是遍历它
let arr = []
function traversal(root) {
if (!root) return false
if (arr.includes(k - root.val)) return true
arr.push(root.val)
return traversal(root.left) || traversal(root.right)
}
return traversal(root)
}
/**
* 404.左叶子之和
* @param {TreeNode} root
* @return {number}
*/
var sumOfLeftLeaves = function (root) {
if (!root) return 0
let result = 0
if (root.left && !root.left.left && !root.left.right) result += root.left.val
return result + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right)
}
/**
* 257. 二叉树的所有路径
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function (root) {
let res = []
if (!root) return res
function getPath(root, str) {
str === '' ? (str += +root.val) : (str += '->' + root.val)
if (!root.left && !root.right) {
res.push(str)
return res
}
if (root.left) getPath(root.left, str)
if (root.right) getPath(root.right, str)
}
let str = ''
getPath(root, str)
return res
}
/**
* 1038. 从二叉搜索树到更大和树(中序遍历逆序)
* @param {TreeNode} root
* @return {TreeNode}
*/
var bstToGst = function (root) {
let sum = 0
function updateNode(node) {
if (!node) return
updateNode(node.right)
let temp = node.val
node.val += sum
sum += temp
updateNode(node.left)
}
updateNode(root)
return root
}
/**
* 114. 二叉树展开为链表
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-place instead.
*/
var flatten = function (root) {
function flat(root) {
if (!root || (!root.left && !root.right)) return
if (!root.left && root.right) {
} else if (root.left && !root.right) {
root.right = root.left
root.left = null
} else {
let right = root.right
root.right = root.left
root.left = null
let temp = root.right
while (temp.right) {
temp = temp.right
}
temp.right = right
}
flat(root.right)
}
flat(root)
}
/**
* 230. 二叉搜索树中第K小的元素
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function (root, k) {
let count = 1,
res = null
function getTthSmallest(node) {
if (!node) return null
if (res) return
getTthSmallest(node.left)
if (k === count) {
res = node.val
count++
return
} else {
count++
}
getTthSmallest(node.right)
}
getTthSmallest(root)
return res
}
/**
* 951. 翻转等价二叉树
* @param {TreeNode} root1
* @param {TreeNode} root2
* @return {boolean}
*/
var flipEquiv = function (root1, root2) {
if (!root1 && !root2) return true
if ((!root1 && root2) || (root1 && !root2)) return false
if (root1.val !== root2.val) return false
return (
(flipEquiv(root1.left, root2.right) &&
flipEquiv(root1.right, root2.left)) ||
(flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right))
)
}
/**
* 102. 二叉树的层次遍历(队列)
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function (root) {
if (!root) return []
let res = [],
queue = [root, 'ok'],
temp = [],
count = 0
while (queue.length) {
let cur = queue.shift()
if (cur === 'ok') {
res.push(temp)
temp = []
if (count) queue.push('ok')
count = 0
} else {
if (cur.left) {
queue.push(cur.left)
count++
}
if (cur.right) {
queue.push(cur.right)
count++
}
temp.push(cur.val)
}
}
return res
}
/**
* 102. 二叉树的层次遍历(优化)
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function (root) {
if (!root) return []
let queue = [root],
res = []
while (queue.length) {
let count = queue.length,
temp = []
while (count) {
let cur = queue.shift()
temp.push(cur.val)
if (cur.left) {
queue.push(cur.left)
}
if (cur.right) {
queue.push(cur.right)
}
count--
}
res.push(temp)
}
return res
}
/**
* 102. 二叉树的层次遍历(dfs)
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function (root) {
let res = []
function dfs(node, count) {
if (!node) return
if (Array.isArray(res[count])) {
res[count].push(node.val)
} else {
res[count] = [node.val]
}
if (node.left) dfs(node.left, count + 1)
if (node.right) dfs(node.right, count + 1)
}
dfs(root, 0)
return res
}
/**
* 107. 二叉树的层次遍历 II(dfs)
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrderBottom = function (root) {
let res = []
function dfs(node, count) {
if (!node) return
if (Array.isArray(res[count])) {
res[count].push(node.val)
} else {
res[count] = [node.val]
}
if (node.left) dfs(node.left, count + 1)
if (node.right) dfs(node.right, count + 1)
}
dfs(root, 0)
res.reverse()
return res
}
/**
* 103. 二叉树的锯齿形层次遍历(dfs)
* @param {TreeNode} root
* @return {number[][]}
*/
var zigzagLevelOrder = function (root) {
let res = []
function dfs(node, count) {
if (!node) return
if (Array.isArray(res[count])) {
if (count % 2 === 0) {
res[count].push(node.val)
} else {
res[count].unshift(node.val)
}
} else {
res[count] = [node.val]
}
if (node.left) dfs(node.left, count + 1)
if (node.right) dfs(node.right, count + 1)
}
dfs(root, 0)
return res
}
/**
* 637. 二叉树的层平均值(队列)
* @param {TreeNode} root
* @return {number[]}
*/
var averageOfLevels = function (root) {
if (!root) return []
let res = [],
queue = [root]
while (queue.length) {
let count = queue.length,
x = count,
sum = 0
while (count) {
let cur = queue.shift()
sum += cur.val
if (cur.left) {
queue.push(cur.left)
}
if (cur.right) {
queue.push(cur.right)
}
count--
}
res.push(sum / x)
}
return res
}
/**
* 111. 二叉树的最小深度(队列)
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function (root) {
if (!root) return 0
let queue = [root],
len = 0
while (queue.length) {
let count = queue.length
len++
while (count) {
let cur = queue.shift()
if (cur.left || cur.right) {
cur.left && queue.push(cur.left)
cur.right && queue.push(cur.right)
} else {
return len
}
count--
}
}
}
/**
* 111. 二叉树的最小深度(dfs)
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function (root) {
if (!root) return 0
let res = Number.MAX_SAFE_INTEGER
function dfs(node, count) {
if (!node) return
if (node.left || node.right) {
node.left && dfs(node.left, count + 1)
node.right && dfs(node.right, count + 1)
} else {
res = Math.min(res, count)
}
}
dfs(root, 1)
return res
}
/**
* 112. 路径总和(dfs)
* @param {TreeNode} root
* @param {number} sum
* @return {boolean}
*/
var hasPathSum = function (root, sum) {
function dfs(node, sum) {
if (!node) return false
sum -= node.val
if (!node.right && !node.left) {
return sum === 0
}
return dfs(node.left, sum) || dfs(node.right, sum)
}
return dfs(root, sum)
}
/**
* 113. 路径总和 II(dfs)
* @param {TreeNode} root
* @param {number} sum
* @return {number[][]}
*/
var pathSum = function (root, sum) {
let res = []
function dfs(node, temp, sum) {
if (!node) return
sum -= node.val
temp.push(node.val)
if (!node.left && !node.right) {
if (sum === 0) {
res.push(temp)
}
return
}
dfs(node.left, [...temp], sum)
dfs(node.right, [...temp], sum)
}
dfs(root, [], sum)
return res
}
/**
* 437. 路径总和 III(dfs)
* @param {TreeNode} root
* @param {number} sum
* @return {number}
*/
var pathSum = function (root, sum) {
function dfs(node, count, arr) {
if (!node) return 0
let cur = node.val,
n = cur === sum ? 1 : 0
arr[count] = node.val
for (let i = count; i > 0; i--) {
cur += arr[i - 1]
if (cur === sum) n++
}
return n + dfs(node.left, count + 1, arr) + dfs(node.right, count + 1, arr)
}
return dfs(root, 0, [])
}
/**
* 257. 二叉树的所有路径(dfs)
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function (root) {
let res = []
function dfs(node, path) {
if (!node) return
if (!node.left && !node.right) {
path += node.val
res.push(path)
} else {
path += node.val + '->'
}
dfs(node.left, path)
dfs(node.right, path)
}
dfs(root, '')
return res
}
/**
* 987. 二叉树的垂序遍历
* @param {TreeNode} root
* @return {number[][]}
*/
var verticalTraversal = function (root) {
const arr = []
const ans = []
function dfs(root, x, y) {
if (!root) return
arr.push({ x, y, val: root.val })
dfs(root.left, x - 1, y - 1)
dfs(root.right, x + 1, y - 1)
}
dfs(root, 0, 0)
function compare(a, b) {
return a.x - b.x || b.y - a.y || a.val - b.val
}
arr.sort(compare)
for (let i = 0, len = arr.length; i < len; i++) {
ans.push([arr[i].val])
while (arr[i + 1] && arr[i].x === arr[i + 1].x) {
ans[ans.length - 1].push(arr[++i].val)
}
}
return ans
}
/**
* 623. 在二叉树中增加一行
* @param {TreeNode} root
* @param {number} v
* @param {number} d
* @return {TreeNode}
*/
var addOneRow = function (root, v, d) {
if (d === 1) {
const node = new TreeNode(v)
node.left = root
return node
} else {
const ans = root
dfs(root, v, 1, d)
return ans
}
}
function dfs(node, v, n, d) {
if (!node) return
if (n === d - 1) {
let l = node.left,
r = node.right
node.left = new TreeNode(v)
node.left.left = l
node.right = new TreeNode(v)
node.right.right = r
return
}
dfs(node.left, v, n + 1, d)
dfs(node.right, v, n + 1, d)
}
/**
* 508. 出现次数最多的子树元素和
* @param {TreeNode} root
* @return {number[]}
*/
var findFrequentTreeSum = function (root) {
const hash = {}
const max = { count: 0, val: [] }
hash.max = max
function getSum(node) {
if (!node) return 0
const l = getSum(node.left)
const r = getSum(node.right)
const sum = node.val + l + r
if (hash[sum]) {
hash[sum]++
} else {
hash[sum] = 1
}
if (hash[sum] > hash.max.count) {
hash.max.count = hash[sum]
hash.max.val = [sum]
} else if (hash[sum] === hash.max.count) {
hash.max.val.push(sum)
}
return sum
}
getSum(root)
return hash.max.val
}
/**
* 907. 子数组的最小值之和
* @param {number[]} A
* @return {number}
*/
var sumSubarrayMins = function (A) {
let ans = 0
const stack = []
A.push(Number.MIN_SAFE_INTEGER)
A.unshift(Number.MIN_SAFE_INTEGER)
for (let i = 0, len = A.length; i < len; i++) {
while (stack.length > 1 && A[stack[stack.length - 1]] > A[i]) {
const cur = stack.pop()
ans += A[cur] * (i - cur) * (cur - stack[stack.length - 1])
}
stack.push(i)
}
return ans % 1000000007
}
/**
* 662. 二叉树最大宽度
* @param {TreeNode} root
* @return {number}
*/
var widthOfBinaryTree = function (root) {
const hash = {}
let ans = 1
function dfs(node, i, pos) {
if (!node) return
if (hash.hasOwnProperty(i)) {
ans = Math.max(Math.abs(pos - hash[i] + 1), ans)
} else {
hash[i] = pos
}
dfs(node.left, i + 1, pos * 2)
dfs(node.right, i + 1, pos * 2 + 1)
}
dfs(root, 0, 1)
return ans
}
/**
* 889. 根据前序和后序遍历构造二叉树
* @param {number[]} pre
* @param {number[]} post
* @return {TreeNode}
*/
var constructFromPrePost = function (pre, post) {
if (!pre.length) return null
const cur = pre[0]
const node = new TreeNode(cur)
const l = pre[1],
r = post[post.length - 2]
if (l || l === r) {
const i = post.indexOf(l)
node.left = constructFromPrePost(pre.slice(1, i + 2), post.slice(0, i + 1))
}
if (r && l !== r) {
const i = pre.indexOf(r)
node.right = constructFromPrePost(
pre.slice(i),
post.slice(i - 1, post.length - 1)
)
}
return node
}
/**
* 1161. 最大层内元素和
* @param {TreeNode} root
* @return {number}
*/
var maxLevelSum = function (root) {
let sum = Number.MIN_SAFE_INTEGER,
ans = 0,
n = 0
const queue = [root]
while (queue.length) {
let count = queue.length
let temp = 0
while (count) {
const cur = queue.shift()
if (cur) temp += cur.val
if (cur.left) queue.push(cur.left)
if (cur.right) queue.push(cur.right)
count--
}
n++
if (temp > sum) {
ans = n
sum = temp
}
}
return ans
}
/**
* 701. 二叉搜索树中的插入操作
* @param {TreeNode} root
* @param {number} val
* @return {TreeNode}
*/
var insertIntoBST = function (root, val) {
if (!root) return new TreeNode(val)
if (root.val < val) {
if (root.right) {
insertIntoBST(root.right, val)
} else {
root.right = new TreeNode(val)
}
} else {
if (root.left) {
insertIntoBST(root.left, val)
} else {
root.left = new TreeNode(val)
}
}
return root
}
/**
* 729. 我的日程安排表 I
*/
var MyCalendar = function () {
this.cal = null
}
function SegNode(s, e) {
this.start = s
this.end = e
this.left = null
this.right = null
}
/**
*
* @param {number} start
* @param {number} end
* @return {boolean}
*/
MyCalendar.prototype.book = function (start, end) {
if (this.cal === null) {
this.cal = new SegNode(start, end)
return true
}
let node = this.cal
while (true) {
if (node.start >= end) {
if (node.left) {
node = node.left
} else {
node.left = new SegNode(start, end)
return true
}
} else if (node.end <= start) {
if (node.right) {
node = node.right
} else {
node.right = new SegNode(start, end)
return true
}
} else {
return false
}
}
}
/**
* Your MyCalendar object will be instantiated and called as such:
* var obj = new MyCalendar()
* var param_1 = obj.book(start,end)
*/
/**
* 589. N叉树的前序遍历
* @param {Node} root
* @return {number[]}
*/
var preorder = function (root) {
const ans = []
if (!root) return ans
const stack = [root]
while (stack.length) {
const cur = stack.pop()
ans.push(cur.val)
for (let i = cur.children.length - 1; i >= 0; i--) {
stack.push(cur.children[i])
}
}
return ans
}
/**
* 590. N叉树的后序遍历
* @param {Node} root
* @return {number[]}
*/
var postorder = function (root) {
const ans = []
if (!root) return ans
const stack = [root]
while (stack.length) {
const cur = stack.pop()
ans.push(cur.val)
for (let i = 0, len = cur.children.length; i < len; i++) {
stack.push(cur.children[i])
}
}
return ans.reverse()
}
/**
* 1041. 困于环中的机器人
* @param {string} instructions
* @return {boolean}
*/
var isRobotBounded = function (instructions) {
const hash = {
0: [1, 0],
90: [0, 1],
180: [-1, 0],
270: [0, -1],
}
let cnt = 4
let x = 0,
y = 0,
ang = 0
while (cnt--) {
for (let i = 0, len = instructions.length; i < len; i++) {
if (instructions[i] === 'G') {
const temp = hash[ang]
x += temp[0]
y += temp[1]
} else if (instructions[i] === 'L') {
ang = (ang + 90) % 360
} else {
ang = ang - 90 < 0 ? ang - 90 + 360 : ang - 90
}
}
}
return x === 0 && y === 0
}
/**
* 731. 我的日程安排表 II
*/
var MyCalendarTwo = function () {
this.repeat = []
this.cal = []
}
/**
* @param {number} start
* @param {number} end
* @return {boolean}
*/
MyCalendarTwo.prototype.book = function (start, end) {
for (let i = 0, len = this.repeat.length; i < len; i++) {
if (start >= this.repeat[i][1] || end <= this.repeat[i][0]) continue
return false
}
for (let i = 0, len = this.cal.length; i < len; i++) {
if (start >= this.cal[i][1] || end <= this.cal[i][0]) continue
this.repeat.push([
Math.max(start, this.cal[i][0]),
Math.min(end, this.cal[i][1]),
])
}
this.cal.push([start, end])
return true
}
/**
* 998. 最大二叉树 II
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} val
* @return {TreeNode}
*/
var insertIntoMaxTree = function (root, val) {
const node = new TreeNode(val)
if (!root) return node
if (root.val < val) {
node.left = root
return node
}
root.right = insertIntoMaxTree(root.right, val)
return root
}
/**
* 669. 修剪二叉搜索树
* @param {TreeNode} root
* @param {number} L
* @param {number} R
* @return {TreeNode}
*/
var trimBST = function (root, L, R) {
if (!root) return null
if (root.val > R) return trimBST(root.left, L, R)
if (root.val < L) return trimBST(root.right, L, R)
root.left = trimBST(root.left, L, R)
root.right = trimBST(root.right, L, R)
return root
}
/**
* 654. 最大二叉树
* @param {number[]} nums
* @return {TreeNode}
*/
var constructMaximumBinaryTree = function (nums) {
if (!nums.length) return null
let maxIndex = 0
for (let i = 1, len = nums.length; i < len; i++) {
if (nums[maxIndex] < nums[i]) maxIndex = i
}
const root = new TreeNode(nums[maxIndex])
root.left = constructMaximumBinaryTree(nums.slice(0, maxIndex))
root.right = constructMaximumBinaryTree(nums.slice(maxIndex + 1))
return root
}
/**
* 235. 二叉搜索树的最近公共祖先
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function (root, p, q) {
if (!root) return null
const a = p.val,
m = root.val,
b = q.val
if ((a < m && b > m) || (a > m && b < m) || m === a || m === b) return root
if (a > m) {
return lowestCommonAncestor(root.right, p, q)
} else {
return lowestCommonAncestor(root.left, p, q)
}
}
/**
* 145. 二叉树的后序遍历
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function (root) {
const ans = []
const stack = []
let cur = root
let prev = null
while (cur || stack.length) {
if (cur) {
stack.push(cur)
cur = cur.left
} else {
const temp = stack[stack.length - 1]
if (temp.right && temp.right !== prev) {
cur = temp.right
} else {
prev = stack.pop()
ans.push(prev.val)
}
}
}
return ans
}
/**
* 968. 监控二叉树
* @param {TreeNode} root
* @return {number}
*/
var minCameraCover = function (root) {
function dfs(node) {
if (!node) return [0, 0, 1]
const l = dfs(node.left),
r = dfs(node.right)
const ans = []
ans[0] = l[1] + r[1]
ans[1] = Math.min(l[2] + r[1], l[2] + r[2], l[1] + r[2])
ans[2] = 1 + Math.min(...l) + Math.min(...r)
return ans
}
const ans = dfs(root)
return Math.min(ans[1], ans[2])
}
<file_sep>/**
* 472. 连接词
* @param {string[]} words
* @return {string[]}
*/
var findAllConcatenatedWordsInADict = function (words) {
const pre = new Set()
const ans = []
words.sort((a, b) => a.length - b.length)
function dfs(word, start) {
let temp = ''
for (let i = start, len = word.length; i < len; i++) {
temp += word[i]
if (pre.has(temp) && (pre.has(word.slice(i + 1)) || dfs(word, i + 1))) {
return true
}
}
return false
}
for (let i = 0, len = words.length; i < len; i++) {
if (dfs(words[i], 0)) {
ans.push(words[i])
} else {
pre.add(words[i])
}
}
return ans
}
/**
* 1269. 停在原地的方案数
* @param {number} steps
* @param {number} arrLen
* @return {number}
*/
var numWays = function (steps, arrLen) {
const hash = new Map()
function dp(s, i) {
if (i < 0 || i >= arrLen || s < 0 || i > s) return 0
if (s === i) return 1
const str = s + '-' + i
if (hash.has(str)) return hash.get(str)
s--
let ans =
(dp(s, i) % 1000000007) +
(dp(s, i - 1) % 1000000007) +
(dp(s, i + 1) % 1000000007)
ans %= 1000000007
hash.set(str, ans)
return ans
}
return dp(steps, 0)
}
/**
* 679. 24 点游戏
* @param {number[]} nums
* @return {boolean}
*/
var judgePoint24 = function (nums) {
function dfs(arr) {
// 判断条件这里重点 与24比较小于1e-6为真
if (arr.length === 1) return Math.abs(arr[0] - 24) < 1e-6
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i === j) continue
const a = arr[i],
b = arr[j]
const temp = [a + b, a - b, a * b]
if (b) temp.push(a / b)
const arr_filter = arr.filter(
(item, index) => index !== i && index !== j
)
for (let k = 0; k < temp.length; k++) {
if (dfs([...arr_filter, temp[k]])) return true
}
}
}
return false
}
return dfs(nums)
}
/**
* 1420. 生成数组
* @param {number} n
* @param {number} m
* @param {number} k
* @return {number}
*/
var numOfArrays = function (n, m, k) {
const mod = 1000000007
const visited = new Map()
function dfs(n, i, k) {
if (n === 0 && k === 0) return 1
if (n < 0 || m - i < k || k < 0) return 0
if (visited.has(n + '-' + i + '-' + k))
return visited.get(n + '-' + i + '-' + k)
let res = 0
for (let j = 1; j <= m; j++) {
let str = ''
if (j > i) {
str = n - 1 + '-' + j + '-' + (k - 1)
if (!visited.has(str)) visited.set(str, dfs(n - 1, j, k - 1) % mod)
} else {
str = n - 1 + '-' + i + '-' + k
if (!visited.has(str)) visited.set(str, dfs(n - 1, i, k) % mod)
}
res += visited.get(str)
}
visited.set(n + '-' + i + '-' + k, res % mod)
return visited.get(n + '-' + i + '-' + k)
}
return dfs(n, 0, k)
}
<file_sep>/**
* 783.二叉搜索树节点最小距离(数组排序)
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDiffInBST = function (root) {
let arr = []
function dfs(root) {
if (!root) return
arr.push(root.val)
dfs(root.left)
dfs(root.right)
}
dfs(root)
arr.sort((a, b) => a - b)
let min = arr[arr.length - 1]
for (let i = 0, len = arr.length - 1; i < len; i++) {
min = Math.min(min, arr[i + 1] - arr[i])
}
return min
}
/**
* 783.二叉搜索树节点最小距离(中序遍历)
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDiffInBST = function (root) {
let prev = null,
min = Number.MAX_SAFE_INTEGER
function dfs(root) {
if (!root) return
dfs(root.left)
if (prev !== null) min = Math.min(min, root.val - prev)
prev = root.val
dfs(root.right)
}
dfs(root)
return min
}
/**
* 1137. 第 N 个泰波那契数
* @param {number} n
* @return {number}
*/
var tribonacci = function (n) {
let a = 0,
b = 1,
c = 1
if (n === 0) return a
if (n === 1 || n === 2) return b
for (let i = 3; i <= n; i++) {
let temp = a + b + c
a = b
b = c
c = temp
}
return c
}
/**
* 1342. 将数字变成 0 的操作次数
* @param {number} num
* @return {number}
*/
var numberOfSteps = function (num) {
if (num === 0) return 0
if (num % 2 === 0) return 1 + numberOfSteps(num / 2)
return 1 + numberOfSteps(num - 1)
}
/**
* 1387. 将整数按权重排序
* @param {number} lo
* @param {number} hi
* @param {number} k
* @return {number}
*/
var getKth = function (lo, hi, k) {
const hash = {}
function toOne(num) {
if (num === 1) return 0
if (!hash.hasOwnProperty(num)) {
hash[num] = 1 + (num % 2 === 0 ? toOne(num / 2) : toOne(3 * num + 1))
}
return hash[num]
}
const arr = []
let j = 0
for (let i = lo; i <= hi; i++) arr[j++] = i
arr.sort((a, b) => {
return toOne(a) - toOne(b) || a - b
})
return arr[k - 1]
}
/**
* 779. 第K个语法符号
* @param {number} N
* @param {number} K
* @return {number}
*/
var kthGrammar = function (N, K) {
if (N === 1) return '0'
const p = kthGrammar(N - 1, Math.ceil(K / 2))
if (K % 2 === 1) return p
return p === '0' ? '1' : '0'
}
/**
* 50. Pow(x, n)
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function (x, n) {
if (n === 0) return 1
if (n === 1) return x
const temp = n
n = Math.abs(n)
let ans = 1
if (n & (1 === 1)) ans *= x
const half = myPow(x, n >> 1)
ans *= half * half
return temp > 0 ? ans : ans <= 0 ? 0 : 1 / ans
}
/**
* 1250. 检查「好数组」
* @param {number[]} nums
* @return {boolean}
*/
var isGoodArray = function (nums) {
let ans = nums[0]
for (let i = 1, len = nums.length; i < len; i++) {
ans = gcd(ans, nums[i])
}
return ans === 1
}
function gcd(a, b) {
if (b === 0) return a
return gcd(b, a % b)
}
<file_sep>/**
* 704. 二分查找(二分法)
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function (nums, target) {
let left = 0,
right = nums.length - 1
while (left <= right) {
if (left === right) return nums[left] === target ? left : -1
let mid = Math.floor(left + (right - left) / 2)
if (nums[mid] === target) return mid
if (nums[mid] < target) {
left = mid + 1
} else {
right = mid - 1
}
}
return -1
}
/**
* 34. 在排序数组中查找元素的第一个和最后一个位置(二分查找)
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function (nums, target) {
let left = 0,
right = nums.length - 1
while (left <= right) {
if (left === right) return nums[left] === target ? [left, left] : [-1, -1]
let mid = left + Math.floor((right - left) / 2)
if (nums[mid] < target) {
left = mid + 1
} else if (nums[mid] === target) {
let temp1 = mid,
temp2 = mid
while (nums[temp1 - 1] === target) temp1--
while (nums[temp2 + 1] === target) temp2++
return [temp1, temp2]
} else {
right = mid - 1
}
}
return [-1, -1]
}
/**
* 69. x 的平方根(二分法)
* @param {number} x
* @return {number}
*/
var mySqrt = function (x) {
let left = 1,
right = x
while (left <= right) {
let mid = left + Math.floor((right - left) / 2)
if (mid * mid <= x && (mid + 1) * (mid + 1) > x) return mid
if (mid * mid > x) {
right = mid - 1
} else {
left = mid + 1
}
}
return 0
}
/**
* 74. 搜索二维矩阵(二分法)
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function (matrix, target) {
let left = 0,
right = matrix.length - 1
while (left <= right) {
if (left === right) {
let l = 0,
r = matrix[0].length - 1
while (l <= r) {
let mid = l + Math.floor((r - l) / 2)
if (matrix[left][mid] === target) return true
if (matrix[left][mid] > target) {
r = mid - 1
} else {
l = mid + 1
}
}
return false
}
let mid = left + Math.floor((right - left) / 2)
if (
matrix[mid][0] <= target &&
matrix[mid][matrix[0].length - 1] >= target
) {
left = right = mid
} else if (matrix[mid][0] > target) {
right = mid - 1
} else {
left = mid + 1
}
}
return false
}
/**
* 240. 搜索二维矩阵 II
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function (matrix, target) {
const h = matrix.length
if (!h) return false
const w = matrix[0].length
let i = h - 1,
j = 0
while (i >= 0 && j < w) {
if (matrix[i][j] === target) return true
if (matrix[i][j] < target) {
j++
} else {
i--
}
}
return false
}
/**
* 33. 搜索旋转排序数组
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function (nums, target) {
let l = 0,
r = nums.length - 1
while (l <= r) {
const m = l + ((r - l) >> 1)
if (nums[m] === target) return m
const temp =
(nums[0] < nums[m] && target >= nums[0] && target < nums[m]) ||
(nums[0] > nums[m] && (target < nums[m] || target >= nums[0]))
if (temp) {
r = m - 1
} else {
l = m + 1
}
}
return -1
}
/**
* 540. 有序数组中的单一元素
* @param {number[]} nums
* @return {number}
*/
var singleNonDuplicate = function (nums) {
let l = 0,
r = nums.length - 1
while (l <= r) {
let m = l + ((r - l) >> 1)
if (nums[m] !== nums[m + 1] && nums[m] !== nums[m - 1]) return nums[m]
if (nums[m] === nums[m - 1]) m = m - 1
const len_l = m - l,
len_r = r - m - 1
if (len_l % 2 === 0) {
l = m + 2
} else {
r = m - 1
}
}
}
/**
* 719. 找出第 k 小的距离对
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var smallestDistancePair = function (nums, k) {
nums.sort((a, b) => a - b)
let l = 0,
r = nums[nums.length - 1] - nums[0]
while (l < r) {
const m = (r + l) >> 1
let cnt = 0,
left = 0
for (let right = 0, len = nums.length; right < len; right++) {
while (nums[right] - nums[left] > m) left++
cnt += right - left
}
if (cnt >= k) {
r = m
} else {
l = m + 1
}
}
return l
}
<file_sep>/**
* 217. 存在重复元素
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function (nums) {
let obj = {}
for (let i = 0, len = nums.length; i < len; i++) {
if (obj.hasOwnProperty(nums[i])) {
return true
}
obj[nums[i]] = true
}
return false
}
/**
* 219. 存在重复元素Ⅱ
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var containsNearbyDuplicate = function (nums, k) {
let obj = {}
for (let i = 0, len = nums.length; i < len; i++) {
if (obj.hasOwnProperty(nums[i])) {
if (Math.abs(i - obj[nums[i]]) <= k) return true
}
obj[nums[i]] = i
}
return false
}
/**
* 220. 存在重复元素Ⅲ
* @param {number[]} nums
* @param {number} k
* @param {number} t
* @return {boolean}
*/
var containsNearbyAlmostDuplicate = function (nums, k, t) {
for (let i = 0, len = nums.length; i < len; i++) {
for (let j = i + 1; j < len; j++) {
if (j - i <= k && Math.abs(nums[i] - nums[j]) <= t) return true
}
}
return false
}
/**
* 525.连续数组(两层for)
* @param {number[]} nums
* @return {number}
*/
var findMaxLength = function (nums) {
let result = 0
for (let i = 0, len = nums.length; i < len; i++) {
let zero = 0,
one = 0
for (let j = i; j < len; j++) {
if (nums[j] === 0) {
zero++
} else {
one++
}
if (zero === one) {
result = Math.max(result, zero + one)
}
}
}
return result
}
/**
* 409. 最长回文串
* @param {string} s
* @return {number}
*/
var longestPalindrome = function (s) {
let obj = {}
for (let i = 0, len = s.length; i < len; i++) {
if (!obj.hasOwnProperty(s[i])) {
obj[s[i]] = 1
continue
}
obj[s[i]]++
}
let keys = Object.keys(obj),
count = 0,
res = 0
for (let i = 0, len = keys.length; i < len; i++) {
if (obj[keys[i]] % 2 === 0) {
res += obj[keys[i]]
continue
}
if (!count) {
res += obj[keys[i]]
count++
continue
}
res += obj[keys[i]] - 1
}
return res
}
/**
* 1. 两数之和(哈希表)
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = function (nums, target) {
let hash = {}
for (let i = 0, len = nums.length; i < len; i++) {
if (hash.hasOwnProperty(target - nums[i]))
return [hash[target - nums[i]], i]
hash[nums[i]] = i
}
}
/**
* 290. 单词规律
* @param {string} pattern
* @param {string} str
* @return {boolean}
*/
var wordPattern = function (pattern, str) {
const hashP = {},
hashS = {}
str = str.split(' ')
if (pattern.length !== str.length) return false
for (let i = 0, len = pattern.length; i < len; i++) {
const p = pattern[i],
s = str[i]
if (hashP.hasOwnProperty(p)) {
if (hashP[p] !== s) return false
} else {
if (hashS.hasOwnProperty(s)) return false
hashP[p] = s
hashS[s] = p
}
}
return true
}
/**
* 692. 前K个高频单词
* @param {string[]} words
* @param {number} k
* @return {string[]}
*/
var topKFrequent = function (words, k) {
const hash = {},
ans = []
for (let i = 0, len = words.length; i < len; i++) {
const cur = words[i]
if (hash.hasOwnProperty(cur)) {
hash[cur]++
} else {
hash[cur] = 1
ans.push(cur)
}
}
function compare(a, b) {
let i = 0,
j = 0
while (i < a.length && j < b.length && a[i] === b[j]) {
i++
j++
}
if (i === a.length) return -1
if (j === b.length) return 1
return a[i].charCodeAt() - b[j].charCodeAt()
}
ans.sort((a, b) => {
return hash[b] - hash[a] || compare(a, b)
})
return ans.slice(0, k)
}
/**
* 535. TinyURL 的加密与解密
*/
const hash = new Map()
let cnt = 1000000000
const str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
const x = new Map()
for (let i = 0; i < 62; i++) {
x.set(i, str[i])
}
const baseUrl = 'http://tyj.com/'
/**
* Encodes a URL to a shortened URL.
*
* @param {string} longUrl
* @return {string}
*/
var encode = function (longUrl) {
cnt++
let code = ''
let num = cnt
while (num) {
const temp = num % 62
code = x.get(temp) + code
num = Math.floor(num / 62)
}
hash.set(code, longUrl)
return baseUrl + code
}
/**
* Decodes a shortened URL to its original URL.
*
* @param {string} shortUrl
* @return {string}
*/
var decode = function (shortUrl) {
const n = baseUrl.length
const code = shortUrl.slice(n)
return hash.get(code)
}
/**
* Your functions will be called as such:
* decode(encode(url));
*/
/**
* 451. 根据字符出现频率排序
* @param {string} s
* @return {string}
*/
var frequencySort = function (s) {
const hash = {}
let cnt = 0
for (let i = 0, len = s.length; i < len; i++) {
if (hash.hasOwnProperty(s[i])) {
hash[s[i]]++
} else {
hash[s[i]] = 1
}
}
return [...s]
.sort(
(a, b) =>
hash[b] - hash[a] ||
(hash[a] === hash[b] && a.charCodeAt() - b.charCodeAt())
)
.join('')
}
/**
* 1267. 统计参与通信的服务器
* @param {number[][]} grid
* @return {number}
*/
var countServers = function (grid) {
let ans = 0
const hash = {}
for (let i = 0, h = grid.length; i < h; i++) {
for (let j = 0, w = grid[0].length; j < w; j++) {
if (grid[i][j] === 0) continue
if (hash.hasOwnProperty('y' + i)) {
hash['y' + i]++
} else {
hash['y' + i] = 1
}
if (hash.hasOwnProperty('x' + j)) {
hash['x' + j]++
} else {
hash['x' + j] = 1
}
}
}
for (let i = 0, h = grid.length; i < h; i++) {
for (let j = 0, w = grid[0].length; j < w; j++) {
if (grid[i][j] === 0) continue
if (
(hash.hasOwnProperty('y' + i) && hash['y' + i] > 1) ||
(hash.hasOwnProperty('x' + j) && hash['x' + j] > 1)
) {
ans++
}
}
}
return ans
}
/**
* 888. 公平的糖果交换
* @param {number[]} A
* @param {number[]} B
* @return {number[]}
*/
var fairCandySwap = function (A, B) {
const hash = new Map()
let sumA = 0,
sumB = 0
for (let i = 0, len = A.length; i < len; i++) sumA += A[i]
for (let i = 0, len = B.length; i < len; i++) {
sumB += B[i]
if (!hash.has(B[i])) hash.set(B[i], 1)
}
const dif = (sumB - sumA) >> 1
for (let i = 0, len = A.length; i < len; i++)
if (hash.has(A[i] + dif)) return [A[i], A[i] + dif]
}
<file_sep>/**
* 41. 缺失的第一个正数(桶排序+抽屉原理)
* @param {number[]} nums
* @return {number}
*/
var firstMissingPositive = function(nums) {
for (let i = 0, len = nums.length; i < len; i++) {
let cur = nums[i]
while (cur <= len && cur - 1 !== i && cur > 0 && nums[cur - 1] !== cur) {
;[nums[i], nums[cur - 1]] = [nums[cur - 1], nums[i]]
cur = nums[i]
}
}
for (let i = 0, len = nums.length; i < len; i++) {
if (i !== nums[i] - 1) return i + 1
}
return nums.length + 1
}
/**
* 448. 找到所有数组中消失的数字(桶排序)
* @param {number[]} nums
* @return {number[]}
*/
var findDisappearedNumbers = function(nums) {
let res = []
for (let i = 0, len = nums.length; i < len; i++) {
let cur = nums[i]
while (cur !== i + 1 && nums[cur - 1] !== cur) {
;[nums[cur - 1], nums[i]] = [nums[i], nums[cur - 1]]
cur = nums[i]
}
}
for (let i = 0, len = nums.length; i < len; i++) {
if (nums[i] !== i + 1) res.push(i + 1)
}
return res
}
/**
* 442. 数组中重复的数据(桶排序)
* @param {number[]} nums
* @return {number[]}
*/
var findDuplicates = function(nums) {
let res = []
for (let i = 0, len = nums.length; i < len; i++) {
let cur = nums[i]
while (cur !== i + 1 && nums[cur - 1] !== cur) {
;[nums[cur - 1], nums[i]] = [nums[i], nums[cur - 1]]
cur = nums[i]
}
}
for (let i = 0, len = nums.length; i < len; i++) {
if (nums[i] !== i + 1) res.push(nums[i])
}
return res
}
/**
* 面试题03. 数组中重复的数字(桶排序)
* @param {number[]} nums
* @return {number}
*/
var findRepeatNumber = function(nums) {
for (let i = 0, len = nums.length; i < len; i++) {
let cur = nums[i]
while (cur !== i && nums[cur] !== cur) {
;[nums[i], nums[cur]] = [nums[cur], nums[i]]
cur = nums[i]
}
}
for (let i = 0, len = nums.length; i < len; i++) {
if (i !== nums[i]) return nums[i]
}
return null
}
<file_sep>/**
* 125.验证回文串(栈)
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
s = s.replace(
/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?]/g,
''
)
let arr = [],
mid1 = Math.ceil(s.length / 2),
mid2 = Math.floor(s.length / 2)
for (let i = 0; i < mid1; i++) {
arr.push(s[i])
}
for (let i = mid2, len = s.length; i < len; i++) {
if (arr[arr.length - 1].toLocaleLowerCase() !== s[i].toLocaleLowerCase())
return false
arr.pop()
}
return true
}
/**
* 125.验证回文串(双指针)
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
s = s.replace(
/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?]/g,
''
)
for (let i = 0, len = s.length; i < len; i++) {
if (i <= len - i - 1) {
if (s[i].toLocaleLowerCase() !== s[len - i - 1].toLocaleLowerCase())
return false
} else {
break
}
}
return true
}
/**
* 394. 字符串解码(栈)
* @param {string} s
* @return {string}
*/
var decodeString = function (s) {
let stack = []
for (let i = 0, len = s.length; i < len; i++) {
if (s[i] !== ']') {
stack.push(s[i])
} else {
let j = stack.length - 1,
n = '',
str = '',
reg = /[0-9]/
while (stack[j] !== '[') {
str = stack.pop() + str
j--
}
stack.pop()
j--
while (j >= 0 && reg.test(stack[j])) {
n = stack.pop() + n
j--
}
let temp = ''
for (let i = 0; i < +n; i++) {
temp += str
}
stack.push(...temp)
}
}
return stack.join('')
}
/**
* 862. 和至少为 K 的最短子数组
* @param {number[]} A
* @param {number} K
* @return {number}
*/
var shortestSubarray = function (A, K) {
const N = A.length
const pre = new Array(N + 1)
pre[0] = 0
for (let i = 0; i < N; i++) pre[i + 1] = pre[i] + A[i]
const deque = []
let ans = N + 1
for (let i = 0; i <= N; i++) {
while (deque.length && pre[deque[deque.length - 1]] >= pre[i]) deque.pop()
while (deque.length && pre[i] - pre[deque[0]] >= K) {
ans = Math.min(ans, i - deque[0])
deque.shift()
}
deque.push(i)
}
return ans > N ? -1 : ans
}
/**
* 921. 使括号有效的最少添加
* @param {string} S
* @return {number}
*/
var minAddToMakeValid = function (S) {
const stack = []
for (let i = 0, len = S.length; i < len; i++) {
if (stack[stack.length - 1] === '(' && S[i] === ')') {
stack.pop()
} else {
stack.push(S[i])
}
}
return stack.length
}
/**
* 1249. 移除无效的括号
* @param {string} s
* @return {string}
*/
var minRemoveToMakeValid = function (s) {
let ans = ''
const stack = []
let l = 0,
r = 0
for (let i = 0, len = s.length; i < len; i++) {
if (s[i] === '(') {
l++
} else if (s[i] === ')') {
if (l === r) continue
r++
}
stack.push(s[i])
}
l = 0
r = 0
for (let i = stack.length - 1; i >= 0; i--) {
if (stack[i] === ')') {
r++
} else if (stack[i] === '(') {
if (l === r) continue
l++
}
ans += stack[i]
}
return [...ans].reverse().join('')
}
/**
* 155. 最小栈
* initialize your data structure here.
*/
var MinStack = function () {
this.stack = []
this.minStack = []
}
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function (x) {
this.stack.push(x)
if (!this.minStack.length || this.minStack[this.minStack.length - 1] >= x)
this.minStack.push(x)
}
/**
* @return {void}
*/
MinStack.prototype.pop = function () {
const temp = this.stack.pop()
if (this.minStack[this.minStack.length - 1] === temp) this.minStack.pop()
}
/**
* @return {number}
*/
MinStack.prototype.top = function () {
return this.stack[this.stack.length - 1]
}
/**
* @return {number}
*/
MinStack.prototype.getMin = function () {
return this.minStack[this.minStack.length - 1]
}
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/
/**
* 316. 去除重复字母(单调栈)
* @param {string} s
* @return {string}
*/
var removeDuplicateLetters = function (s) {
const visited = new Map()
const stack = []
const cnts = new Array(26)
cnts.fill(0)
for (let i = 0, len = s.length; i < len; i++) {
cnts[s[i].charCodeAt() - 97]++
}
for (let i = 0, len = s.length; i < len; i++) {
while (
stack.length &&
!visited.has(s[i]) &&
stack[stack.length - 1].charCodeAt() > s[i].charCodeAt() &&
cnts[stack[stack.length - 1].charCodeAt() - 97] > 0
) {
const temp = stack.pop()
visited.delete(temp)
}
cnts[s[i].charCodeAt() - 97]--
if (!visited.has(s[i])) {
stack.push(s[i])
visited.set(s[i], true)
}
}
return stack.join('')
}
<file_sep>/**
* 56. 合并区间(排序)
* @param {number[][]} intervals
* @return {number[][]}
*/
var merge = function(intervals) {
let res = [],
len = intervals.length,
temp
if (len < 2) return intervals
intervals.sort((a, b) => a[0] - b[0])
temp = intervals[0]
for (let i = 1; i < len; i++) {
let cur = intervals[i]
if (cur[0] > temp[1]) {
res.push(temp)
temp = cur
} else {
temp[0] = Math.min(temp[0], cur[0])
temp[1] = Math.max(temp[1], cur[1])
}
}
res.push(temp)
return res
}
let arr = [2, 6, 3, 1, 5, 7, 10, 9, 8]
function test(arr) {
for (let i = 0, len = arr.length; i < len; i++) {
let cur = arr[i]
if (cur - 1 !== i) {
;[arr[i], arr[cur - 1]] = [arr[cur - 1], arr[i]]
}
}
return arr
}
<file_sep>/**
* 208.实现Trie(前缀树)
* Initialize your data structure here.
*/
var Trie = function () {
this.root = {}
}
/**
* Inserts a word into the trie.
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function (word) {
function insertOne(word, node) {
if (!word.length) return
let letter = word[0]
if (!node.hasOwnProperty(letter))
node[letter] = { isEnd: word.length === 1 }
if (word.length === 1) node[letter].isEnd = true
insertOne(word.slice(1), node[letter])
}
insertOne(word, this.root)
}
/**
* Returns if the word is in the trie.
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function (word) {
function search(word, node) {
let letter = word[0]
if (!node.hasOwnProperty(letter)) return false
if (word.length === 1) return node[letter].isEnd
return search(word.slice(1), node[letter])
}
return search(word, this.root)
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function (prefix) {
function startsWith(word, node) {
if (!word.length) return true
let letter = word[0]
if (!node.hasOwnProperty(letter)) return false
return startsWith(word.slice(1), node[letter])
}
return startsWith(prefix, this.root)
}
/**
* 211. 添加与搜索单词 - 数据结构设计
* Initialize your data structure here.
*/
var WordDictionary = function () {
this.root = {}
}
/**
* Adds a word into the data structure.
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.addWord = function (word) {
function insert(word, root) {
if (!word.length) return
let letter = word[0]
if (!root.hasOwnProperty(letter))
root[letter] = { isEnd: word.length === 1 }
if (word.length === 1) {
root[letter].isEnd = true
return
}
return insert(word.slice(1), root[letter])
}
insert(word, this.root)
}
/**
* Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.search = function (word) {
function search(word, root) {
if (!word.length) return false
let letter = word[0]
if (letter === '.') {
let arr = Object.keys(root).filter((x) => x !== 'isEnd')
let result = false
for (let i = 0, len = arr.length; i < len; i++) {
if (word.length === 1) {
if (root[arr[i]].isEnd) return true
} else {
result = search(word.slice(1), root[arr[i]])
if (result) break
}
}
return result
}
if (!root.hasOwnProperty(letter)) return false
if (word.length === 1 && root[letter].isEnd) return true
return search(word.slice(1), root[letter])
}
return search(word, this.root)
}
/**
* 1032. 字符流
* Your WordDictionary object will be instantiated and called as such:
* var obj = new WordDictionary()
* obj.addWord(word)
* var param_2 = obj.search(word)
*/
/**
* @param {string[]} words
*/
var StreamChecker = function (words) {
this.tree = new Map()
this.visited = []
for (let i = 0, len = words.length; i < len; i++) {
let node = this.tree
const cur = words[i]
let j = cur.length - 1
while (j >= 0) {
if (!node.has(cur[j])) node.set(cur[j], new Map())
node = node.get(cur[j])
node.set('isEnd', j === 0 || node.get('isEnd'))
j--
}
}
}
/**
* @param {character} letter
* @return {boolean}
*/
StreamChecker.prototype.query = function (letter) {
this.visited.push(letter)
let node = this.tree
for (let i = this.visited.length - 1; i >= 0; i--) {
if (!node.has(this.visited[i])) return false
node = node.get(this.visited[i])
if (node.get('isEnd')) return true
}
return false
}
/**
* Your StreamChecker object will be instantiated and called as such:
* var obj = new StreamChecker(words)
* var param_1 = obj.query(letter)
*/
<file_sep>/**
* 581.最短无序连续子数组
* @param {number[]} nums
* @return {number}
*/
var findUnsortedSubarray = function (nums) {
let arr = [...nums].sort((a, b) => a - b)
let start = nums.length,
end = 0,
count = 0
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== arr[i]) {
start = Math.min(start, i)
end = Math.max(end, i)
} else {
count++
}
}
return count === nums.length ? 0 : end - start + 1
}
/**
* 914.卡牌分组
* @param {number[]} deck
* @return {boolean}
*/
var hasGroupsSizeX = function (deck) {
if (!deck.length) return false
function gcd(a, b) {
if (a % b === 0) return b
return gcd(b, a % b)
}
deck.sort((a, b) => a - b)
let arr = [],
count = 0
for (let i = 0, len = deck.length; i < len; i++) {
if (deck[i] === deck[i + 1]) {
count++
} else {
count++
arr.push(count)
count = 0
}
}
if (Math.min(...arr) === 1) return false
for (let i = 0, len = arr.length - 1; i < len; i++) {
if (gcd(arr[i], arr[i + 1]) <= 1) {
return false
}
}
return true
}
/**
* 941.有效的山脉数组
* @param {number[]} A
* @return {boolean}
*/
var validMountainArray = function (A) {
const len = A.length
let i = 0
while (i < len - 1 && A[i] < A[i + 1]) {
i++
}
if (i === 0 || i === len - 1) return false
while (i < len - 1 && A[i] > A[i + 1]) {
i++
}
return i === len - 1
}
/**
* 414.第三大的数
* @param {number[]} nums
* @return {number}
*/
var thirdMax = function (nums) {
let arr = [...new Set(nums)].sort((a, b) => a - b)
if (arr.length < 3) return Math.max(...arr)
return arr[arr.length - 3]
}
/**
* 766. 托普利茨矩阵
* @param {number[][]} matrix
* @return {boolean}
*/
var isToeplitzMatrix = function (matrix) {
const hash = {}
for (let i = 0, h = matrix.length; i < h; i++) {
for (let j = 0, w = matrix[0].length; j < w; j++) {
if (i === 0 || j === 0) continue
if (matrix[i][j] !== matrix[i - 1][j - 1]) return false
}
}
return true
}
/**
* 845. 数组中的最长山脉
* @param {number[]} A
* @return {number}
*/
var longestMountain = function (A) {
const len = A.length
let ans = 0
let i = 0
while (i < len - 1) {
while (i < len - 1 && A[i] >= A[i + 1]) i++
let x = i
while (i < len - 1 && A[i] <= A[i + 1]) {
if (A[i] === A[i + 1]) x = i + 1
i++
}
let y = i
while (i < len - 1 && A[i] > A[i + 1]) i++
if (i > y && y > x) {
ans = Math.max(ans, i - x + 1)
}
}
return ans
}
/**
* 846. 一手顺子
* @param {number[]} hand
* @param {number} W
* @return {boolean}
*/
var isNStraightHand = function (hand, W) {
const hash = {}
for (let i = 0, len = hand.length; i < len; i++) {
if (hash.hasOwnProperty(hand[i])) {
hash[hand[i]]++
} else {
hash[hand[i]] = 1
}
}
hand.sort((a, b) => a - b)
for (let i = 0, len = hand.length; i < len; i++) {
let cur = hand[i]
if (hash[cur] <= 0) continue
hash[cur]--
let cnt = W - 1
while (cnt) {
if (!hash[cur + W - cnt] || hash[cur + W - cnt] <= 0) return false
hash[cur + W - cnt]--
cnt--
}
}
return true
}
/**
* 119. 杨辉三角 II
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function (rowIndex) {
if (rowIndex === 0) return [1]
let prev = [1, 1]
for (let i = 1; i < rowIndex; i++) {
let temp = [1]
for (let i = 0, len = prev.length; i < len - 1; i++) {
temp.push(prev[i] + prev[i + 1])
}
temp.push(1)
prev = temp
}
return prev
}
/**
* 1170. 比较字符串最小字母出现频次
* @param {string[]} queries
* @param {string[]} words
* @return {number[]}
*/
var numSmallerByFrequency = function (queries, words) {
const ans = new Array(queries.length)
ans.fill(0)
function getNums(str) {
const arr = new Array(26)
arr.fill(0)
for (let i = 0, len = str.length; i < len; i++) {
arr[str[i].charCodeAt() - 97]++
}
for (let i = 0; i < 26; i++) if (arr[i]) return arr[i]
}
const counts = []
for (let i = 0, len = words.length; i < len; i++) {
counts.push(getNums(words[i]))
}
counts.sort((a, b) => a - b)
for (let i = 0, len = queries.length; i < len; i++) {
const cur = getNums(queries[i])
let j = 0
while (cur >= counts[j]) j++
ans[i] = counts.length - j
}
return ans
}
/**
* 1422. 分割字符串的最大得分
* @param {string} s
* @return {number}
*/
var maxScore = function (s) {
const len = s.length
const prev = new Array(len + 1)
const post = new Array(len + 1)
prev[0] = 0
post[len] = 0
for (let i = 0; i < len; i++) {
prev[i + 1] = prev[i]
if (s[i] === '0') prev[i + 1]++
post[len - i - 1] = post[len - i]
if (s[len - i - 1] === '1') post[len - i - 1]++
}
let ans = 0
for (let i = 1; i < len; i++) ans = Math.max(ans, prev[i] + post[i])
return ans
}
/**
* 1013. 将数组分成和相等的三个部分
* @param {number[]} A
* @return {boolean}
*/
var canThreePartsEqualSum = function (A) {
let sum = 0
for (let i = 0, len = A.length; i < len; i++) sum += A[i]
if (sum % 3 !== 0) return false
const third = sum / 3
let cnt = 0
let temp = 0
for (let i = 0, len = A.length; i < len; i++) {
temp += A[i]
if (temp === third) {
cnt++
temp = 0
}
if (cnt === 2 && i < len - 1) return true
}
return false
}
/**
* 59. 螺旋矩阵 II
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function (n) {
const ans = new Array(n)
for (let i = 0; i < n; i++) ans[i] = new Array(n)
let cnt = 1
let t = 0,
b = n - 1,
l = 0,
r = n - 1
while (true) {
for (let i = l; i <= r; i++) ans[t][i] = cnt++
if (++t > b) break
for (let i = t; i <= b; i++) ans[i][r] = cnt++
if (--r < l) break
for (let i = r; i >= l; i--) ans[b][i] = cnt++
if (--b < t) break
for (let i = b; i >= t; i--) ans[i][l] = cnt++
if (++l > r) break
}
return ans
}
/**
* 189. 旋转数组
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function (nums, k) {
k %= nums.length
function reverse(l, r) {
while (l < r) {
;[nums[l], nums[r]] = [nums[r], nums[l]]
l++
r--
}
}
reverse(0, nums.length - 1)
reverse(0, k - 1)
reverse(k, nums.length - 1)
}
/**
* 1103. 分糖果 II
* @param {number} candies
* @param {number} num_people
* @return {number[]}
*/
var distributeCandies = function (candies, num_people) {
const ans = new Array(num_people)
ans.fill(0)
for (let i = 0; ; ) {
ans[i++ % num_people] += i > candies ? candies : i
candies -= i
if (candies <= 0) break
}
return ans
}
/**
* 1131. 绝对值表达式的最大值
* @param {number[]} arr1
* @param {number[]} arr2
* @return {number}
*/
var maxAbsValExpr = function (arr1, arr2) {
let a1 = Number.MIN_SAFE_INTEGER,
a2 = Number.MAX_SAFE_INTEGER
let b1 = Number.MIN_SAFE_INTEGER,
b2 = Number.MAX_SAFE_INTEGER
let c1 = Number.MIN_SAFE_INTEGER,
c2 = Number.MAX_SAFE_INTEGER
let d1 = Number.MIN_SAFE_INTEGER,
d2 = Number.MAX_SAFE_INTEGER
for (let i = 0, len = arr1.length; i < len; i++) {
a1 = Math.max(a1, arr1[i] + arr2[i] + i)
b1 = Math.max(b1, arr1[i] + arr2[i] - i)
c1 = Math.max(c1, arr1[i] - arr2[i] + i)
d1 = Math.max(d1, arr1[i] - arr2[i] - i)
a2 = Math.min(a2, arr1[i] + arr2[i] + i)
b2 = Math.min(b2, arr1[i] + arr2[i] - i)
c2 = Math.min(c2, arr1[i] - arr2[i] + i)
d2 = Math.min(d2, arr1[i] - arr2[i] - i)
}
return Math.max(a1 - a2, b1 - b2, c1 - c2, d1 - d2)
}
<file_sep>/**
* 140. 单词拆分 II(暴力解)
* @param {string} s
* @param {string[]} wordDict
* @return {string[]}
*/
var wordBreak = function (s, wordDict) {
let res = [],
len = s.length
function dp(i, j, str) {
if (j === len && i === len) {
res.push(str)
return
}
for (let n = j; n < len; n++) {
let temp = s.slice(i, n + 1)
if (wordDict.indexOf(temp) !== -1) {
dp(n + 1, n + 1, str + (str === '' ? '' : ' ') + temp)
dp(i, n + 1, str)
return
}
}
}
dp(0, 0, '')
return res
}
/**
* 139. 单词拆分(动态规划)
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function (s, wordDict) {
const len = s.length
const dp = new Array(len + 1)
dp.fill(false)
dp[0] = true
for (let i = 1; i <= len; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && wordDict.indexOf(s.slice(j, i)) !== -1) dp[i] = true
}
}
return dp[len]
}
/**
* 44. 通配符匹配(暴力解)
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function (s, p) {
function dp(i, j) {
if (i < 0 && j < 0) return true
if (j < 0) return false
if (i < 0) {
while (j >= 0) {
if (p[j] !== '*') return false
j--
}
return true
}
const charS = s[i],
charP = p[j]
if (charS === charP || charP === '?') {
return dp(i - 1, j - 1)
} else if (charP === '*') {
let res = false
for (let n = -1; n <= i; n++) {
res = res || dp(n, j - 1)
}
return res
} else {
return false
}
}
return dp(s.length - 1, p.length - 1)
}
/**
* 98. 验证二叉搜索树(中序遍历)
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function (root) {
let compare = Number.MIN_SAFE_INTEGER,
res = true
function mfs(node) {
if (!node) return
mfs(node.left)
if (compare >= node.val) res = false
compare = node.val
mfs(node.right)
}
mfs(root)
return res
}
/**
* 20. 有效的括号(栈)
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
const hash = { ')': '(', '}': '{', ']': '[' }
let stack = []
for (let i = 0, len = s.length; i < len; i++) {
if (hash.hasOwnProperty(s[i]) && stack[stack.length - 1] === hash[s[i]]) {
stack.pop()
} else {
stack.push(s[i])
}
}
return stack.length === 0
}
/**
* 125. 验证回文串
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
let res = ''
for (let i = 0, len = s.length; i < len; i++) {
let cur = s[i]
if (cur.charCodeAt() >= 65 && cur.charCodeAt() <= 90)
res += cur.toLocaleLowerCase()
if (cur.charCodeAt() >= 97 && cur.charCodeAt() <= 122) res += cur
if (!isNaN(cur) && cur !== ' ') res += cur
}
for (
let i = 0, len = Math.floor(res.length / 2), l = res.length;
i < len;
i++
) {
if (res[i] !== res[l - i - 1]) return false
}
return true
}
/**
* 242. 有效的字母异位词(hash表)
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
let hashS = {}
for (let i = 0, len = s.length; i < len; i++) {
if (!hashS.hasOwnProperty(s[i])) {
hashS[s[i]] = 1
} else {
hashS[s[i]]++
}
}
let count = 0,
hashT = {}
for (let i = 0, len = t.length; i < len; i++) {
if (!hashT.hasOwnProperty(t[i])) {
hashT[t[i]] = 1
} else {
hashT[t[i]]++
}
if (hashS[t[i]] === hashT[t[i]]) count++
}
return s.length === t.length && count === Object.keys(hashS).length
}
/**
* 242. 有效的字母异位词(排序)
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
s = s
.split('')
.sort((a, b) => a.charCodeAt() - b.charCodeAt())
.join('')
t = t
.split('')
.sort((a, b) => a.charCodeAt() - b.charCodeAt())
.join('')
return s === t
}
/**
* 1. 两数之和(hash表)
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = function (nums, target) {
const hash = {}
for (let i = 0, len = nums.length; i < len; i++) {
if (hash.hasOwnProperty(target - nums[i]))
return [hash[target - nums[i]], i]
hash[nums[i]] = i
}
}
/**
* 42. 接雨水(单调栈)
* @param {number[]} height
* @return {number}
*/
var trap = function (height) {
let res = 0,
stack = []
for (let i = 0, len = height.length; i < len; i++) {
while (stack.length > 0 && height[i] > height[stack[stack.length - 1]]) {
let h = height[stack.pop()]
if (stack.length !== 0) {
let w = i - stack[stack.length - 1] - 1
res += (Math.min(height[stack[stack.length - 1]], height[i]) - h) * w
}
}
stack.push(i)
}
return res
}
/**
* 84. 柱状图中最大的矩形(单调栈)
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function (heights) {
let stack = [],
res = 0
heights.push(0)
heights.unshift(0)
for (let i = 0, len = heights.length; i < len; i++) {
while (stack.length > 0 && heights[stack[stack.length - 1]] > heights[i]) {
let temp = stack.pop()
res = Math.max(res, (i - stack[stack.length - 1] - 1) * heights[temp])
}
stack.push(i)
}
return res
}
/**
* 456. 132模式(单调栈)
* @param {number[]} nums
* @return {boolean}
*/
var find132pattern = function (nums) {
let sec = Number.MIN_SAFE_INTEGER
const stack = []
for (let i = nums.length - 1; i >= 0; i--) {
if (nums[i] < sec) return true
while (stack.length > 0 && nums[i] > stack[stack.length - 1]) {
sec = stack.pop()
}
stack.push(nums[i])
}
return false
}
/**
* 101. 对称二叉树
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function (root) {
if (!root) return true
function isSym(node1, node2) {
if (!node1 && !node2) return true
if (!node1 || !node2) return false
if (node1.val !== node2.val) return false
return isSym(node1.left, node2.right) && isSym(node1.right, node2.left)
}
return isSym(root.left, root.right)
}
/**
* 130. 被围绕的区域(dfs)
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solve = function (board) {
if (!board || !board.length) return
const h = board.length,
w = board[0].length
for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
if (
(i === 0 || i === h - 1 || j === 0 || j === w - 1) &&
board[i][j] === 'O'
) {
dfs(i, j)
}
}
}
function dfs(i, j) {
if (
i < 0 ||
i >= h ||
j < 0 ||
j >= w ||
board[i][j] === 'X' ||
board[i][j] === '#'
)
return
board[i][j] = '#'
dfs(i - 1, j)
dfs(i + 1, j)
dfs(i, j - 1)
dfs(i, j + 1)
}
for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
if (board[i][j] === 'O') board[i][j] = 'X'
if (board[i][j] === '#') board[i][j] = 'O'
}
}
}
/**
* 130. 被围绕的区域(非递归dfs)
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solve = function (board) {
if (!board || !board.length) return
const h = board.length,
w = board[0].length
for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
if (
(i === 0 || i === h - 1 || j === 0 || j === w - 1) &&
board[i][j] === 'O'
) {
dfs(i, j)
}
}
}
function dfs(i, j) {
const stack = []
stack.push({ i, j })
board[i][j] = '#'
while (stack.length) {
let cur = stack[stack.length - 1]
if (cur.i - 1 >= 0 && board[cur.i - 1][cur.j] === 'O') {
board[cur.i - 1][cur.j] = '#'
stack.push({ i: cur.i - 1, j: cur.j })
continue
}
if (cur.i + 1 < h && board[cur.i + 1][cur.j] === 'O') {
board[cur.i + 1][cur.j] = '#'
stack.push({ i: cur.i + 1, j: cur.j })
continue
}
if (cur.j - 1 >= 0 && board[cur.i][cur.j - 1] === 'O') {
board[cur.i][cur.j - 1] = '#'
stack.push({ i: cur.i, j: cur.j - 1 })
continue
}
if (cur.j - 1 < w && board[cur.i][cur.j + 1] === 'O') {
board[cur.i][cur.j + 1] = '#'
stack.push({ i: cur.i, j: cur.j + 1 })
continue
}
stack.pop()
}
}
for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
if (board[i][j] === 'O') board[i][j] = 'X'
if (board[i][j] === '#') board[i][j] = 'O'
}
}
}
/**
* 371. 两整数之和(位运算)
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function (a, b) {
while (b !== 0) {
let temp = a ^ b
b = (a & b) << 1
a = temp
}
return a
}
/**
* 79. 单词搜索(dfs)
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function (board, word) {
const len = word.length,
h = board.length,
w = board[0].length
for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
if (board[i][j] === word[0]) {
if (dfs(i, j, 1, [i + ',' + j])) return true
}
}
}
function dfs(i, j, k, used) {
if (k === len) return true
let res = false
if (
i - 1 >= 0 &&
board[i - 1][j] === word[k] &&
used.indexOf(i - 1 + ',' + j) === -1
) {
res = res || dfs(i - 1, j, k + 1, used.concat([i - 1 + ',' + j]))
}
if (
i + 1 < h &&
board[i + 1][j] === word[k] &&
used.indexOf(i + 1 + ',' + j) === -1
) {
res = res || dfs(i + 1, j, k + 1, used.concat([i + 1 + ',' + j]))
}
if (
j - 1 >= 0 &&
board[i][j - 1] === word[k] &&
used.indexOf(i + ',' + (j - 1)) === -1
) {
res = res || dfs(i, j - 1, k + 1, used.concat([i + ',' + (j - 1)]))
}
if (
j + 1 < w &&
board[i][j + 1] === word[k] &&
used.indexOf(i + ',' + (j + 1)) === -1
) {
res = res || dfs(i, j + 1, k + 1, used.concat([i + ',' + (j + 1)]))
}
return res
}
return false
}
/**
* 78. 子集(回溯法)
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function (nums) {
const res = [],
len = nums.length
function backtrack(has, i) {
res.push(has)
for (let n = i; n < len; n++) {
backtrack([...has, nums[n]], n + 1)
}
}
backtrack([], 0)
return res
}
/**
* 8. 字符串转换整数 (atoi)
* @param {string} str
* @return {number}
*/
var myAtoi = function (str) {
let i = 0,
len = str.length,
res = ''
while (str[i] === ' ') i++
if (str[i] === '-' || str[i] === '+') res += str[i++]
while (!Number.isNaN(+str[i]) && str[i] !== ' ' && i < len) res += str[i++]
if (Number.isNaN(+res)) return 0
if (+res < -Math.pow(2, 31)) return -Math.pow(2, 31)
if (+res > Math.pow(2, 31) - 1) return Math.pow(2, 31) - 1
return +res
}
/**
* 69. x 的平方根
* @param {number} x
* @return {number}
*/
var mySqrt = function (x) {
if (x === 0) return 0
for (let i = 1; i <= x; i++) {
if (i * i === x || (i * i < x && (i + 1) * (i + 1) > x)) return i
}
}
/**
* 54. 螺旋矩阵(定义边界)
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
if (!matrix.length) return []
let l = 0,
r = matrix[0].length - 1,
t = 0,
b = matrix.length - 1
const res = []
while (true) {
for (let n = l; n <= r; n++) res.push(matrix[t][n])
if (++t > b) break
for (let n = t; n <= b; n++) res.push(matrix[n][r])
if (--r < l) break
for (let n = r; n >= l; n--) res.push(matrix[b][n])
if (--b < t) break
for (let n = b; n >= t; n--) res.push(matrix[n][l])
if (++l > r) break
}
return res
}
/**
* 148. 排序链表(归并排序)
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function (head) {
let p = head,
len = 0
while (head) {
len++
head = head.next
}
const dummy = new ListNode(null)
let t = dummy,
step = 1
while (step <= len) {
while (p) {
let l = p,
r = cut(l, step)
p = cut(r, step)
t.next = merge(l, r)
while (t.next) t = t.next
}
step <<= 1
p = dummy.next
t = dummy
}
return dummy.next
function cut(node, step) {
if (step === 0 || !node) return node
while (step > 1 && node.next) {
node = node.next
step--
}
const temp = node.next
node.next = null
return temp
}
function merge(l1, l2) {
if (!l1 || !l2) return l1 ? l1 : l2
let p = new ListNode(null),
dummy = p
while (l1 && l2) {
if (l1.val < l2.val) {
p.next = l1
p = l1
l1 = l1.next
} else {
p.next = l2
p = l2
l2 = l2.next
}
}
p.next = l1 ? l1 : l2
return dummy.next
}
}
/**
* 239. 滑动窗口最大值(队列)
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var maxSlidingWindow = function (nums, k) {
const queue = [],
res = [],
len = nums.length
let l = 0,
r = 0
while (r < len) {
while (queue.length > 0 && nums[queue[queue.length - 1]] < nums[r]) {
queue.pop()
}
queue.push(r)
if (r - l + 1 === k) {
res.push(nums[queue[0]])
l++
if (queue[0] < l) queue.shift()
}
r++
}
return res
}
/**
* 136. 只出现一次的数字(异或)
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function (nums) {
let res = 0
for (let i = 0, len = nums.length; i < len; i++) res ^= nums[i]
return res
}
/**
* 73. 矩阵置零(dfs)
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function (matrix) {
const h = matrix.length,
w = matrix[0].length
function dfs(i, j, dir) {
if (i < 0 || i >= h || j < 0 || j >= w || matrix[i][j] === 0) return
matrix[i][j] = '#'
if (dir === 'l') return dfs(i, j - 1, 'l')
if (dir === 'r') return dfs(i, j + 1, 'r')
if (dir === 'u') return dfs(i - 1, j, 'u')
if (dir === 'd') return dfs(i + 1, j, 'd')
}
for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
if (matrix[i][j] === 0) {
matrix[i][j] = '#'
dfs(i - 1, j, 'u')
dfs(i + 1, j, 'd')
dfs(i, j - 1, 'l')
dfs(i, j + 1, 'r')
}
}
}
for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
if (matrix[i][j] === '#') {
matrix[i][j] = '0'
}
}
}
}
/**
* 344. 反转字符串(双指针)
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseString = function (s) {
for (let i = 0, len = s.length; i < Math.floor(len / 2); i++) {
;[s[i], s[len - i - 1]] = [s[len - i - 1], s[i]]
}
}
/**
* 206. 反转链表(递归)
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
function reverse(prev, l) {
if (!l) return prev
const temp = l.next
l.next = prev
return reverse(l, temp)
}
return reverse(null, head)
}
/**
* 116. 填充每个节点的下一个右侧节点指针
* @param {Node} root
* @return {Node}
*/
var connect = function (root) {
function point(l, r) {
if (!l && !r) return
l.next = r
point(l.left, l.right)
if (r) {
point(l.right, r.left)
point(r.left, r.right)
point(r.right, null)
} else {
point(l.right, null)
}
}
point(root, null)
return root
}
/**
* 50. Pow(x, n)
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function (x, n) {
if (x === 0) return 0
if (n === 0) return 1
if (n === 1) return x
let absN = Math.abs(n),
halfN = Math.floor(absN / 2)
let halfRes = myPow(x, halfN)
let res = absN % 2 === 0 ? halfRes * halfRes : halfRes * halfRes * x
return n > 0 ? res : 1 / res
}
/**
* 307. 区域和检索 - 数组可修改(线段树)
* @param {number[]} nums
*/
var NumArray = function (nums) {
let len = nums.length
this.tree = new Array(len * 2)
for (let i = 0; i < len; i++) {
this.tree[len + i] = nums[i]
}
for (let i = len - 1; i > 0; i--) {
this.tree[i] = this.tree[i * 2] + this.tree[i * 2 + 1]
}
}
/**
* @param {number} i
* @param {number} val
* @return {void}
*/
NumArray.prototype.update = function (i, val) {
i += this.tree.length / 2
this.tree[i] = val
while (i > 1) {
let parent = Math.floor(i / 2)
let other = i % 2 == 1 ? i - 1 : i + 1
this.tree[parent] = this.tree[i] + this.tree[other]
i = parent
}
}
/**
* @param {number} i
* @param {number} j
* @return {number}
*/
NumArray.prototype.sumRange = function (i, j) {
let l = this.tree.length / 2 + i
let r = this.tree.length / 2 + j
let sum = 0
while (l <= r) {
if (l % 2 == 1) {
sum += this.tree[l]
l++
}
if (r % 2 == 0) {
sum += this.tree[r]
r--
}
l /= 2
r = Math.floor(r / 2)
}
return sum
}
/**
* Your NumArray object will be instantiated and called as such:
* var obj = new NumArray(nums)
* obj.update(i,val)
* var param_2 = obj.sumRange(i,j)
*/
/**
* 327. 区间和的个数(暴力循环)
* @param {number[]} nums
* @param {number} lower
* @param {number} upper
* @return {number}
*/
var countRangeSum = function (nums, lower, upper) {
let ans = 0
for (let i = 0, len = nums.length; i < len; i++) {
let sum = 0
for (let j = i; j < len; j++) {
sum += nums[j]
if (sum >= lower && sum <= upper) ans++
}
}
return ans
}
/**
* 326. 3的幂
* @param {number} n
* @return {boolean}
*/
var isPowerOfThree = function (n) {
let res = 1
while (res < n) {
res *= 3
}
return res === n
}
/**
* 238. 除自身以外数组的乘积
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function (nums) {
const pre = [],
suf = [],
res = []
let l = 1
for (let i = 0, len = nums.length; i < len; i++) {
pre.push(l)
l *= nums[i]
}
let r = 1
for (let len = nums.length, i = len - 1; i >= 0; i--) {
suf[i] = r
r *= nums[i]
}
for (let i = 0, len = nums.length; i < len; i++) res.push(pre[i] * suf[i])
return res
}
/**
* 66. 加一
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function (digits) {
const len = digits.length
if (digits[len - 1] !== 9) {
digits[len - 1]++
} else {
let i = 1
while (i <= len && digits[len - i] === 9) {
digits[len - i] = 0
i++
}
if (len - i < 0) {
digits.unshift(1)
return digits
}
digits[len - i]++
}
return digits
}
/**
* 5. 最长回文子串(中心扩展)
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
const len = s.length,
N = len * 2 - 1
let res = ''
for (let i = 0; i < N; i++) {
let l = Math.ceil(i / 2) - 1,
r = l + 1 + (i % 2 === 0 ? 1 : 0)
let count = i % 2 === 0 ? 1 : 0
while (l >= 0 && r < len && s[l] === s[r]) {
l--
r++
count += 2
}
if (count > res.length) res = s.slice(l + 1, r)
}
return res
}
/**
* 334. 递增的三元子序列
* @param {number[]} nums
* @return {boolean}
*/
var increasingTriplet = function (nums) {
let first = Number.MAX_SAFE_INTEGER,
second = Number.MAX_SAFE_INTEGER
for (let i = 0, len = nums.length; i < len; i++) {
if (nums[i] <= first) {
first = nums[i]
} else if (nums[i] < second) {
second = nums[i]
}
if (nums[i] > second) return true
}
return false
}
/**
* 350. 两个数组的交集 II(排序)
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersect = function (nums1, nums2) {
nums1.sort((a, b) => a - b)
nums2.sort((a, b) => a - b)
const ans = []
let i = 0,
j = 0,
len1 = nums1.length,
len2 = nums2.length
while (i < len1 && j < len2) {
if (nums1[i] === nums2[j]) {
ans.push(nums1[i])
i++
j++
} else if (nums1[i] < nums2[j]) {
i++
} else {
j++
}
}
return ans
}
/**
* 134. 加油站
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
var canCompleteCircuit = function (gas, cost) {
let total = 0,
len = gas.length,
sum = 0,
start = 0
for (let i = 0; i < len; i++) {
sum += gas[i] - cost[i]
total += gas[i] - cost[i]
if (sum < 0) {
sum = 0
start = i + 1
}
}
return total >= 0 ? start : -1
}
/**
* 387. 字符串中的第一个唯一字符(hash)
* @param {string} s
* @return {number}
*/
var firstUniqChar = function (s) {
const hash = {}
for (let i = 0, len = s.length; i < len; i++) {
if (hash.hasOwnProperty(s[i])) {
hash[s[i]]++
} else {
hash[s[i]] = 1
}
}
for (let i = 0, len = s.length; i < len; i++) {
if (hash[s[i]] === 1) return i
}
return -1
}
/**
* 124. 二叉树中的最大路径和
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function (root) {
let res = Number.MIN_SAFE_INTEGER
function getMax(node) {
if (!node) return 0
let l = Math.max(0, getMax(node.left))
let r = Math.max(0, getMax(node.right))
res = Math.max(res, node.val + l + r)
return Math.max(l, r) + node.val
}
getMax(root)
return res
}
/**
* 227. 基本计算器 II(栈)
* @param {string} s
* @return {number}
*/
var calculate = function (s) {
let stack = []
for (let i = 0, len = s.length; i < len; i++) {
if (s[i] === ' ') continue
let cur = ''
if (s[i] === '+' || s[i] === '-') {
cur = s[i]
} else if (s[i] === '*' || s[i] === '/') {
let symb = s[i]
let prev = stack.pop()
let next = ''
while (s[i + 1] === ' ' && i < s.length) i++
while (!Number.isNaN(+s[i + 1]) && s[i + 1] !== ' ' && i < s.length) {
next += s[++i]
}
cur = symb === '*' ? prev * +next : Math.floor(prev / +next)
} else {
cur += s[i]
while (!Number.isNaN(+s[i + 1]) && s[i + 1] !== ' ' && i < s.length) {
cur += s[++i]
}
cur = +cur
}
stack.push(cur)
}
let ans = stack[0]
for (let i = 1, len = stack.length; i < len; i++) {
if (stack[i] === '+') {
ans += stack[++i]
} else {
ans -= stack[++i]
}
}
return ans
}
/**
* 108. 将有序数组转换为二叉搜索树
* @param {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function (nums) {
if (nums.length === 0) return null
let mid = Math.floor(nums.length / 2)
let root = new TreeNode(nums[mid])
root.left = sortedArrayToBST(nums.slice(0, mid))
root.right = sortedArrayToBST(nums.slice(mid + 1))
return root
}
/**
* 38. 外观数列
* @param {number} n
* @return {string}
*/
var countAndSay = function (n) {
let ans = '1'
for (let i = 2; i <= n; i++) {
let temp = ''
for (let j = 0, len = ans.length; j < len; j++) {
let cur = ans[j],
count = 1
while (cur === ans[j + 1]) {
count++
j++
}
temp += count + cur
}
ans = temp
}
return ans
}
/**
* 315. 计算右侧小于当前元素的个数(暴力循环)
* @param {number[]} nums
* @return {number[]}
*/
var countSmaller = function (nums) {
if (nums.length === 0) return []
const ans = []
for (let i = 0, len = nums.length; i < len - 1; i++) {
let temp = 0
for (let j = i + 1; j < len; j++) {
if (nums[i] > nums[j]) temp++
}
ans.push(temp)
}
ans.push(0)
return ans
}
/**
* 138. 复制带随机指针的链表(hash)
* @param {Node} head
* @return {Node}
*/
var copyRandomList = function (head) {
const hash = new Map()
if (!head) return null
let cHead = new Node()
function copy(cNode, node) {
cNode.val = node.val
hash.set(node, cNode)
if (node.next) {
if (hash.has(node.next)) {
cNode.next = hash.get(node.next)
} else {
cNode.next = new Node()
copy(cNode.next, node.next)
}
}
if (node.random) {
if (hash.has(node.random)) {
cNode.random = hash.get(node.random)
} else {
cNode.random = new Node()
copy(cNode.random.node.random)
}
}
}
copy(cHead, head)
return cHead
}
/**
* 138. 复制带随机指针的链表(回溯)
* @param {Node} head
* @return {Node}
*/
const hash = new Map()
var copyRandomList = function (head) {
if (!head) return null
if (hash.has(head)) return hash.get(head)
const node = new Node()
node.val = head.val
hash.set(head, node)
node.next = copyRandomList(head.next)
node.random = copyRandomList(head.random)
return node
}
/**
* 171. Excel表列序号
* @param {string} s
* @return {number}
*/
var titleToNumber = function (s) {
const len = s.length
let ans = 0
for (let i = 0; i < len; i++) {
ans += (s[i].charCodeAt() - 64) * Math.pow(26, len - i - 1)
}
return ans
}
/**
* 204. 计数质数
* @param {number} n
* @return {number}
*/
var countPrimes = function (n) {
const prims = new Array(n)
prims.fill(true)
for (let i = 2; i * i <= n; i++) {
if (prims[i]) {
for (let j = 2; i * j <= n; j++) {
prims[i * j] = false
}
}
}
let ans = 0
for (let i = 2; i <= n; i++) if (prims[i]) ans++
return ans
}
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
let ans = ''
if (strs.length === 0) return ans
if (strs.length === 1) return strs[0]
const len = strs.length,
firstL = strs[0].length
for (let i = 0; i < firstL; i++) {
let temp = strs[0].slice(0, i + 1)
let j
for (j = 1; j < len; j++) {
if (temp !== strs[j].slice(0, i + 1)) break
}
if (j === len) {
ans = temp
} else {
break
}
}
return ans
}
/**
* 191. 位1的个数(位运算)
* @param {number} n - a positive integer
* @return {number}
*/
var hammingWeight = function (n) {
let ans = 0
for (let i = 32; i > 0; i--) {
ans += n & 1
n >>= 1
}
return ans
}
/**
* 131. 分割回文串(回溯法)
* @param {string} s
* @return {string[][]}
*/
var partition = function (s) {
const ans = [],
len = s.length
function backtrack(i, temp) {
if (i === len) ans.push(temp)
for (let count = i; count < len; count++) {
let cur = s.slice(i, count + 1)
if (cur === cur.split('').reverse().join('')) {
backtrack(count + 1, [...temp, cur])
}
}
}
backtrack(0, [])
return ans
}
/**
* 5. 最长回文子串(中心扩展)
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
const len = s.length,
N = len * 2 - 1
let ans = ''
for (let i = 0; i < N; i++) {
let l = (i - 1) >> 1
let r = l + (i % 2 === 0 ? 1 : 0) + 1
let count = i % 2 === 0 ? 1 : 0
while (l >= 0 && r < len && s[l] === s[r]) {
l--
r++
count += 2
}
if (ans.length < count) ans = s.slice(l + 1, r)
}
return ans
}
/**
* 395. 至少有K个重复字符的最长子串(分治法)
* @param {string} s
* @param {number} k
* @return {number}
*/
var longestSubstring = function (s, k) {
const queue = [s]
let ans = 0
while (queue.length) {
const cur = queue.pop(),
hash = {}
for (let i = 0, len = cur.length; i < len; i++) {
if (hash.hasOwnProperty(cur[i])) {
hash[cur[i]]++
} else {
hash[cur[i]] = 1
}
}
let i = 0,
prev = 0
for (i = 0, len = cur.length; i < len; i++) {
if (hash[cur[i]] < k) {
queue.push(cur.slice(prev, i))
prev = i + 1
}
}
if (prev === 0) ans = Math.max(ans, cur.length)
if (prev !== 0) queue.push(cur.slice(prev))
}
return ans
}
/**
* 88. 合并两个有序数组
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function (nums1, m, nums2, n) {
let i = 0,
j = 0
while (i < m && j < n) {
if (nums1[i] > nums2[j]) {
for (let k = m; k > i; k--) {
nums1[k] = nums1[k - 1]
}
m++
nums1[i] = nums2[j]
j++
i++
} else {
i++
}
}
while (j < n) {
nums1[m++] = nums2[j++]
}
}
/**
* 412. Fizz Buzz(极度简单,引起舒适)
* @param {number} n
* @return {string[]}
*/
var fizzBuzz = function (n) {
const ans = []
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
ans.push('FizzBuzz')
} else if (i % 3 === 0) {
ans.push('Fizz')
} else if (i % 5 === 0) {
ans.push('Buzz')
} else {
ans.push(i + '')
}
}
return ans
}
/**
* 91. 解码方法(动态规划)
* @param {string} s
* @return {number}
*/
var numDecodings = function (s) {
if (s[0] == 0) return 0
let prev1 = 1,
prev2 = 1
const len = s.length
for (let i = 1; i < len; i++) {
let temp = 0
if (s[i] == 0 && (s[i - 1] == 0 || s[i - 1] > 2)) return 0
if (s[i] == 0) {
temp = prev1
} else if (s[i - 1] == 0 || +(s[i - 1] + s[i]) > 26) {
temp = prev2
} else {
temp = prev1 + prev2
}
prev1 = prev2
prev2 = temp
}
return prev2
}
/**
* 44. 通配符匹配(动态规划)
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function (s, p) {
const lenS = s.length,
lenP = p.length
const dp = new Array(lenS + 1)
for (let i = 0; i <= lenS; i++) {
dp[i] = new Array(lenP + 1)
dp[i].fill(false)
}
dp[lenS][lenP] = true
for (let i = lenP - 1; i >= 0; i--) {
dp[lenS][i] = dp[lenS][i + 1] && p[i] === '*'
}
for (let i = lenS - 1; i >= 0; i--) {
for (let j = lenP - 1; j >= 0; j--) {
const charS = s[i],
charP = p[j]
if (charS === charP || charP === '?') {
dp[i][j] = dp[i + 1][j + 1]
} else if (charP === '*') {
for (let n = 0; n <= lenS - i; n++) {
dp[i][j] = dp[i][j] || dp[i + n][j + 1]
}
}
}
}
return dp[0][0]
}
/**
* 118. 杨辉三角
* @param {number} numRows
* @return {number[][]}
*/
var generate = function (numRows) {
if (numRows === 0) return []
const ans = [[1]]
for (let i = 1; i < numRows; i++) {
const cur = [1]
for (let j = 1; j < i; j++) {
cur.push(ans[i - 1][j - 1] + ans[i - 1][j])
}
cur.push(1)
ans.push(cur)
}
return ans
}
/**
* 1108. IP 地址无效化
* @param {string} address
* @return {string}
*/
var defangIPaddr = function (address) {
let ans = ''
for (let i = 0, len = address.length; i < len; i++) {
if (address[i] === '.') {
ans += '[.]'
} else {
ans += address[i]
}
}
return ans
}
/**
* 1317. 将整数转换为两个无零整数的和
* @param {number} n
* @return {number[]}
*/
var getNoZeroIntegers = function (n) {
for (let i = 1; i < n; i++) {
let temp = n - i
if (!/0/.test(i) && !/0/.test(temp)) return [i, temp]
}
}
/**
* 1313. 解压缩编码列表
* @param {number[]} nums
* @return {number[]}
*/
var decompressRLElist = function (nums) {
const ans = []
let i = 0
const len = nums.length
while (i < len) {
const cnt = nums[i++]
const val = nums[i++]
for (j = 0; j < cnt; j++) ans.push(val)
}
return ans
}
/**
* 592. 分数加减运算
* @param {string} expression
* @return {string}
*/
var fractionAddition = function (expression) {
const arr = [],
len = expression.length
let i = 0
while (i < len) {
let nu = '',
de = ''
if (expression[i] === '+') {
i++
continue
}
while (i < len && expression[i] !== '/') nu += expression[i++]
i++
while (i < len && expression[i] !== '+' && expression[i] !== '-')
de += expression[i++]
arr.push([+nu, +de])
}
const ans = arr[0]
for (let i = 1, len = arr.length; i < len; i++) {
const temp = arr[i]
if (ans[1] !== temp[1]) {
const a = ans[1],
b = temp[1]
ans[0] *= b
ans[1] *= b
temp[0] *= a
temp[1] *= a
}
ans[0] += temp[0]
}
function dp(a, b) {
if (b === 0) return a
return dp(b, a % b)
}
let x = dp(Math.abs(ans[0]), Math.abs(ans[1]))
ans[0] /= x
ans[1] /= x
return '' + ans[0] + '/' + ans[1]
}
/**
* 7. 整数反转
* @param {number} x
* @return {number}
*/
var reverse = function (x) {
let ans = 0
let n = Math.abs(x)
const max = Math.pow(2, 31)
while (n) {
ans = ans * 10 + (n % 10)
n = Math.floor(n / 10)
if (ans >= max) return 0
}
return x > 0 ? ans : -ans
}
/**
* 231. 2的幂
* @param {number} n
* @return {boolean}
*/
var isPowerOfTwo = function (n) {
return n > 0 && (n & (n - 1)) === 0
}
/**
* 9. 回文数
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function (x) {
if (x < 0) return false
let rev = 0
let n = x
while (n) {
rev = rev * 10 + (n % 10)
n = Math.floor(n / 10)
}
return rev === x
}
// const coins = [25,10,5,1]
// const mod = 1000000007
// const dp = new Array(n+1)
// dp.fill(0)
// dp[0] = 1
// for(let i = 0; i<4; i++){
// for(let j = coins[i]; j<=n;j++){
// dp[j] += dp[j-coins[i]]
// }
// }
// return dp[n]
/**
* 292. Nim 游戏
* @param {number} n
* @return {boolean}
*/
var canWinNim = function (n) {
return n % 4 !== 0
}
/**
* 89. 格雷编码
* @param {number} n
* @return {number[]}
*/
var grayCode = function (n) {
const ans = []
for (let i = 0; i < 1 << n; i++) {
ans.push(i ^ (i >> 1))
}
return ans
}
/**
* 874. 模拟行走机器人
* @param {number[]} commands
* @param {number[][]} obstacles
* @return {number}
*/
var robotSim = function (commands, obstacles) {
const obs_hash = new Map()
for (let i = 0, len = obstacles.length; i < len; i++) {
const temp = obstacles[i]
obs_hash.set(temp[0] + '-' + temp[1])
}
let x = 0,
y = 0,
dx = 0,
dy = 1,
angle = 0,
ans = 0
for (let i = 0, len = commands.length; i < len; i++) {
let cur = commands[i]
if (cur === -1 || cur === -2) {
if (cur === -1) angle = (angle + 90) % 360
if (cur === -2) angle = angle ? angle - 90 : 270
if (angle === 0) [dx, dy] = [0, 1]
if (angle === 90) [dx, dy] = [1, 0]
if (angle === 180) [dx, dy] = [0, -1]
if (angle === 270) [dx, dy] = [-1, 0]
} else {
while (cur-- && !obs_hash.has(x + dx + '-' + (y + dy))) {
x += dx
y += dy
ans = Math.max(ans, x * x + y * y)
}
}
}
return ans
}
<file_sep>/**
* 997. 找到小镇的法官(图)
* @param {number} N
* @param {number[][]} trust
* @return {number}
*/
var findJudge = function (N, trust) {
let deGeree = new Array(N)
deGeree.fill(0)
for (let i = 0, len = trust.length; i < len; i++) {
deGeree[trust[i][0] - 1]++
}
for (let i = 0; i < N; i++) {
if (deGeree[i] === 0) {
let count = N - 1,
cur = i + 1
for (let j = 0, len = trust.length; j < len; j++) {
if (trust[j][1] == cur) count--
}
if (count === 0) return cur
}
}
return -1
}
/**
* 133. 克隆图(dfs)
* @param {Node} node
* @return {Node}
*/
var cloneGraph = function (node) {
const visited = new WeakMap()
function dfs(node) {
if (!node) return null
if (visited.has(node)) return visited.get(node)
const cur = new Node(node.val)
visited.set(node, cur)
for (let i = 0, len = node.neighbors.length; i < len; i++) {
cur.neighbors.push(dfs(node.neighbors[i]))
}
return cur
}
return dfs(node)
}
/**
* 133. 克隆图(bfs)
* @param {Node} node
* @return {Node}
*/
var cloneGraph = function (node) {
if (!node) return null
const visited = new WeakMap()
visited.set(node, new Node(node.val))
const queue = [node]
while (queue.length) {
const cur = queue.shift()
for (let i = 0, len = cur.neighbors.length; i < len; i++) {
const nei = cur.neighbors[i]
if (!visited.has(nei)) {
queue.push(nei)
visited.set(nei, new Node(nei.val))
}
visited.get(cur).neighbors.push(visited.get(nei))
}
}
return visited.get(node)
}
/**
* 1203. 项目管理
* @param {number} n
* @param {number} m
* @param {number[]} group
* @param {number[][]} beforeItems
* @return {number[]}
*/
var sortItems = function (n, m, group, beforeItems) {
let max_m = 0
for (let i = 0; i < n; i++) max_m = Math.max(max_m, group[i])
m = max_m + 1
for (let i = 0; i < n; i++) if (group[i] === -1) group[i] = m++
const ans = []
const graph_group = new Array(m)
const indegree_group = new Array(m)
const graph_items = new Array(n)
const indegree_items = new Array(n)
indegree_group.fill(0)
indegree_items.fill(0)
for (let i = 0; i < m; i++) {
graph_group[i] = new Array(m)
graph_group[i].fill(0)
}
for (let i = 0; i < n; i++) {
graph_items[i] = new Array(n)
graph_items[i].fill(0)
}
for (let i = 0; i < n; i++) {
const g = group[i]
const before = beforeItems[i]
for (let j = 0, len = before.length; j < len; j++) {
const b = before[j]
if (g === group[b]) {
graph_items[b][i] = 1
indegree_items[i]++
}
if (g !== group[b] && graph_group[group[b]][g] === 0) {
graph_group[group[b]][g] = 1
indegree_group[g]++
}
}
}
const order_group = []
while (true) {
const list = []
for (let i = 0; i < m; i++) {
if (indegree_group[i] === 0) {
list.push(i)
indegree_group[i]--
for (let j = 0; j < m; j++) {
if (graph_group[i][j]) indegree_group[j]--
}
}
}
if (list.length === 0) break
order_group.push(...list)
}
if (order_group.length !== m) return ans
const g_items = new Array(order_group.length)
for (let i = 0, len = order_group.length; i < len; i++) g_items[i] = []
for (let i = 0; i < n; i++) {
const index = order_group.indexOf(group[i])
g_items[index].push(i)
}
for (let i = 0, len = g_items.length; i < len; i++) {
const items = g_items[i]
const order_items = []
while (true) {
const list = []
for (let j = 0, len = items.length; j < len; j++) {
if (items[j] !== -1 && indegree_items[items[j]] === 0) {
list.push(items[j])
for (let k = 0; k < n; k++) {
if (graph_items[items[j]][k]) indegree_items[k]--
}
indegree_items[items[j]]--
items[j] = -1
}
}
if (list.length === 0) break
order_items.push(...list)
}
if (order_items.length !== items.length) return []
ans.push(...order_items)
}
return ans
}
<file_sep>/**
* 78. 子集(枚举)
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function (nums) {
let res = [[]]
for (let i = 0, len = nums.length; i < len; i++) {
let count = res.length
while (count) {
let temp = [...res[count - 1]]
temp.push(nums[i])
res.push(temp)
count--
}
}
return res
}
/**
* 17. 电话号码的字母组合(枚举)
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function (digits) {
let hash = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz',
},
res = []
if (digits <= 1) return res
res = [...hash[digits[0]]]
for (let i = 1, len1 = digits.length; i < len1; i++) {
let count = res.length,
len = count
while (count) {
for (let k = 0, len3 = hash[digits[i]].length; k < len3; k++) {
res.push(res[count - 1] + hash[digits[i]][k])
}
count--
}
res.splice(0, len)
}
return res
}
/**
* 17. 电话号码的字母组合(回溯法)
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function (digits) {
let hash = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz',
},
res = []
if (!digits) return res
function backtrack(str, digits) {
if (!digits) {
res.push(str)
return
}
let cur = hash[digits[0]]
for (let i = 0, len = cur.length; i < len; i++) {
backtrack(str + cur[i], digits.slice(1))
}
}
backtrack('', digits)
return res
}
/**
* 46. 全排列(全排列)
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function (nums) {
let res = []
function backtrack(has, left) {
if (has.length === nums.length) {
res.push(has)
return
}
for (let i = 0, len = left.length; i < len; i++) {
backtrack(
[...has, left[i]],
left.filter((x) => x != left[i])
)
}
}
backtrack([], nums)
return res
}
/**
* 78. 子集(回溯法)
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function (nums) {
let res = []
function backtrack(arr, index) {
res.push(arr)
for (let i = index, len = nums.length; i < len; i++) {
backtrack([...arr, nums[i]], i + 1)
}
}
backtrack([], 0)
return res
}
/**
* 90. 子集 II(排序+回溯)
* @param {number[]} nums
* @return {number[][]}
*/
var subsetsWithDup = function (nums) {
let res = []
nums.sort((a, b) => a - b)
function backtrack(arr, index) {
res.push(arr)
for (let i = index, len = nums.length; i < len; i++) {
backtrack([...arr, nums[i]], i + 1)
while (nums[i] === nums[i + 1]) i++
}
}
backtrack([], 0)
return res
}
/**
* 784. 字母大小写全排列(回溯法)
* @param {string} S
* @return {string[]}
*/
var letterCasePermutation = function (S) {
let res = []
const reg = new RegExp('[A-Za-z]')
function backtrack(str, index) {
if (str.length === S.length) {
res.push(str)
return
}
for (let i = index, len = S.length; i < len; i++) {
while (!reg.test(S[i])) {
str += S[i]
i++
if (i >= S.length) {
str.length === S.length && res.push(str)
return
}
}
let letter1 = S[i]
let letter2 =
letter1.charCodeAt() < 97
? letter1.toLocaleLowerCase()
: letter1.toLocaleUpperCase()
backtrack(str + letter1, i + 1)
backtrack(str + letter2, i + 1)
}
}
backtrack('', 0)
return res
}
/**
* 77. 组合(回溯法)
* @param {number} n
* @param {number} k
* @return {number[][]}
*/
var combine = function (n, k) {
let res = []
function backtrack(arr, index) {
if (arr.length === k) {
res.push(arr)
return
}
if (index > n) return
for (let i = index; i <= n; i++) {
backtrack([...arr, i], i + 1)
}
}
backtrack([], 1)
return res
}
/**
* 77. 组合(回溯法剪枝)
* @param {number} n
* @param {number} k
* @return {number[][]}
*/
var combine = function (n, k) {
let res = []
function backtrack(arr, index) {
if (arr.length === k) {
res.push(arr)
return
}
if (index > n) return
for (let i = index; i <= n - (k - arr.length) + 1; i++) {
backtrack([...arr, i], i + 1)
}
}
backtrack([], 1)
return res
}
/**
* 526. 优美的排列
* @param {number} N
* @return {number}
*/
var countArrangement = function (N) {
const visited = new Array(N + 1)
visited.fill(false)
let ans = 0
function backTrack(i) {
if (i > N) ans++
for (let j = 1; j <= N; j++) {
if (visited[j]) continue
if (i % j === 0 || j % i === 0) {
visited[j] = true
backTrack(i + 1)
visited[j] = false
}
}
}
backTrack(1)
return ans
}
/**
* 51. N皇后
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function (n) {
const ans = []
const grid = new Array(n)
for (let i = 0; i < n; i++) {
grid[i] = new Array(n)
grid[i].fill('.')
}
function backTrack(i) {
if (i === n) {
const temp = new Array()
grid.forEach((item) => {
temp.push(item.join(''))
})
ans.push(temp)
return
}
for (let j = 0; j < n; j++) {
if (isOk(i, j, grid)) {
grid[i][j] = 'Q'
backTrack(i + 1)
grid[i][j] = '.'
}
}
}
backTrack(0)
return ans
}
function isOk(i, j, grid) {
for (let k = 0; k < i; k++) {
if (grid[k][j] === 'Q') return false
}
let a = i,
b = j
while (a >= 0 && b >= 0) {
if (grid[a--][b--] === 'Q') return false
}
;(a = i), (b = j)
while (a >= 0 && b < grid[0].length) {
if (grid[a--][b++] === 'Q') return false
}
return true
}
/**
* 37. 解数独
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solveSudoku = function (board) {
function isOk(i, j, val) {
for (let k = 0; k < 9; k++) {
if (board[i][k] == val) return false
}
for (let k = 0; k < 9; k++) {
if (board[k][j] == val) return false
}
let l = Math.floor(j / 3) * 3,
t = Math.floor(i / 3) * 3
for (let m = t; m < t + 3; m++) {
for (let n = l; n < l + 3; n++) {
if (board[m][n] == val) return false
}
}
return true
}
function backTrace(i, j) {
if (j === 9) {
if (i === 8) return true
i++
j = 0
}
if (board[i][j] === '.') {
for (let val = 1; val <= 9; val++) {
if (isOk(i, j, val)) {
board[i][j] = val + ''
if (backTrace(i, j + 1)) return true
}
board[i][j] = '.'
}
} else {
return backTrace(i, j + 1)
}
return false
}
backTrace(0, 0)
}
/**
* 301. 删除无效的括号
* @param {string} s
* @return {string[]}
*/
var removeInvalidParentheses = function (s) {
let ans = new Set()
function backTrace(i, cnt, str) {
if (cnt < 0 || i > s.length) return
if (i === s.length && cnt === 0) ans.add(str)
if (s[i] !== ')' && s[i] !== '(') {
backTrace(i + 1, cnt, str + s[i])
} else {
backTrace(i + 1, cnt + (s[i] === '(' ? 1 : -1), str + s[i])
backTrace(i + 1, cnt, str)
}
}
backTrace(0, 0, '')
ans = [...ans]
ans.sort((a, b) => b.length - a.length)
let i = 0
while (i < ans.length - 1 && ans[i].length === ans[i + 1].length) i++
return ans.slice(0, i + 1)
}
<file_sep>/**
* 15.三数之和(双指针)
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
nums.sort((a, b) => a - b)
let res = []
for (let i = 0, len = nums.length; i < len; i++) {
let cur = nums[i]
let left = i + 1,
right = len - 1
while (left < right) {
if (cur + nums[left] + nums[right] === 0) {
res.push([cur, nums[left], nums[right]])
while (
nums[left + 1] === nums[left] &&
nums[right - 1] === nums[right]
) {
left++
right--
}
left++
right--
} else if (cur + nums[left] + nums[right] > 0) {
right--
} else {
left++
}
}
while (nums[i] === nums[i + 1]) i++
}
return res
}
/**
* 2. 两数相加(链表)
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function (l1, l2) {
let num1 = '',
num2 = ''
while (l1) {
num1 = l1.val + num1
l1 = l1.next
}
while (l2) {
num2 = l2.val + num2
l2 = l2.next
}
let l = new ListNode(null),
dummy = new ListNode(null)
dummy.next = l
let index1 = num1.length - 1,
index2 = num2.length - 1,
surplus = 0
while (index1 >= 0 || index2 >= 0 || surplus) {
let n1 = 0,
n2 = 0
if (index1 >= 0) {
n1 = +num1[index1]
index1--
}
if (index2 >= 0) {
n2 = +num2[index2]
index2--
}
let num = n1 + n2 + surplus
if (num >= 10) {
num = num % 10
surplus = 1
} else {
surplus = 0
}
l.val = num
if (index1 >= 0 || index2 >= 0 || surplus) {
l.next = new ListNode(null)
l = l.next
}
}
return dummy.next
}
/**
* 121. 买卖股票的最佳时机
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let min = Number.MAX_SAFE_INTEGER,
profit = 0
for (let i = 0, len = prices.length; i < len; i++) {
min = Math.min(min, prices[i])
profit = Math.max(prices[i] - min, profit)
}
return profit
}
/**
* 94. 二叉树的中序遍历
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function (root) {
let res = []
function mfs(node) {
if (!node) return null
mfs(node.left)
res.push(node.val)
mfs(node.right)
}
mfs(root)
return res
}
/**
* 102. 二叉树的层次遍历(dfs)
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function (root) {
let res = []
function dfs(node, i) {
if (!node) return
if (!Array.isArray(res[i])) res[i] = []
res[i].push(node.val)
dfs(node.left, i + 1)
dfs(node.right, i + 1)
}
dfs(root, 0)
return res
}
/**
* 312. 戳气球(暴力递归)
* @param {number[]} nums
* @return {number}
*/
var maxCoins = function (nums) {
function dp(arr) {
if (arr.length === 0) return 0
if (arr.length === 1) return arr[0]
let res = 0
for (let i = 0, len = arr.length; i < len; i++) {
let left = i === 0 ? 1 : arr[i - 1],
right = i === arr.length - 1 ? 1 : arr[i + 1]
res = Math.max(
res,
left * arr[i] * right + dp(arr.filter((x) => x !== arr[i]))
)
}
return res
}
return dp(nums)
}
/**
* 70. 爬楼梯(暴力递归)
* @param {number} n
* @return {number}
*/
var climbStairs = function (n) {
function dp(n) {
if (n === 0) return 1
if (n === 1) return 1
if (n === 2) return 2
return dp(n - 1) + dp(n - 2)
}
return dp(n)
}
/**
* 70. 爬楼梯(动态规划)
* @param {number} n
* @return {number}
*/
var climbStairs = function (n) {
let a = 1,
b = 1
for (let i = 2; i <= n; i++) {
let temp = b
b = a + b
a = temp
}
return b
}
/**
* 322. 零钱兑换(暴力递归)
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
function dp(n) {
if (n < 0) return -1
if (n === 0) return 0
let res = Number.MAX_SAFE_INTEGER,
count = 0
for (let i = 0, len = coins.length; i < len; i++) {
if (n - coins[i] >= 0) {
count++
res = Math.min(res, 1 + dp(n - coins[i]))
}
}
return count === 0 ? -1 : res
}
return dp(amount)
}
/**
* 322. 零钱兑换(动态规划)
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
let dp = new Array(amount + 1)
dp.fill(-1)
dp[0] = 0
for (let i = 1; i <= amount; i++) {
let res = Number.MAX_SAFE_INTEGER
for (let j = 0, len = coins.length; j < len; j++) {
if (coins[j] > i) continue
if (dp[i - coins[j]] === -1) continue
res = Math.min(res, 1 + dp[i - coins[j]])
}
if (res !== Number.MAX_SAFE_INTEGER) dp[i] = res
}
return dp[amount]
}
/**
* 39. 组合总和(回溯法)
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function (candidates, target) {
let res = [],
len = candidates.length
candidates.sort((a, b) => a - b)
function backtrack(i, sum, arr) {
if (i >= len || sum > target) return
if (sum === target) {
res.push(arr)
return
}
for (let j = i; j < len; j++) {
if (candidates[j] + sum > target) break
backtrack(j, sum + candidates[j], [...arr, candidates[j]])
}
}
backtrack(0, 0, [])
return res
}
/**
* 11. 盛最多水的容器(暴力递归)
* @param {number[]} height
* @return {number}
*/
var maxArea = function (height) {
function dp(i, j) {
if (i > j) return 0
if (i === j) return 0
let temp = (j - i) * Math.min(height[i], height[j])
return Math.max(temp, dp(i + 1, j), dp(i, j - 1))
}
return dp(0, height.length - 1)
}
/**
* 11. 盛最多水的容器(双指针)
* @param {number[]} height
* @return {number}
*/
var maxArea = function (height) {
let left = 0,
right = height.length - 1
let res = (right - left) * Math.min(height[left], height[right])
while (left < right) {
if (height[left] > height[right]) {
right--
} else {
left++
}
res = Math.max(res, (right - left) * Math.min(height[left], height[right]))
}
return res
}
/**
* 538. 把二叉搜索树转换为累加树(逆中序遍历)
* @param {TreeNode} root
* @return {TreeNode}
*/
var convertBST = function (root) {
let count = 0
function dfs(node) {
if (!node) return
dfs(node.right)
let temp = node.val
node.val += count
count += temp
dfs(node.left)
}
dfs(root)
return root
}
/**
* 739. 每日温度
* @param {number[]} T
* @return {number[]}
*/
var dailyTemperatures = function (T) {
let res = []
for (let i = 0, len = T.length; i < len; i++) {
let j = i
while (j < len - 1 && T[i] >= T[j]) j++
if (T[i] < T[j]) {
res.push(j - i)
} else {
res.push(0)
}
}
return res
}
/**
* 394. 字符串解码(栈)
* @param {string} s
* @return {string}
*/
var decodeString = function (s) {
let stack = []
for (let i = 0, len = s.length; i < len; i++) {
if (s[i] !== ']') {
stack.push(s[i])
} else {
let j = stack.length - 1,
n = '',
str = '',
reg = /[0-9]/
while (stack[j] !== '[') {
str = stack.pop() + str
j--
}
stack.pop()
j--
while (j >= 0 && reg.test(stack[j])) {
n = stack.pop() + n
j--
}
let temp = ''
for (let i = 0; i < +n; i++) {
temp += str
}
stack.push(...temp)
}
}
return stack.join('')
}
/**
* 543. 二叉树的直径(dfs)
* @param {TreeNode} root
* @return {number}
*/
var diameterOfBinaryTree = function (root) {
let res = 1
function dfs(node) {
if (node == null) return 0
let L = dfs(node.left)
let R = dfs(node.right)
res = Math.max(res, L + R + 1)
return Math.max(L, R) + 1
}
dfs(root)
return res - 1
}
/**
* 72. 编辑距离(暴力递归)
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var minDistance = function (word1, word2) {
function dp(i, j) {
if (i < 0 && j < 0) return 0
if (i < 0 || j < 0) return Math.abs(j - i)
if (word1[i] === word2[j]) return dp(i - 1, j - 1)
return 1 + Math.min(dp(i, j - 1), dp(i - 1, j), dp(i - 1, j - 1))
}
return dp(word1.length - 1, word2.length - 1)
}
/**
* 438. 找到字符串中所有字母异位词(滑动窗口)
* @param {string} s
* @param {string} p
* @return {number[]}
*/
var findAnagrams = function (s, p) {
let hash = {},
left = 0,
right = 0,
res = [],
temp = {}
for (let i = 0, len = p.length; i < len; i++) {
if (hash.hasOwnProperty(p[i])) {
hash[p[i]]++
} else {
hash[p[i]] = 1
}
}
let count = Object.keys(hash).length
while (right < s.length) {
let char = s[right]
if (temp.hasOwnProperty(char)) {
temp[char]++
} else {
temp[char] = 1
}
if (hash[char] === temp[char]) count--
if (count === 0) res.push(left)
if (right - left + 1 === p.length) {
let char = s[left]
if (temp[char] === hash[char]) count++
if (temp[char] === 1) {
delete temp[char]
} else {
temp[char]--
}
left++
}
right++
}
return res
}
/**
* 448. 找到所有数组中消失的数字(抽屉原理)
* @param {number[]} nums
* @return {number[]}
*/
var findDisappearedNumbers = function (nums) {
for (let i = 0, len = nums.length; i < len; i++) {
let cur = nums[i]
while (cur !== i + 1 && nums[cur - 1] !== cur) {
;[nums[cur - 1], nums[i]] = [nums[i], nums[cur - 1]]
cur = nums[i]
}
}
let res = []
for (let i = 0, len = nums.length; i < len; i++) {
if (i + 1 !== nums[i]) res.push(i + 1)
}
return res
}
/**
* 34. 在排序数组中查找元素的第一个和最后一个位置(二分法)
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function (nums, target) {
let left = 0,
right = nums.length - 1
while (left <= right) {
let mid = left + Math.floor((right - left) / 2)
if (nums[mid] === target) {
let start = mid,
end = mid
while (nums[start] === nums[start - 1]) start--
while (nums[end] === nums[end + 1]) end++
return [start, end]
}
if (nums[mid] > target) {
right = mid - 1
} else {
left = mid + 1
}
}
return [-1, -1]
}
/**
* 22. 括号生成(回溯法)
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function (n) {
if (n === 0) return ['']
let res = []
function backtrack(str, left, right) {
if (str.length === n * 2) {
let stack = []
for (let i = 0, len = str.length; i < len; i++) {
if (stack[stack.length - 1] === '(' && str[i] === ')') {
stack.pop()
} else {
stack.push(str[i])
}
}
if (stack.length === 0) {
res.push(str)
}
return
}
if (left === 0) {
backtrack(str + ')', 0, right - 1)
} else if (right === 0) {
backtrack(str + '(', left - 1, 0)
} else {
backtrack(str + '(', left - 1, right)
backtrack(str + ')', left, right - 1)
}
}
backtrack('(', n - 1, n)
return res
}
/**
* 49. 字母异位词分组
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function (strs) {
let hash = {},
res = [],
count = 0
for (let i = 0, len = strs.length; i < len; i++) {
let cur = strs[i],
temp = []
for (let j = 0, len = cur.length; j < len; j++) {
temp.push(+cur[j].charCodeAt())
}
temp.sort((a, b) => a - b)
let key = temp.join('')
if (hash.hasOwnProperty(key)) {
res[hash[key]].push(cur)
} else {
hash[key] = count
res[count] = [cur]
count++
}
}
return res
}
/**
* 208. 实现 Trie (前缀树)
* Initialize your data structure here.
*/
var Trie = function () {
this.root = {}
}
/**
* Inserts a word into the trie.
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function (word) {
const insert = (node, word) => {
if (!word) return
let char = word[0]
if (!node.hasOwnProperty(char)) node[char] = {}
if (word.length === 1) node[char].isEnd = true
insert(node[char], word.slice(1))
}
insert(this.root, word)
}
/**
* Returns if the word is in the trie.
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function (word) {
const search = (node, word) => {
if (!word) return false
let char = word[0]
if (!node.hasOwnProperty(char)) return false
if (word.length === 1 && node[char].isEnd) return true
return search(node[char], word.slice(1))
}
return search(this.root, word)
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function (prefix) {
const startsWith = (node, prefix) => {
if (!prefix) return false
let char = prefix[0]
if (!node.hasOwnProperty(char)) return false
if (prefix.length === 1) return true
return startsWith(node[char], prefix.slice(1))
}
return startsWith(this.root, prefix)
}
/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/
/**
* 226. 翻转二叉树
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function (root) {
function reverse(node) {
if (!node) return
let temp = node.right
node.right = node.left
node.left = temp
reverse(node.left)
reverse(node.right)
}
reverse(root)
return root
}
/**
* 55. 跳跃游戏(暴力递归)
* @param {number[]} nums
* @return {boolean}
*/
var canJump = function (nums) {
if (nums.length === 0) return true
let len = nums.length
function dp(i) {
if (i === len - 1) return true
if (nums[i] === 0) return false
let res = false
for (let j = 1; j <= nums[i]; j++) {
res = res || dp(i + j)
}
return res
}
return dp(0)
}
/**
* 55. 跳跃游戏(动态规划)
* @param {number[]} nums
* @return {boolean}
*/
var canJump = function (nums) {
let len = nums.length,
dp = new Array(len)
dp.fill(false)
dp[len - 1] = true
for (let i = len - 2; i >= 0; i--) {
if (nums[i] > len - i) {
dp[i] = true
continue
}
for (let j = 1; j <= nums[i]; j++) {
dp[i] = dp[i] || dp[i + j]
}
}
return dp[0]
}
/**
* 215. 数组中的第K个最大元素(小顶堆)
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findKthLargest = function (nums, k) {
if (k > nums.length) return -1
let heap = [null]
function insert(val) {
heap.push(val)
let i = heap.length - 1,
p = Math.floor(i / 2)
while (i > 1 && heap[i] < heap[p]) {
let temp = heap[i]
heap[i] = heap[p]
heap[p] = temp
i = p
p = Math.floor(i / 2)
}
}
function replace(val) {
heap.push(val)
let temp = heap[1]
heap[1] = heap[heap.length - 1]
heap[heap.length - 1] = temp
heap.pop()
let i = 1,
len = heap.length
while (i * 2 <= len - 1) {
let left = i * 2,
right = i * 2 + 1
if (heap[i] <= heap[left] && (right >= k || heap[i] <= heap[right]))
return
if (right >= k || heap[left] < heap[right]) {
;[heap[i], heap[left]] = [heap[left], heap[i]]
i = left
} else {
;[heap[i], heap[right]] = [heap[right], heap[i]]
i = right
}
}
}
for (let i = 0, len = nums.length; i < len; i++) {
if (heap.length <= k) {
insert(nums[i])
} else {
if (heap[1] < nums[i]) replace(nums[i])
}
}
return heap[1]
}
/**
* 128. 最长连续序列(哈希表)
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function (nums) {
let hash = {}
for (let i = 0, len = nums.length; i < len; i++) {
hash[nums[i]] = 1
}
let res = 0
while (Object.keys(hash).length) {
let keys = Object.keys(hash)
let cur = keys[0],
count = 1,
left = +cur - 1 + '',
right = +cur + 1 + ''
delete hash[cur]
while (hash.hasOwnProperty(left)) {
delete hash[left]
count++
left--
}
while (hash.hasOwnProperty(right)) {
delete hash[right]
count++
right++
}
res = Math.max(res, count)
}
return res
}
/**
* 84. 柱状图中最大的矩形(暴力递归)
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function (heights) {
function dp(i, j) {
if (i > j) return 0
if (i === j) return heights[i]
return Math.max(
(j - i + 1) * Math.min(...heights.slice(i, j + 1)),
dp(i + 1, j),
dp(i, j - 1)
)
}
return dp(0, heights.length - 1)
}
/**
* 84. 柱状图中最大的矩形(动态规划)
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function (heights) {
if (heights.length === 0) return 0
let len = heights.length,
dp = new Array(len)
for (let i = 0; i < len; i++) {
dp[i] = new Array(len)
dp[i][i] = heights[i]
}
for (let l = 1; l < len; l++) {
for (let i = 0; i < len - 1; i++) {
let j = l + i,
temp = (j - i + 1) * Math.min(...heights.slice(i, j + 1))
dp[i][j] = Math.max(temp, dp[i + 1][j], dp[i][j - 1])
}
}
return dp[0][len - 1]
}
/**
* 300. 最长上升子序列(暴力递归)
* @param {number[]} nums
* @return {number}
*/
var lengthOfLIS = function (nums) {
function dp(i, j) {
if (i === j) return 1
if (i > j) return 0
let res = 1
if (nums[j] > nums[i]) res = 2
let left = nums[i] > nums[i + 1] ? 0 : 1,
right = nums[j] > nums[j - 1] ? 1 : 0
res = Math.max(res, left + dp(i + 1, j), right + dp(i, j - 1))
return res
}
return dp(0, nums.length - 1)
}
/**
* 5. 最长回文子串(暴力递归)
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
function dp(i, j) {
if (i === j) return s[i]
if (j < i) return ''
let cur = s.slice(i, j + 1),
temp = cur.split('').reverse().join('')
if (cur === temp) return cur
let l = dp(i + 1, j),
r = dp(i, j - 1)
return l.length > r.length ? l : r
}
return dp(0, s.length - 1)
}
/**
* 5. 最长回文子串(动态规划)
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
if (s.length === 0) return ''
let len = s.length,
dp = new Array(len)
for (let i = 0; i < len; i++) {
dp[i] = new Array(len)
dp[i][i] = s[i]
}
for (let l = 1; l < len; l++) {
for (let i = 0; i < len - l; i++) {
let j = l + i
let cur = s.slice(i, j + 1),
temp = cur.split('').reverse().join('')
if (cur === temp) {
dp[i][j] = cur
} else {
dp[i][j] =
dp[i + 1][j].length > dp[i][j - 1].length
? dp[i + 1][j]
: dp[i][j - 1]
}
}
}
return dp[0][len - 1]
}
/**
* 3. 无重复字符的最长子串(滑动窗口)
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function (s) {
let hash = {},
left = 0,
right = 0,
len = s.length,
res = 0
while (right < len) {
let char = s[right]
if (!hash.hasOwnProperty(char)) {
res = Math.max(res, right - left + 1)
hash[char] = 1
} else {
while (hash.hasOwnProperty(char)) {
delete hash[s[left]]
left++
}
res = Math.max(res, right - left + 1)
hash[char] = 1
}
right++
}
return res
}
/**
* 32. 最长有效括号(暴力递归)
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function (s) {
function dp(i, j) {
if (i === j) return 0
if (i > j) return 0
let temp = s.slice(i, j + 1),
stack = []
for (let i = 0, len = temp.length; i < len; i++) {
let cur = temp[i]
if (stack[stack.length - 1] === '(' && cur === ')') {
stack.pop()
} else {
stack.push(cur)
}
}
if (stack.length === 0) return j - i + 1
return Math.max(dp(i + 1, j), dp(i, j - 1))
}
return dp(0, s.length - 1)
}
/**
* 236. 二叉树的最近公共祖先
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function (root, p, q) {
if (!root) return null
if (p === q) return p
if (root === q || root === p) return root
let l = lowestCommonAncestor(root.left, p, q),
r = lowestCommonAncestor(root.right, p, q)
if (l && r) return root
return l ? l : r
}
/**
* 169. 多数元素(摩尔投票)
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function (nums) {
let count = 0,
res
for (let i = 0, len = nums.length; i < len; i++) {
if (count === 0) {
res = nums[i]
count++
} else {
count += res === nums[i] ? 1 : -1
}
}
return res
}
/**
* 104. 二叉树的最大深度
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function (root) {
function dfs(node) {
if (!node) return 0
return 1 + Math.max(dfs(node.left), dfs(node.right))
}
return dfs(root)
}
/**
* 139. 单词拆分(暴力递归)
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function (s, wordDict) {
let len = s.length
function dp(i, j) {
let str = s.slice(i, j + 1),
res = false
if (!str) return true
if (j > len - 1) return false
if (wordDict.indexOf(str) !== -1) res = res || dp(j + 1, j + 1)
res = res || dp(i, j + 1)
return res
}
return dp(0, 0)
}
/**
* 62. 不同路径(暴力递归)
* @param {number} m
* @param {number} n
* @return {number}
*/
var uniquePaths = function (m, n) {
function dp(i, j) {
if (i >= m || j >= n) return 0
if (i === m - 1 && j === n - 1) return 1
return dp(i + 1, j) + dp(i, j + 1)
}
return dp(0, 0)
}
/**
* 42. 接雨水(双指针)
* @param {number[]} height
* @return {number}
*/
var trap = function (height) {
let left = 0,
right = height.length - 1,
res = 0
let l = height[left],
r = height[right]
while (left < right - 1) {
if (l <= r) {
let temp = height[left + 1]
res += temp < l ? l - temp : 0
l = Math.max(l, temp)
left++
} else {
let temp = height[right - 1]
res += temp < r ? r - temp : 0
r = Math.max(r, temp)
right--
}
}
return res
}
/**
* 494. 目标和(暴力递归)
* @param {number[]} nums
* @param {number} S
* @return {number}
*/
var findTargetSumWays = function (nums, S) {
let len = nums.length
function dp(count, i) {
if (i === len) return count === S ? 1 : 0
return dp(count + nums[i], i + 1) + dp(count - nums[i], i + 1)
}
return dp(0, 0)
}
/**
* 101. 对称二叉树
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function (root) {
if (!root) return true
function isSym(node1, node2) {
if (!node1 && !node2) return true
if (!node1 || !node2) return false
if (node1.val !== node2.val) return false
return isSym(node1.left, node2.right) && isSym(node1.right, node2.left)
}
return isSym(root.left, root.right)
}
/**
* 78. 子集(回溯法)
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function (nums) {
let res = []
function backtrack(has, rest) {
res.push(has)
for (let i = 0, len = rest.length; i < len; i++) {
backtrack([...has, rest[i]], rest.slice(i + 1))
}
}
backtrack([], nums)
return res
}
/**
* 78. 子集(回溯法优化)
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function (nums) {
let res = [],
len = nums.length
function backtrack(has, start) {
res.push(has)
for (let i = start; i < len; i++) {
backtrack([...has, nums[i]], i + 1)
}
}
backtrack([], 0)
return res
}
/**
* 560. 和为K的子数组(暴力循环)
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var subarraySum = function (nums, k) {
let res = 0
for (let i = 0, len = nums.length; i < len; i++) {
let count = nums[i]
if (count === k) res++
for (let j = i + 1; j < len; j++) {
count += nums[j]
if (count === k) res++
}
}
return res
}
/**
* 53. 最大子序和(暴力递归)
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function (nums) {
let sum = 0
for (let i = 0, len = nums.length; i < len; i++) sum += nums[i]
function dp(i, j, sum) {
if (i === j) return sum
return Math.max(
sum,
dp(i + 1, j, sum - nums[i]),
dp(i, j - 1, sum - nums[j])
)
}
return dp(0, nums.length - 1, sum)
}
/**
* 53. 最大子序和(动态规划)
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function (nums) {
if (nums.length === 0) return 0
let len = nums.length,
res = Number.MIN_SAFE_INTEGER,
prev = 0
for (let i = 0; i < len; i++) {
prev = Math.max(prev + nums[i], nums[i])
res = Math.max(res, prev)
}
return res
}
/**
* 416. Partition Equal Subset Sum(dynamic planning)
* @param {number[]} nums
* @return {boolean}
*/
var canPartition = function (nums) {
let sum = 0,
len = nums.length
for (let i = 0; i < len; i++) sum += nums[i]
if (sum % 2 !== 0) return false
let half = sum / 2,
dp = new Array(half + 1)
dp.fill(false)
dp[0] = true
for (let i = 0; i < len; i++) {
for (let j = half; j >= nums[i]; j--) {
dp[j] = dp[j] || dp[j - nums[i]]
}
}
return dp[half]
}
/**
* 31. 下一个排列
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var maxProduct = function (nums) {
let len = nums.length,
dp = new Array(len),
res = Number.MIN_SAFE_INTEGER
for (let i = 0; i < len; i++) {
dp[i] = new Array(len)
dp[i][i] = nums[i]
res = Math.max(res, dp[i][i])
}
for (let l = 1; l < len; l++) {
for (let i = 0; i < len - l; i++) {
let j = l + i
dp[i][j] = nums[j] * dp[i][j - 1]
res = Math.max(res, dp[i][j])
}
}
}
/**
* 152. 乘积最大子序列(动态规划)
* @param {number[]} nums
* @return {number}
*/
var maxProduct = function (nums) {
let res = Number.MIN_SAFE_INTEGER,
max = 1,
min = 1
for (let i = 0, len = nums.length; i < len; i++) {
if (nums[i] < 0) {
let temp = max
max = min
min = temp
}
max = Math.max(nums[i], max * nums[i])
min = Math.min(nums[i], min * nums[i])
res = Math.max(res, max)
}
return res
}
/**
* 617. 合并二叉树
* @param {TreeNode} t1
* @param {TreeNode} t2
* @return {TreeNode}
*/
var mergeTrees = function (t1, t2) {
if (!t1 || !t2) return t1 ? t1 : t2
t1.val = t1.val + t2.val
t1.left = mergeTrees(t1.left, t2.left)
t1.right = mergeTrees(t1.right, t2.right)
return t1
}
/**
* 96. 不同的二叉搜索树(动态规划)
* @param {number} n
* @return {number}
*/
var numTrees = function (n) {
let dp = new Array(n + 1)
dp.fill(0)
dp[0] = 1
dp[1] = 1
for (let i = 2; i <= n; i++) {
for (let j = 0; j < i; j++) {
dp[i] += dp[j] * dp[i - j - 1]
}
}
return dp[n]
}
/**
* 283. 移动零(双指针)
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
let p1 = 0,
len = nums.length
while (nums[p1] !== 0 && p1 < len) p1++
let p2 = p1 + 1
while (p2 < len) {
if (nums[p2] !== 0) {
;[nums[p1], nums[p2]] = [nums[p2], nums[p1]]
p1++
}
p2++
}
}
/**
* 234. 回文链表
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function (head) {
let arr = []
while (head) {
arr.push(head.val)
head = head.next
}
for (let i = 0, len = arr.length; i < Math.floor(len / 2); i++) {
if (arr[i] !== arr[len - 1 - i]) return false
}
return true
}
/**
* 647. 回文子串(滑动窗口)
* @param {string} s
* @return {number}
*/
var countSubstrings = function (s) {
let l = 0,
r = 0,
len = s.length,
res = 0
while (r < len) {
let cur = s.slice(l, r + 1)
if (cur.split('').reverse().join('') === cur) res++
let count = l
while (count < r) {
count++
let cur = s.slice(count, r + 1)
if (cur.split('').reverse().join('') === cur) res++
}
r++
}
return res
}
/**
* 647. 回文子串(中心法则)
* @param {string} s
* @return {number}
*/
var countSubstrings = function (s) {
let len = s.length,
res = 0
for (let i = 0, c = 2 * len - 1; i < c; i++) {
let l = Math.floor(i / 2),
r = l + (i % 2)
while (l >= 0 && l < len && s[l] === s[r]) {
l--
r++
res++
}
}
return res
}
/**
* 238. 除自身以外数组的乘积
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function (nums) {
let res = [],
len = nums.length
let lMul = new Array(len),
rMul = new Array(len)
;(lMul[0] = 1), (rMul[len - 1] = 1)
for (let i = 1; i < len; i++) {
lMul[i] = lMul[i - 1] * nums[i - 1]
}
res[len - 1] = lMul[len - 1] * rMul[len - 1]
for (let j = len - 2; j >= 0; j--) {
rMul[j] = rMul[j + 1] * nums[j + 1]
res[j] = rMul[j] * lMul[j]
}
return res
}
/**
* 416. 分割等和子集(动态规划)
* @param {number[]} nums
* @return {boolean}
*/
var canPartition = function (nums) {
let sum = 0,
len = nums.length
for (let i = 0; i < len; i++) sum += nums[i]
if (sum % 2 !== 0) return false
let half = sum / 2,
dp = new Array(half + 1)
dp.fill(false)
dp[0] = true
for (let i = 0; i < len; i++) {
for (let j = half; j >= nums[i]; j--) {
dp[j] = dp[j] || dp[j - nums[i]]
}
}
return dp[half]
}
/**
* 279. 完全平方数(动态规划)
* @param {number} n
* @return {number}
*/
var numSquares = function (n) {
let squares = []
function isSquares(num) {
for (let i = 1; i <= num; i++) {
if (i * i === num) {
squares.push(num)
return
} else if (i * i > num) return
}
}
for (let i = 1; i <= n; i++) {
isSquares(i)
}
let dp = new Array(n + 1)
dp.fill(-1)
dp[0] = 0
for (let i = 1; i <= n; i++) {
for (let j = 0, len = squares.length; j < len; j++) {
if (i - squares[j] >= 0) {
if (dp[i - squares[j]] !== -1) {
dp[i] =
dp[i] === -1
? 1 + dp[i - squares[j]]
: Math.min(dp[i], 1 + dp[i - squares[j]])
}
}
}
}
return dp[n]
}
/**
* 279. 完全平方数(动态规划)
* @param {number} n
* @return {number}
*/
var numSquares = function (n) {
let dp = new Array(n + 1)
dp.fill(-1)
dp[0] = 0
for (let i = 1; i <= n; i++) {
let j = 1
while (i >= j * j) {
dp[i] =
dp[i] === -1 ? 1 + dp[i - j * j] : Math.min(dp[i], 1 + dp[i - j * j])
j++
}
}
return dp[n]
}
/**
* 10. 正则表达式匹配(暴力递归)
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function (s, p) {
function dp(i, j) {
if (i < 0 && j < 0) return true
if (j < 0) return false
if (i < 0) {
while (j >= 0) {
if (p[j] !== '*') {
return false
}
j -= 2
}
return true
}
let charS = s[i],
charP = p[j]
if (charP === '.' || charS === charP) {
return dp(i - 1, j - 1)
} else if (charP === '*') {
if (p[j - 1] === charS || p[j - 1] === '.')
return dp(i - 1, j) || dp(i - 1, j - 2) || dp(i, j - 2)
return dp(i, j - 2)
} else {
return false
}
}
return dp(s.length - 1, p.length - 1)
}
/**
* 301. 删除无效的括号(暴力递归)
* @param {string} s
* @return {string[]}
*/
var removeInvalidParentheses = function (s) {
let all = [],
max = 0
function dp(brackets) {
let stack = []
for (let i = 0, len = brackets.length; i < len; i++) {
if (brackets[i] === '(' || brackets[i] === ')') {
if (brackets[i] === ')' && stack[stack.length - 1] === '(') {
stack.pop()
} else {
stack.push(brackets[i])
}
}
}
if (stack.length === 0) {
if (all.indexOf(brackets) === -1) {
all.push(brackets)
max = Math.max(max, brackets.length)
}
}
for (let i = 0, len = brackets.length; i < len; i++) {
dp(brackets.slice(0, i) + brackets.slice(i + 1))
}
}
dp(s)
let res = []
for (let i = 0, len = all.length; i < len; i++) {
if (all[i].length === max) res.push(all[i])
}
return res
}
/**
* 301. 删除无效的括号(bfs)
* @param {string} s
* @return {string[]}
*/
var removeInvalidParentheses = function (s) {
let queue = [s]
while (queue.length) {
let res = queue.filter(isValid)
if (res.length > 0) return [...new Set(res)]
let temp = []
for (let i = 0, len1 = queue.length; i < len1; i++) {
for (let j = 0, len2 = queue[i].length; j < len2; j++) {
if (queue[i][j] === '(' || queue[i][j] === ')')
temp.push(queue[i].slice(0, j) + queue[i].slice(j + 1))
}
}
queue = temp
}
function isValid(brackets) {
let count = 0,
len = brackets.length
for (let i = 0; i < len; i++) {
if (brackets[i] === '(') {
count++
} else if (brackets[i] === ')') {
count--
}
if (count < 0) return false
}
return count === 0
}
}
/**
* 136. 只出现一次的数字(异或)
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function (nums) {
let a = 0
for (let i = 0, len = nums.length; i < len; i++) {
a ^= nums[i]
}
return a
}
/**
* 1356. 根据数字二进制下 1 的数目排序(位运算)
* @param {number[]} arr
* @return {number[]}
*/
var sortByBits = function (arr) {
function compare(n1, n2) {
let count1 = 0,
count2 = 0,
temp = n1 - n2
for (let i = 32; i > 0; i--) {
if ((n1 & 1) === 1) count1++
if ((n2 & 1) === 1) count2++
n1 >>= 1
n2 >>= 1
}
return count1 - count2 || temp
}
arr.sort(compare)
return arr
}
/**
* 762. 二进制表示中质数个计算置位(位运算)
* @param {number} L
* @param {number} R
* @return {number}
*/
var countPrimeSetBits = function (L, R) {
const prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
let res = 0
function countOne(n) {
let count = 0
for (let i = 32; i > 0; i--) {
if ((n & 1) === 1) count++
n >>= 1
}
return count
}
for (let i = L; i <= R; i++) {
if (prime.indexOf(countOne(i)) !== -1) res++
}
return res
}
/**
* 268. 缺失数字(异或)
* @param {number[]} nums
* @return {number}
*/
var missingNumber = function (nums) {
let ans = 0
for (let i = 0, len = nums.length; i < len; i++) {
ans ^= nums[i]
ans ^= i
}
ans ^= nums.length
return ans
}
/**
* 98. 验证二叉搜索树(中序遍历)
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function (root) {
let temp = Number.MIN_SAFE_INTEGER,
res = true
function mfs(node) {
if (!node) return
mfs(node.left)
if (node.val > temp) {
temp = node.val
} else {
res = false
return
}
mfs(node.right)
}
mfs(root)
return res
}
/**
* 62. 不同路径(动态规划)
* @param {number} m
* @param {number} n
* @return {number}
*/
var uniquePaths = function (m, n) {
let dp = new Array(m + 1)
for (let i = 0; i <= m; i++) {
dp[i] = new Array(n + 1)
dp[i][n] = 0
}
dp[m].fill(0)
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
if (i === m - 1 && j === n - 1) {
dp[i][j] = 1
} else {
dp[i][j] = dp[i + 1][j] + dp[i][j + 1]
}
}
}
return dp[0][0]
}
/**
* 75. 颜色分类(双指针)
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var sortColors = function (nums) {
let l = 0,
len = nums.length,
r = len - 1
for (let i = 0; i <= r; i++) {
if (nums[i] === 2) {
;[nums[i], nums[r]] = [nums[r], nums[i]]
r--
i--
} else if (nums[i] === 0) {
;[nums[i], nums[l]] = [nums[l], nums[i]]
l++
}
}
}
/**
* 297. 二叉树的序列化与反序列化
* Encodes a tree to a single string.
*
* @param {TreeNode} root
* @return {string}
*/
var serialize = function (root) {
const nodes = [],
queue = [root]
while (queue.length) {
let cur = queue.shift()
if (cur) {
nodes.push(cur.val)
queue.push(cur.left, cur.right)
} else {
nodes.push(null)
}
}
while (nodes.length && nodes[nodes.length - 1] === null) nodes.pop()
let res = '['
for (let i = 0, len = nodes.length; i < len; i++) {
res += nodes[i] + ','
}
res = res.slice(0, res.length - 1)
return res + ']'
}
/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function (data) {
data = data.slice(1, data.length - 1)
if (!data) return null
data = data.split(',')
let i = 1,
len = data.length,
root = new TreeNode(data[0]),
queue = [root]
while (i < len && queue.length) {
let left = i < len ? data[i++] : 'null'
let right = i < len ? data[i++] : 'null'
let node = queue.shift()
if (left !== 'null') {
node.left = new TreeNode(left)
queue.push(node.left)
}
if (right !== 'null') {
node.right = new TreeNode(right)
queue.push(node.right)
}
}
return root
}
/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/
/**
* 19. 删除链表的倒数第N个节点
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function (head, n) {
let dummy = new ListNode(null)
dummy.next = head
let len = 0
while (head) {
len++
head = head.next
}
let count = len - n,
p = dummy
while (count > 0) {
count--
p = p.next
}
p.next = p.next.next
return dummy.next
}
/**
* 19. 删除链表的倒数第N个节点(遍历一遍)
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function (head, n) {
let dummy = new ListNode(null)
dummy.next = head
let p = dummy
while (n > 0) {
n--
head = head.next
}
while (head) {
head = head.next
p = p.next
}
p.next = p.next.next
return dummy.next
}
/**
* 32. 最长有效括号(暴力循环)
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function (s) {
let res = 0
for (let i = 0, len = s.length; i < len; i++) {
let count = s[i] === '(' ? 1 : -1
for (let j = i + 1; j < len; j++) {
if (count < 0) break
if (s[j] === '(') {
count++
} else {
count--
}
if (count === 0) res = Math.max(res, j - i + 1)
}
}
return res
}
/**
* 84. 柱状图中最大的矩形(暴力循环)
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function (heights) {
let res = 0
for (let i = 0, len = heights.length; i < len; i++) {
let min = heights[i]
res = Math.max(res, min)
for (let j = i + 1; j < len; j++) {
min = Math.min(min, heights[j])
res = Math.max(res, (j - i + 1) * min)
}
}
return res
}
/**
* 461. 汉明距离(位运算)
* @param {number} x
* @param {number} y
* @return {number}
*/
var hammingDistance = function (x, y) {
let z = x ^ y,
res = 0
for (let i = 32; i > 0; i--) {
if ((z & 1) === 1) res++
z >>= 1
}
return res
}
/**
* 105. 从前序与中序遍历序列构造二叉树
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function (preorder, inorder) {
if (preorder.length === 0) return null
let cur = preorder[0],
index = inorder.indexOf(cur)
let tree = new TreeNode(cur)
let preLeft = preorder.slice(1, index + 1),
preRight = preorder.slice(index + 1)
let inLeft = inorder.slice(0, index),
inRight = inorder.slice(index + 1)
tree.left = buildTree(preLeft, inLeft)
tree.right = buildTree(preRight, inRight)
return tree
}
/**
* 739. 每日温度(单调栈)
* @param {number[]} T
* @return {number[]}
*/
var dailyTemperatures = function (T) {
let stack = [],
res = []
for (let i = 0, len = T.length; i < len; i++) {
while (stack.length !== 0 && T[stack[stack.length - 1]] < T[i]) {
let cur = stack.pop()
res[cur] = i - cur
}
stack.push(i)
}
for (let i = 0, len = stack.length; i < len; i++) res[stack[i]] = 0
return res
}
/**
* 1019. 链表中的下一个更大节点(单调栈)
* @param {ListNode} head
* @return {number[]}
*/
var nextLargerNodes = function (head) {
let stack = [],
res = [],
count = 0
while (head) {
while (stack.length > 0 && stack[stack.length - 1].val < head.val) {
let temp = stack.pop()
res[temp.key] = head.val
}
stack.push({ key: count, val: head.val })
count++
head = head.next
}
for (let i = 0, len = stack.length; i < len; i++) res[stack[i].key] = 0
return res
}
/**
* 312. 戳气球(备忘录)
* @param {number[]} nums
* @return {number}
*/
var maxCoins = function (nums) {
let hash = {}
function dp(nums) {
let len = nums.length
if (len === 0) return 0
if (len === 1) return nums[0]
let res = 0
for (let i = 0; i < len; i++) {
let l = i === 0 ? 1 : nums[i - 1],
r = i === len - 1 ? 1 : nums[i + 1]
let arr = nums.slice(0, i).concat(nums.slice(i + 1))
if (!hash.hasOwnProperty(arr.toString())) {
hash[arr.toString()] = dp(arr)
}
res = Math.max(res, l * r * nums[i] + hash[arr.toString()])
}
return res
}
return dp(nums)
}
/**
* 415. 字符串相加
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = function (num1, num2) {
let i = num1.length - 1,
j = num2.length - 1
let ans = ''
let pre = 0
while (i >= 0 || j >= 0 || pre) {
let n1 = i >= 0 ? +num1[i--] : 0
let n2 = j >= 0 ? +num2[j--] : 0
let sum = n1 + n2 + pre
ans = (sum % 10) + ans
pre = Math.floor(sum / 10)
}
return ans
}
/**
* 22. 括号生成
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function (n) {
const ans = []
function dp(l, r, str) {
if (l === n && r === n) ans.push(str)
if (r > l || l > n || r > n) return
dp(l + 1, r, str + '(')
dp(l, r + 1, str + ')')
}
dp(0, 0, '')
return ans
}
/**
* 1232. 缀点成线
* @param {number[][]} coordinates
* @return {boolean}
*/
var checkStraightLine = function (coordinates) {
const slope =
(coordinates[1][1] - coordinates[0][1]) /
(coordinates[1][0] - coordinates[0][0])
for (let i = 1, len = coordinates.length; i < len - 1; i++) {
if (
(coordinates[i + 1][1] - coordinates[i][1]) /
(coordinates[i + 1][0] - coordinates[i][0]) !==
slope
)
return false
}
return true
}
/**
* LCP 07. 传递信息
* @param {number} n
* @param {number[][]} relation
* @param {number} k
* @return {number}
*/
var numWays = function (n, relation, k) {
function dfs(cur, times) {
if (cur === n - 1 && times === 0) return 1
if (times < 0) return 0
let res = 0
for (let i = 0, len = relation.length; i < len; i++) {
if (relation[i][0] === cur) res += dfs(relation[i][1], times - 1)
}
return res
}
return dfs(0, k)
}
/**
* 43. 字符串相乘
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var multiply = function (num1, num2) {
if (num1 === '0' || num2 === '0') return '0'
let ans = '',
prev = ''
for (let i = 0, len = num1.length; i < len; i++) {
ans = add(mul(num2, num1[i]), ans + prev)
prev = '0'
}
return ans
}
function mul(str, n) {
let ans = '',
prev = 0
for (let i = str.length - 1; i >= 0; i--) {
const temp = str[i] * n + prev
prev = Math.floor(temp / 10)
ans = (temp % 10) + ans
}
if (prev) ans = prev + ans
return ans
}
function add(str1, str2) {
let ans = '',
prev = 0,
i = str1.length - 1,
j = str2.length - 1
while (i >= 0 || j >= 0 || prev) {
const a = i >= 0 ? +str1[i--] : 0
const b = j >= 0 ? +str2[j--] : 0
const temp = a + b + prev
ans = (temp % 10) + ans
prev = Math.floor(temp / 10)
}
return ans
}
/**
* 829. 连续整数求和
* @param {number} N
* @return {number}
*/
var consecutiveNumbersSum = function (N) {
N *= 2
let n = 1,
res = 0
while (n * n < N) {
if (N % n === 0 && (n % 2 || (N / n) % 2)) res++
n++
}
return res
}
<file_sep>/**
* 206.反转链表
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
let prev = null
while (head) {
let temp = head.next
head.next = prev
prev = head
head = temp
}
return head
}
/**
* 203.移除链表元素
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function (head, val) {
while (head && head.val === val) {
head = head.next
}
if (!head) return head
let prev = head
while (prev.next) {
if (prev.next === val) {
prev.next = prev.next.next
} else {
prev = prev.next
}
}
return head
}
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* 83.删除排序链表中的重复元素
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function (head) {
if (!head) return head
let prev = head
while (prev.next) {
if (prev.val === prev.next.val) {
prev.next = prev.next.next
} else {
prev = prev.next
}
}
return head
}
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* 876.链表的中间节点
* @param {ListNode} head
* @return {ListNode}
*/
var middleNode = function (head) {
let fast = head,
low = head
while (fast && fast.next) {
fast = fast.next.next ? fast.next.next : fast.next
low = low.next
}
return low
}
/**
* 160.相交链表(方法一)
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function (headA, headB) {
let pointerA = headA,
pointerB = headB
while (pointerB) {
while (pointerA) {
if (pointerA === pointerB) {
return pointerA
}
pointerA = pointerA.next
}
pointerA = headA
pointerB = pointerB.next
}
return null
}
/**
* 160.相交链表(方法二)
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function (headA, headB) {
let pointerA = headA,
pointerB = headB,
x = new WeakSet()
while (pointerA) {
x.add(pointerA)
pointerA = pointerA.next
}
while (pointerB) {
if (x.has(pointerB)) return pointerB
pointerB = pointerB.next
}
return null
}
/**
* 141.环形链表(哈希表)
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
const x = new WeakSet()
while (head) {
if (x.has(head)) return true
x.add(head)
head = head.next
}
return false
}
/**
* 141.环形链表(快慢指针)
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
let s = head,
f = head
while (f) {
s = s.next
f = f.next ? f.next.next : f.next
if (s && s === f) return true
}
return false
}
/**
* 328.奇偶链表
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var oddEvenList = function (head) {
if (!head) return null
let odd = head,
even = head.next,
list = even
while (even && even.next) {
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
}
odd.next = list
return head
}
/**
* 21. 合并两个有序链表
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
let result = new ListNode(null),
dummy = result
while (l1 && l2) {
if ((l1 && l2 && l1.val <= l2.val) || (l1 && !l2)) {
result.next = new ListNode(l1.val)
result = result.next
l1 = l1.next
} else if ((l1 && l2 && l2.val < l1.val) || (!l1 && l2)) {
result.next = new ListNode(l2.val)
result = result.next
l2 = l2.next
}
}
result.next = l1 ? l1 : l2
return dummy.next
}
/**
* 147. 对链表进行插入排序
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
var insertionSortList = function (head) {
let dummy = new ListNode(null)
dummy.next = head
while (head && head.next) {
let prev = dummy,
i = 0
while (prev.next !== head.next) {
if (prev.next.val > head.next.val) {
let temp = head.next
head.next = head.next.next
temp.next = prev.next
prev.next = temp
i++
break
} else {
prev = prev.next
}
}
if (i) continue
head = head.next
}
return dummy.next
}
/**
* 143.重排链表
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderList = function (head) {
while (head && head.next && head.next) {
let penult = getPenult(head)
let last = penult.next
penult.next = null
last.next = head.next
head.next = last
head = head.next.next
}
function getPenult(l) {
while (l && l.next && l.next.next) {
l = l.next
}
return l
}
}
/**
* 143.重排链表
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderList = function (head) {
if (!head || !head.next) return
let fast = head,
low = head
while (fast && fast.next) {
low = low.next
fast = fast.next.next ? fast.next.next : fast.next
}
let last = low.next
low.next = null
let prev = null
while (last) {
let head = last.next
last.next = prev
prev = last
last = head
}
while (prev) {
let temp = prev
prev = prev.next
temp.next = head.next
head.next = temp
head = head.next.next
}
}
/**
* 61. 旋转链表
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var rotateRight = function (head, k) {
if (!head || !head.next) return head
//求出链表的长度
let len = 0
let p = head
while (p) {
len++
p = p.next
}
//长度与k求余,值为旋转的位置
let offset = k % len
if (!offset) return head
//找出链表索引为(len-k)的节点
let rest = head
while (len - offset > 1) {
rest = rest.next
offset++
}
let temp = rest.next
rest.next = null
let last = temp
while (last && last.next) {
last = last.next
}
last.next = head
head = temp
return head
}
/**
* 61. 旋转链表
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var rotateRight = function (head, k) {
if (!head || !head.next) return head
let p = head,
len = 1
while (p && p.next) {
len++
p = p.next
}
p.next = head
let offset = len - (k % len)
let prev = null
while (offset > 0) {
prev = head
head = head.next
offset--
}
prev.next = null
return head
}
/**
* 24. 两两交换链表中的节点
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function (head) {
let dummy = new ListNode(null)
dummy.next = head
let prev = dummy
while (head && head.next) {
let temp = head.next
head.next = head.next.next
temp.next = head
prev.next = temp
prev = head
head = head.next
}
return dummy.next
}
/**
* 2. 两数相加
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function (l1, l2) {
const dummy = new ListNode(null)
let prev = 0
let p = dummy
while (l1 || l2 || prev) {
const val_1 = l1 ? l1.val : 0
const val_2 = l2 ? l2.val : 0
const sum = val_1 + val_2 + prev
p.next = new ListNode(sum % 10)
prev = Math.floor(sum / 10)
p = p.next
l1 = l1 ? l1.next : l1
l2 = l2 ? l2.next : l2
}
return dummy.next
}
/**
* 109. 有序链表转换二叉搜索树
* @param {ListNode} head
* @return {TreeNode}
*/
var sortedListToBST = function (head) {
let list = []
while (head) {
list.push(head.val)
head = head.next
}
let root = null
if (!list.length) return root
let mid = Math.floor(list.length / 2)
root = new TreeNode(list[mid])
function slb(root, left, right) {
if (!left.length && !right.length) return
let midL = Math.floor(left.length / 2),
midR = Math.floor(right.length / 2)
if (left[midL] !== undefined) {
root.left = new TreeNode(left[midL])
slb(root.left, left.slice(0, midL), left.slice(midL + 1))
}
if (right[midR] !== undefined) {
root.right = new TreeNode(right[midR])
slb(root.right, right.slice(0, midR), right.slice(midR + 1))
}
}
slb(root, list.slice(0, mid), list.slice(mid + 1))
return root
}
/**
* 25. K 个一组翻转链表
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var reverseKGroup = function (head, k) {
if (k === 1) return head
let dummy = new ListNode(null)
dummy.next = head
let p = dummy
while (p.next) {
let count = k,
list = []
while (head && count) {
list.push(head.val)
count--
if (count === 0) break
head = head.next
}
if (count) break
let temp = null,
dummyTemp = new ListNode(null)
for (let i = k - 1; i >= 0; i--) {
if (!temp) {
temp = new ListNode(list[i])
dummyTemp.next = temp
continue
}
temp.next = new ListNode(list[i])
temp = temp.next
}
if (!head) break
temp.next = head.next
p.next = dummyTemp.next
p = temp
head = temp.next
}
return dummy.next
}
/**
* 160. 相交链表
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function (headA, headB) {
if (!headA || !headB) return null
let pA = headA,
pB = headB
while (pA != pB) {
pA = pA == null ? headB : pA.next
pB = pB == null ? headA : pB.next
}
return pA
}
/**
* 面试题24. 反转链表
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
let prev = null
while (head) {
let temp = head
head = head.next
temp.next = prev
prev = temp
}
return prev
}
/**
* 92. 反转链表 II
* @param {ListNode} head
* @param {number} m
* @param {number} n
* @return {ListNode}
*/
var reverseBetween = function (head, m, n) {
if (!head) return null
let count = 1,
dummy = new ListNode(null)
dummy.next = head
let p = dummy,
rev = null,
last = null
while (head) {
if (count > n) {
p.next = rev
last.next = head
return dummy.next
}
if (count >= m) {
let temp = head
head = head.next
count++
temp.next = rev
rev = temp
if (count - 1 === m) {
last = rev
}
continue
}
p = p.next
head = head.next
count++
}
p.next = rev
return dummy.next
}
let root = {
val: 3,
left: { val: 9, left: null, right: null },
right: { val: 20, left: null, right: null },
}
var levelOrder = function (root) {
if (!root) return []
let res = [],
queue = [root, 'ok']
while (queue.length) {
let cur = queue.shift()
if (cur.left) {
queue.push(cur.left)
}
if (cur.right) {
queue.push(cur.right)
}
}
return res
}
/**
* 21. 合并两个有序链表(空间O(1))
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
if (!l1 || !l2) return l1 ? l1 : l2
let p = new ListNode(null),
dummy = p
while (l1 && l2) {
if (l1.val < l2.val) {
p.next = l1
p = l1
l1 = l1.next
} else {
p.next = l2
p = l2
l2 = l2.next
}
}
p.next = l1 ? l1 : l2
return dummy.next
}
/**
* 21. 合并两个有序链表(递归,空间O(1))
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
if (!l1 || !l2) return l1 ? l1 : l2
if (l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2)
} else {
l2.next = mergeTwoLists(l1, l2.next)
l1 = l2
}
return l1
}
/**
* 142. 环形链表 II
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function (head) {
let f = head
let s = head
while (f) {
f = f.next ? f.next.next : f.next
s = s.next
if (s && s === f) {
while (head !== s) {
s = s.next
head = head.next
}
return head
}
}
return null
}
<file_sep>/**
* 1046. 最后一块石头的重量(大顶堆)
* @param {number[]} stones
* @return {number}
*/
var lastStoneWeight = function(stones) {
//解题思路:大顶堆
let heap = [null]
//初始化堆
for (let i = 0, len = stones.length; i < len; i++) {
insert(stones[i])
}
// 插入
function insert(val) {
heap.push(val)
let i = heap.length - 1,
p = Math.floor(i / 2)
while (i > 1) {
if (heap[i] <= heap[p]) return
;[heap[i], heap[p]] = [heap[p], heap[i]]
i = p
p = Math.floor(i / 2)
}
}
//取出堆顶
function getTop() {
let res = heap[1]
heap[1] = heap[heap.length - 1]
heap.pop()
//维持大顶堆
let i = 1
while (i * 2 < heap.length) {
let cur = heap[i],
left = heap[i * 2],
right = heap[i * 2 + 1]
if (cur >= left && (right === undefined || cur >= right)) return res
if (left >= cur && (right === undefined || left >= right)) {
;[heap[i], heap[i * 2]] = [left, cur]
i = i * 2
} else if (right !== undefined && right >= left && right >= cur) {
;[heap[i], heap[i * 2 + 1]] = [right, cur]
i = i * 2 + 1
}
}
return res
}
//循环数组,直到数组长度为0或1
while (heap.length > 2) {
let y = getTop(),
x = getTop()
if (x === y) continue
insert(y - x)
}
return heap.length === 1 ? 0 : heap[1]
}
/**
* 347. 前 K 个高频元素(小顶堆)
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var topKFrequent = function(nums, k) {
//使用哈希表获取每个数字出现的频率
//这里应该用Map,懒得改了
let obj = {}
for (let i = 0, len = nums.length; i < len; i++) {
if (!obj.hasOwnProperty(nums[i])) {
obj[nums[i]] = 1
continue
}
obj[nums[i]]++
}
//维护一个长度为k的小顶堆
let keys = Object.keys(obj),
heap = [null]
for (let i = 0, len = keys.length; i < len; i++) {
if (i < k) {
insert(keys[i])
} else {
compare(keys[i])
}
function insert(key) {
heap.push(key)
let i = heap.length - 1,
p = Math.floor(i / 2)
while (i > 1) {
if (obj[heap[i]] >= obj[heap[p]]) break
;[heap[i], heap[p]] = [heap[p], heap[i]]
i = p
p = Math.floor(i / 2)
}
}
function compare(key) {
if (obj[key] <= obj[heap[1]]) return
heap[1] = key
let i = 1
while (i * 2 < heap.length) {
let left = heap[i * 2],
right = heap[i * 2 + 1]
if (
obj[key] <= obj[left] &&
(right === undefined || obj[key] <= obj[right])
)
break
if (
obj[left] <= obj[key] &&
(right === undefined || obj[left] <= obj[right])
) {
;[heap[i * 2], heap[i]] = [heap[i], heap[i * 2]]
i = i * 2
} else if (
right !== undefined &&
obj[right] <= obj[key] &&
obj[right] <= obj[left]
) {
;[heap[i * 2 + 1], heap[i]] = [heap[i], heap[i * 2 + 1]]
i = i * 2 + 1
}
}
}
}
heap.shift()
return heap.map(item => +item)
}
/**
* 378. 有序矩阵中第K小的元素(大顶堆)
* @param {number[][]} matrix
* @param {number} k
* @return {number}
*/
var kthSmallest = function(matrix, k) {
let heap = [null]
//维持一个大顶堆
function insert(val, k) {
if (heap.length - 1 < k) {
//堆中元素数量小于k,继续插入
heap.push(val)
let i = heap.length - 1
while (i > 1) {
let p = Math.floor(i / 2)
if (val <= heap[p]) return
;[heap[i], heap[p]] = [heap[p], heap[i]]
i = p
}
} else {
//堆中元素大于等于k,要插入的值与堆顶比较
//如果大于不做处理,小于则替换掉堆顶
if (heap[1] <= val) return
heap[1] = val
let i = 1
while (i * 2 < heap.length) {
let left = heap[i * 2],
right = heap[i * 2 + 1]
if (val >= left && (right === undefined || val >= right)) return
if (left > val && (right === undefined || left >= right)) {
;[heap[i * 2], heap[i]] = [heap[i], heap[i * 2]]
i = i * 2
} else if (right !== undefined && right >= left && right > val) {
;[heap[i * 2 + 1], heap[i]] = [heap[i], heap[i * 2 + 1]]
i = i * 2 + 1
}
}
}
}
for (let i = 0, len = matrix.length; i < len; i++) {
for (let j = 0; j < len; j++) {
insert(matrix[i][j], k)
}
}
return heap[1]
}
/**
* 480. 滑动窗口中位数(排序超时)
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var medianSlidingWindow = function(nums, k) {
let temp = [],
res = [],
left = 0,
right = 0
if (!k) return res
while (right < nums.length) {
temp.push(nums[right])
if (temp.length >= k) {
if (temp.length > k) {
temp.shift()
}
let arr = [...temp]
arr.sort((a, b) => a - b)
if (k % 2 === 0) {
res.push((arr[Math.floor((k - 1) / 2)] + arr[k / 2]) / 2)
} else {
res.push(arr[Math.floor(k / 2)])
}
}
right++
}
return res
}
/**
* 23. 合并K个排序链表(多路归并)
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
const minHeap = [null],
dummy = new ListNode(null)
let p = dummy
for (let i = 0, len = lists.length; i < len; i++) {
insert(lists[i], minHeap)
}
while (minHeap.length > 1) {
let l = delTop(minHeap)
p.next = new ListNode(l.val)
p = p.next
if (l.next) insert(l.next, minHeap)
}
//向堆中插入链表
function insert(node, heap) {
if (!node) return
heap.push(node)
let i = heap.length - 1
while (i > 1) {
let p = Math.floor(i / 2)
if (node.val >= heap[p].val) return
;[heap[i], heap[p]] = [heap[p], heap[i]]
i = p
}
}
//删除堆顶元素
function delTop(heap) {
if (heap.length <= 1) return null
let temp = heap[1]
heap[1] = heap[heap.length - 1]
heap[heap.length - 1] = temp
let res = heap.pop()
let i = 1
while (i * 2 <= heap.length - 1) {
let cur = heap[i],
left = heap[i * 2],
right = heap[i * 2 + 1]
if (cur.val <= left.val && (right === undefined || cur.val <= right.val))
return res
if (right === undefined || left.val <= right.val) {
;[heap[i * 2], heap[i]] = [heap[i], heap[i * 2]]
i = i * 2
} else {
;[heap[i * 2 + 1], heap[i]] = [heap[i], heap[i * 2 + 1]]
i = i * 2 + 1
}
}
return res
}
return dummy.next
}
/**
* 378. 有序矩阵中第K小的元素(大顶堆)
* @param {number[][]} matrix
* @param {number} k
* @return {number}
*/
var kthSmallest = function(matrix, k) {
let maxHeap = [null]
for (let i = 0, len1 = matrix.length; i < len1; i++) {
for (let j = 0, len2 = matrix[0].length; j < len2; j++) {
if (maxHeap.length > k) {
if (matrix[i][j] >= maxHeap[1]) continue
delTop(maxHeap)
insert(matrix[i][j], maxHeap)
} else {
insert(matrix[i][j], maxHeap)
}
}
}
function insert(num, heap) {
heap.push(num)
let i = heap.length - 1,
p = Math.floor(i / 2)
while (i > 1 && heap[i] > heap[p]) {
;[heap[i], heap[p]] = [heap[p], heap[i]]
i = p
p = Math.floor(i / 2)
}
}
function delTop(heap) {
if (heap.length <= 1) return
;[heap[1], heap[heap.length - 1]] = [heap[heap.length - 1], heap[1]]
heap.pop()
let i = 1
while (i * 2 < heap.length) {
let cur = heap[i],
left = heap[i * 2],
right = heap[i * 2 + 1]
if (cur >= left && (right === undefined || cur >= right)) return
if (right === undefined || left > right) {
;[heap[i], heap[i * 2]] = [heap[i * 2], heap[i]]
i = i * 2
} else {
;[heap[i], heap[i * 2 + 1]] = [heap[i * 2 + 1], heap[i]]
i = i * 2 + 1
}
}
}
return maxHeap.length > 1 ? maxHeap[1] : null
}
<file_sep>/**
* 127. 单词接龙
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
var ladderLength = function (beginWord, endWord, wordList) {
if (beginWord === endWord) return 1
if (wordList.indexOf(endWord) === -1) return 0
const visited = { [beginWord]: 1, [endWord]: 1 }
let q1 = [beginWord],
q2 = [endWord]
let ans = 1
function canChange(word1, word2) {
let ans = word1.length
for (let i = 0, len = word1.length; i < len; i++) {
if (word1[i] === word2[i]) ans--
}
return ans === 1
}
while (q1.length && q2.length) {
if (q1.length > q2.length) {
const temp = q1
q1 = q2
q2 = temp
}
const q3 = []
for (let i = 0, len1 = q1.length; i < len1; i++) {
for (let j = 0, len2 = wordList.length; j < len2; j++) {
if (canChange(q1[i], wordList[j])) {
if (q2.indexOf(wordList[j]) !== -1) return ans + 1
if (!visited.hasOwnProperty(wordList[j])) {
q3.push(wordList[j])
visited[wordList[j]] = 1
}
}
}
}
ans++
q1 = q3
}
return 0
}
/**
* 752. 打开转盘锁
* @param {string[]} deadends
* @param {string} target
* @return {number}
*/
var openLock = function (deadends, target) {
const deadHash = {}
for (let i = 0, len = deadends.length; i < len; i++) deadHash[deadends[i]] = 1
if (deadHash['0000']) return -1
if ('0000' === target) return 0
deadHash['0000'] = 1
function getNeighbors(str) {
const ans = []
for (let i = 0; i < 4; i++) {
const a = str[i] == 0 ? 9 : +str[i] - 1
const b = str[i] == 9 ? 0 : +str[i] + 1
ans.push(
str.slice(0, i) + a + str.slice(i + 1),
str.slice(0, i) + b + str.slice(i + 1)
)
}
return ans
}
let ans = 0
let q1 = ['0000'],
q2 = [target]
while (q1.length && q2.length) {
if (q1.length > q2.length) {
const temp = q2
q2 = q1
q1 = temp
}
const q3 = []
for (let i = 0, len = q1.length; i < len; i++) {
const cur = getNeighbors(q1[i])
for (let j = 0, len = cur.length; j < len; j++) {
if (q2.indexOf(cur[j]) !== -1) return ans + 1
if (!deadHash[cur[j]]) {
deadHash[cur[j]] = 1
q3.push(cur[j])
}
}
}
ans++
q1 = q3
}
return -1
}
/**
* 743. 网络延迟时间
* @param {number[][]} times
* @param {number} N
* @param {number} K
* @return {number}
*/
var networkDelayTime = function (times, N, K) {
const graph = new Array(N + 1)
for (let i = 0; i <= N; i++) {
graph[i] = new Array(N + 1)
graph[i].fill(-1)
}
for (let i = 0, len = times.length; i < len; i++) {
const time = times[i]
graph[time[0]][time[1]] = time[2]
}
const cost = new Array(N + 1)
for (let i = 1; i <= N; i++) {
cost[i] = graph[K][i]
}
cost[K] = 0
const visited = new Array(N + 1)
visited.fill(false)
visited[K] = true
for (let c = 0; c < N - 1; c++) {
let minVal = Number.MAX_SAFE_INTEGER
let minIndex = -1
for (let i = 1; i <= N; i++) {
if (cost[i] !== -1 && !visited[i] && minVal > cost[i]) {
minVal = cost[i]
minIndex = i
}
}
if (minIndex === -1) break
visited[minIndex] = true
for (let i = 1; i <= N; i++) {
if (graph[minIndex][i] !== -1) {
const temp = graph[minIndex][i] + cost[minIndex]
cost[i] = cost[i] === -1 ? temp : Math.min(temp, cost[i])
}
}
}
let ans = -1
for (let i = 1; i <= N; i++) {
if (cost[i] === -1) return -1
ans = Math.max(ans, cost[i])
}
return ans
}
/**
* 310. 最小高度树
* @param {number} n
* @param {number[][]} edges
* @return {number[]}
*/
var findMinHeightTrees = function (n, edges) {
const visited = new Array(n)
visited.fill(false)
const inDegree = new Array(n)
inDegree.fill(0)
for (let i = 0, len = edges.length; i < len; i++) {
const temp = edges[i]
inDegree[temp[0]]++
inDegree[temp[1]]++
}
while (true) {
const temp = []
let flag = false
for (let i = 0; i < n; i++) {
if (inDegree[i] > 1) flag = true
if (inDegree[i] === 1) temp.push(i)
}
if (!flag) break
for (let i = 0, len = temp.length; i < len; i++) {
visited[temp[i]] = true
for (let j = 0, len2 = edges.length; j < len2; j++) {
if (temp[i] === edges[j][0] || temp[i] === edges[j][1]) {
const item = edges[j]
inDegree[item[0]]--
inDegree[item[1]]--
}
}
}
}
const ans = []
for (let i = 0; i < n; i++) if (!visited[i]) ans.push(i)
return ans
}
/**
* 1293. 网格中的最短路径(DFS)
* @param {number[][]} grid
* @param {number} k
* @return {number}
*/
var shortestPath = function (grid, k) {
const h = grid.length,
w = grid[0].length
function dp(i, j, k) {
if (k < 0) return Number.MAX_SAFE_INTEGER
if (i === h - 1 && j === w - 1) return 0
if (grid[i][j] === '#') return Number.MAX_SAFE_INTEGER
const temp = grid[i][j]
grid[i][j] = '#'
let ans = Number.MAX_SAFE_INTEGER
if (j + 1 < w)
ans = Math.min(dp(i, j + 1, k - (grid[i][j + 1] === 1 ? 1 : 0)), ans)
if (j - 1 >= 0)
ans = Math.min(dp(i, j - 1, k - (grid[i][j - 1] === 1 ? 1 : 0)), ans)
if (i + 1 < h)
ans = Math.min(dp(i + 1, j, k - (grid[i + 1][j] === 1 ? 1 : 0)), ans)
if (i - 1 >= 0)
ans = Math.min(dp(i - 1, j, k - (grid[i - 1][j] === 1 ? 1 : 0)), ans)
grid[i][j] = temp
return 1 + ans
}
const ans = dp(0, 0, k)
return ans >= Number.MAX_SAFE_INTEGER ? -1 : ans
}
/**
* 1293. 网格中的最短路径
* @param {number[][]} grid
* @param {number} k
* @return {number}
*/
var shortestPath = function (grid, k) {
const h = grid.length,
w = grid[0].length
const queue = [{ x: 0, y: 0, rest: k }]
const next = [
[-1, 0],
[1, 0],
[0, -1],
[0, 1],
]
const visited = {}
if (h == 1 && w === 1) return 0
visited[0 + '-' + 0 + '-' + k] = true
let ans = 0
while (queue.length) {
let count = queue.length
while (count) {
count--
const { x, y, rest } = queue.shift()
for (let i = 0; i < 4; i++) {
const nx = x + next[i][0]
const ny = y + next[i][1]
if (0 <= nx && nx < h && 0 <= ny && ny < w) {
if (nx === h - 1 && ny === w - 1) return ans + 1
if (
grid[nx][ny] === 1 &&
rest > 0 &&
!visited[nx + '-' + ny + '-' + (rest - 1)]
) {
queue.push({ x: nx, y: ny, rest: rest - 1 })
visited[nx + '-' + ny + '-' + (rest - 1)] = true
}
if (grid[nx][ny] === 0 && !visited[nx + '-' + ny + '-' + rest]) {
queue.push({ x: nx, y: ny, rest })
visited[nx + '-' + ny + '-' + rest] = true
}
}
}
}
ans++
}
return -1
}
/**
* 815. 公交路线
* @param {number[][]} routes
* @param {number} S
* @param {number} T
* @return {number}
*/
var numBusesToDestination = function (routes, S, T) {
if (T === S) return 0
const len = routes.length
const graph_routes = new Array(len)
for (let i = 0; i < len; i++) {
graph_routes[i] = new Array(len)
graph_routes[i].fill(0)
}
for (let i = 0; i < len; i++) {
routes[i].sort((a, b) => a - b)
for (let j = i + 1; j < len; j++) {
routes[j].sort((a, b) => a - b)
if (intersect(routes[i], routes[j])) {
graph_routes[i][j] = 1
graph_routes[j][i] = 1
}
}
}
const queue = [],
visited = new Array(len)
visited.fill(false)
let ans = 0
for (let i = 0; i < len; i++) {
if (binarySearch(routes[i], S)) queue.push(i)
}
while (queue.length) {
let cnt = queue.length
while (cnt--) {
const cur = queue.shift()
if (binarySearch(routes[cur], T)) return ans + 1
visited[cur] = true
for (let i = 0; i < len; i++) {
if (graph_routes[cur][i] && !visited[i]) queue.push(i)
}
}
ans++
}
return -1
}
function binarySearch(arr, target) {
const len = arr.length
let l = 0,
r = len - 1
while (l <= r) {
const m = l + ((r - l) >> 1)
if (arr[m] === target) return true
if (arr[m] > target) {
r = m - 1
} else {
l = m + 1
}
}
return false
}
function intersect(arr1, arr2) {
let i = 0,
j = 0,
len_1 = arr1.length,
len_2 = arr2.length
while (i < len_1 && j < len_2) {
if (arr1[i] === arr2[j]) return true
if (arr1[i] > arr2[j]) {
j++
} else {
i++
}
}
return false
}
<file_sep>/**
* 982. 按位与为零的三元组
* @param {number[]} A
* @return {number}
*/
var countTriplets = function (A) {
const len = A.length
let ans = 0
const map = new Array(1 << 16)
map.fill(0)
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
map[A[i] & A[j]]++
}
}
for (let i = 0; i < map.length; i++) {
if (!map[i]) continue
for (let j = 0; j < len; j++) {
if ((i & A[j]) === 0) ans += map[i]
}
}
return ans
}
| c493acc3cb2a24bc59294145ad92d6c88ac34abd | [
"JavaScript"
] | 19 | JavaScript | sponses/leetcode | 5ee86f5a7f124d567defb31e0d48a175e7334b8b | e5621d931a67a05af41df0fb94e185500ae915c9 |
refs/heads/master | <repo_name>JD-aka-Techy/fcc_url_shortener<file_sep>/README.md
API Basejump: URL Shortener
=========================
User stories:
---------------
1) I can pass a URL as a parameter and I will receive a shortened URL in the JSON response.
2) When I visit that shortened URL, it will redirect me to my original link.
Example creation usage:
* {base url}/new/https://www.google.com
* {base url}/new/http://freecodecamp.com/
Example creation output:
* { "original": "http://freecodecamp.com/", "redirect":{base url}/4 }
Usage:
* {base url}/4
Will redirect to:
* http://freecodecamp.com/<file_sep>/server.js
var express = require('express')
var app = express()
var mongo = require('mongodb').MongoClient
var validUrl = require('valid-url')
var dbUrl = 'mongodb:' + process.env.IP + '/data'
app.get('/', function(req, res){
// output base information
var url = req.get('host')
var stringy = 'API Basejump: URL Shortener\n\n' +
'User stories: \n\n' +
'1) I can pass a URL as a parameter and I will receive a shortened URL in the JSON response. \n' +
'2) When I visit that shortened URL, it will redirect me to my original link.\n\n' +
'Example creation usage:\n\n' +
' ' + url + '/new/https://www.google.com\n' +
' ' + url + '/new/http://freecodecamp.com/news\n\n' +
'Example creation output:\n\n' +
' { "original": "http://freecodecamp.com/news", "redirect":' + url + '/4 }\n\n' +
'Usage:\n\n' +
'https://shurli.herokuapp.com/4\n\n' +
'Will redirect to:\n\n' +
'http://freecodecamp.com/news\n'
res.end(stringy)
})
app.get('/:rLink', function(req,res){
var rLink = req.params.rLink
var url = req.get('host')
mongo.connect(dbUrl, function(err, db){
if(err) throw err
var collection = db.collection('sUrls')
var toFind = {'redirect': parseInt(rLink)}
collection.find( toFind )
.toArray(function(err,docs){
if(err) throw err
if(docs[0]) {
res.redirect('http://' + docs[0].original)
db.close()
} else {
res.json({"error":"No short url found for given input"})
res.end()
db.close()
}
})
})
})
app.get('/new/:newUrl', function(req, res){
var newUrl = req.params.newUrl
var url = req.get('host')
if ( validUrl.isUri( 'http://' + newUrl ) === undefined ) {
// return error
res.json({'error': 'Invalid Url'})
res.end()
} else {
mongo.connect(dbUrl, function(err, db){
if(err) throw err
var collection = db.collection('sUrls')
collection.find({'original': newUrl}).toArray(function(err, docs){
if(err) throw err
if(docs[0]) {
// return the original record if it already exists
res.json( {'original': docs[0].original, 'redirect': url + '/' + docs[0].redirect} )
res.end()
db.close()
} else {
//insert new record and return it
collection.count({},function(err, count){
if(err) throw err
count += 1
collection.insert({'original': newUrl, 'redirect': count})
res.json( {'original': newUrl, 'redirect': url + '/' + count } )
res.end()
db.close()
})
}
})
})
}
})
app.listen(process.env.PORT)
| a8b4a772f89fdce1530fb615741514f2f45fc912 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | JD-aka-Techy/fcc_url_shortener | 057491211e54b843397be4ebe50b8f362c070d6a | 86d16b43713b7da4d085807df5d49e53b8b282d4 |
refs/heads/master | <repo_name>Zhousm0929/try<file_sep>/script.js
let img1
let img2
let img3
let img4
let img5
let img6
let imgg1
let imgg2
let imgg3
let press
let changguan
let wifiImg
let a = 100
let b = 270
let y = []
let x = []
let e = 420
let f = 120
let speedCar = -0.5
let speed1 = -0.5
let speed2 = -0.3
let speed3 = -0.2
let speed4 = 0.3
let speedx
let speedy
let line1, line2, line3, line4, line5
let clouds
let turn = []
let turn1 = []
let triangles = []
var hit1 = false
var hit2 = false
var hit3 = false
var hit4 = false
var hit5 = false
var hitCircle = false
let CG = false
let rects = [];
let r
const n = 20
let agrid
let yx
let yy
var still = false
let still2 = false
let still3 = false
let still4 = false
let chuizi = false
let jinzhi = false
let wifi = false
let wifion = false
let move = true
let jinzhiON = []
let lineX = 291
let lineY = 260
let lineYY = []
let lineYY2 = []
let mousex, mousey
let img7
let img8
let img9
let img10
let img11
let g = 100
let g2 = 604
let h = 220
let success=0
const colors = [
"#1B234C", //底色
"#60413E", //红色
"#55684E", //绿色
"#725D1C", //黄色
"#394070", //紫色
]
const grid = 20 //颜色固定
function preload() {
//前一张的图片加载
img1 = loadImage("./imgs/456.png")
img2 = loadImage("./imgs/123.png")
img3 = loadImage("./imgs/123.png")
img5 = loadImage("./imgs/2.png")
img6 = loadImage("./imgs/zhe.png")
imgg1 = loadImage("./imgs/gongju1.png")
imgg2 = loadImage("./imgs/gongju2.png")
imgg3 = loadImage("./imgs/gongju3.png")
press = loadImage("./imgs/zheda.png")
clouds = loadImage("./imgs/1.png")
changguan = loadImage("./imgs/changguan.png")
wifiImg = loadImage("./imgs/wifi.png")
//后一张图片加载
img7 = loadImage("./imgs/beijing2.png")
img8 = loadImage("./imgs/21.png")
img9 = loadImage("./imgs/22.png")
img10 = loadImage("./imgs/zhe2.png")
img11 = loadImage("./imgs/23.png")
}
class rectangle {
//构造人函数
constructor(x, y, r, i) {
this.x = x;
this.y = y;
this.r = r;
this.i = i
this.angle = 1;
//相当于定义x方向上的speed
this.yx = cos(TAU / n * i) * (r) / 50;
//相当于定义y方向上的speed
this.yy = sin(TAU / n * i) * (r) / 50;
this.turn = 0
}
translating() {
//检测人撞击边线,每撞击一次turn+1
if (hit1 || hit2 || hit3 || hit4 || hit5) {
this.turn += 1
}
//turn为单数时,人改变方向
if (this.turn % 2 != 0) {
this.yx = -this.yx
this.yy = -this.yy
this.x += this.yx
this.y += this.yy
}
//turn为双数时,原方向前进
else if (this.turn % 2 == 0) {
this.x += this.yx
this.y += this.yy
}
}
//定义方法rotating
rotating() {
rotate(this.angle);
this.angle += 1;
}
//定义方法display
display() {
fill("#1B234C")
stroke("#55684E");
strokeWeight(1);
ellipse(this.x, this.y, 10, 10);
}
}
function setup() {
createCanvas(700, 700)
//弹出框
Notiflix.Confirm.Show('前方高能', '提供三个工具,请拖动它们完成建设', '开始', '不了', function() { // Yes button callback
alert('工具箱🧰:锤子🔨 禁止🚫 代码01010');
},
function() { // No button callback
alert('怂什么?');
});
//定义云单初始位置和turn初始为0
for (var i = 0; i < 8; i++) {
x[i] = 140 + 5 * (8 - i)
y[i] = 420 - 8 * i
turn[i] = 0
}
agrid = TAU / n
for (let i = 0; i < n; i++) {
r = 20
//定义人的初始位置
let x = cos(agrid * i) * r + 120
let y = sin(agrid * i) * r + 180
rects.push(new rectangle(x, y, r, i));
rects[i].display()
}
for (let i = 0; i < 3; i++) {
jinzhiON[i] = false
}
}
function draw() {
background(255)
//加speed移动,并超出范围回到原点
a += speedCar
b += speedCar
e += speed2
f -= speed2
if (a < -100) {
a = 480
}
if (b < -100) {
b = 480
}
if (e < 200) {
e = 470
}
if (f > 470) {
f = 120
}
//画图
image(img1, 0, 0, 518, 700)
image(img2, a, 62, 150, 60)
image(img3, b, 62, 150, 60)
image(img5, f, 620, 342, 21)
image(img5, f - 350, 620, 342, 21)
//画遮住的图
image(img6, 0, 0, 518, 700)
//云移动
for (var i = 0; i < 8; i++) {
//move可执行的状态
if (move) {
//超出上面,回到原点
if (y[i] < 270) {
y[i] = 420
x[i] = 180
}
//超出左右,turn+1
if (x[i] <= 140 || x[i] >= 200) {
turn[i]++
}
//turn为双数时,x向左移动,y向上
if (turn[i] % 2 == 0) {
speedx = -0.08 * (8 - i)
x[i] += speedx
speedy = -0.05 * i
y[i] += speedy
}
//turn为单数时,x向右移动,y向上
else {
speedx = 0.08 * (8 - i)
x[i] += speedx
speedy = -0.05 * i
y[i] += speedy
}
}
//画云
image(clouds, x[i], y[i], 57, 42)
}
//画方形遮住
stroke(255)
fill(255)
rect(518, 0, 200, 700)
//画工具图
image(imgg1, 535, 200, 72.3, 33.9)
image(imgg2, 550, 250, 44.1, 52.2)
image(imgg3, 555, 320, 37.2, 37.2)
//点击并拖动工具
if (mouseIsPressed) {
//dist为两点之间距离
if (dist(mouseX, mouseY, 550, 210) < 20) wifi = true
if (dist(mouseX, mouseY, 550, 290) < 20) chuizi = true
if (dist(mouseX, mouseY, 550, 350) < 30) jinzhi = true
//拖动锤子图片
if (chuizi) {
image(imgg2, mouseX, mouseY, 44.1, 52.2)
still2 = true
mousex = mouseX
mousey = mouseY
}
//拖动wifi图片
if (wifi) {
image(imgg1, mouseX, mouseY, 72.3, 33.9)
still3 = true
mousex = mouseX
mousey = mouseY
}
//拖动禁止图片
if (jinzhi) {
image(imgg3, mouseX, mouseY, 37.2, 37.2)
still4 = true
mousex = mouseX
mousey = mouseY
}
}
//锤子工具
if (!mouseIsPressed && still2) {
chuizi = false
if (mousex < 460 && mousex > 310 && mousey < 350 && mousey > 240) {
//遮住废楼部分
image(press, 287, 230, 187, 140.8)
//画线
for (var i = 0; i < 10; i++) {
let speeddown = 0.01 * (i + 1)
lineY += speeddown
lineX = 320 + i * 5
lineYY[i] = lineY + 6 * i
lineYY2[i] = lineY + 6 * (10 - i)
if (lineYY[i] > 360 || lineYY2[i] > 360) {
lineYY[i] = 360
lineYY2[i] = 360
lineX = 295 + i * 6
// CG=true
}
stroke("#725D1C")
noFill()
line(lineX, lineYY[i], lineX + 120, lineYY[i])
line(lineX, lineYY2[i], lineX + 80, lineYY2[i])
}
}
}
//每一根直线落下,m+1,m为10时,改变cg状态
let m = 0
for (var i = 0; i < 10; i++) {
if (lineYY[i] == 360 && lineYY2[i] == 360) {
m++
}
if (m == 10){
CG = true
}
}
//cg为true时,画遮挡图以及亚运会场馆
if (CG) {
image(press, 287, 230, 187, 140.8)
image(changguan, 320, 250, 150, 90)
}
//wifi工具
if (!mouseIsPressed && still3) {
wifi = false
if (mousex < 460 && mousex > 370 && mousey < 500 && mousey > 360) {
wifion = true
}
}
if (wifion) {
image(wifiImg, 392, 365, 89.7, 76.2)
}
//禁止工具
if (!mouseIsPressed && still4) {
jinzhi = false
if (mousex < 90 && mousex > 40 && mousey < 600 && mousey > 540) {
jinzhiON[0] = true
}
if (mousex < 250 && mousex > 150 && mousey < 460 && mousey > 360) {
jinzhiON[1] = true
}
if (mousex < 500 && mousex > 50 && mousey < 100 && mousey > 70) {
jinzhiON[2] = true
}
}
if (jinzhiON[0]) {
image(imgg3, 56, 560, 37.2, 37.2)
}
//云不动
if (jinzhiON[1]) {
image(imgg3, 190, 440, 37.2, 37.2)
move = false
}
//车停止
if (jinzhiON[2]) {
image(imgg3, 260, 80, 37.2, 37.2)
speedCar = 0
}
//画无形的五根线
stroke("#1B234C")
line(65, 140, 235, 140)
line(65, 140, 65, 235)
line(65, 235, 140, 235)
line(140, 235, 235, 180)
line(235, 180, 235, 140)
noFill()
stroke("#55684E")
for (let i = 0; i < n; i++) {
//人与无形的线的撞击检测
hit1 = collideLineCircle(65, 140, 235, 140, rects[i].x, rects[i].y, 10);
hit2 = collideLineCircle(65, 140, 65, 235, rects[i].x, rects[i].y, 10);
hit3 = collideLineCircle(65, 235, 140, 235, rects[i].x, rects[i].y, 10);
hit4 = collideLineCircle(140, 235, 235, 180, rects[i].x, rects[i].y, 10);
hit5 = collideLineCircle(235, 180, 235, 140, rects[i].x, rects[i].y, 10);
//移动
rects[i].translating()
rects[i].display()
}
//当任务完成后,执行后一张海报
if (CG&&wifion&&jinzhiON[0]&&jinzhiON[1]&&jinzhiON[2]) {
g += speed1
if (g < -504) {
g = 504
}
g2 += speed1
if (g2 < -504) {
g2 = 504
}
h += speed4
if (h < 210 || h > 230) {
speed4 = -speed4
}
image(img7, 0, 0, 518, 700)
image(img8, g, 75, 504, 33)
image(img8, g2, 80, 504, 33)
image(img8, g + 100, 215, 504, 33)
image(img8, g2 + 100, 215, 504, 33)
image(img9, g, 585, 504, 55)
image(img9, g2, 585, 504, 55)
image(img10, 0, 0, 518, 700)
image(img11, 100, h, 59.1, 20.7)
stroke(255)
fill(255)
rect(518, 0, 200, 700)
success++
}
if(success==1){
Notiflix.Report.Success( '建设成功!', '"你真是一个平平无奇建筑🏠小天才" ', '观看活力杭州' );
}
}
| d8f203913f9818dc59a90bd938cd8c209bfb4b69 | [
"JavaScript"
] | 1 | JavaScript | Zhousm0929/try | e1b2136a3e9dc96a6fc436cf018b7aa7e4e8bb47 | e0862bb7c4225337f58184a505eb93dee5f48374 |
refs/heads/master | <file_sep># tf_idf_go
In information retrieval, tf–idf or TFIDF, short for term frequency–inverse document frequency, is a numerical statistic that is intended to reflect how important a word is to a document in a collection or corpus.
Note: this was written for a take-home interview. It was my first Go code and I had no knowledge of Go prior to this activity. I was offered a job, not the job I interviewed for but didn't end up going there.
<file_sep>//implementation of tf-idf (term frequency–inverse document frequency) ranking
//
// <wikipedia> term frequency–inverse document frequency, is a numerical statistic that is intended to reflect how important a word is to a document
// in a collection or corpus.[1]:8 It is often used as a weighting factor in information retrieval and text mining. The tf-idf value
// increases proportionally to the number of times a word appears in the document, but is offset by the frequency of the word in the
// corpus, which helps to adjust for the fact that some words appear more frequently in general.
// Variations of the tf–idf weighting scheme are often used by search engines as a central tool in scoring and ranking a document's
// relevance given a user query. tf–idf can be successfully used for stop-words filtering in various subject fields including text
// summarization and classification.
package main
import "fmt"
import "strings"
import "os"
import "log"
import "bufio"
import "path"
import "regexp"
import . "math"
// Our Term Map, term (string) to map of docid (int) to term raw count (int)
var TermMap map[string] map[int] *int
// TermInDocs term (string) to number of docs
var TermInDocsMap map[string] *int
// DocWordCount docid (int) to words in doc
var DocWordCount map[int] int
// DocIDs - id for each doc in our set, convieniently can be used to create input and output files
var docids [5]int
// clean_term()
// clean up each term by removing punctuation, rendering lower case, demoting plural to singular
func clean_term(term string) string{
// clean it all up (borrowed from github.com/kennygrant/sanitize)
name := strings.ToLower(term)
name = path.Clean(path.Base(name))
name = strings.Trim(name, " ")
// remove the plural s (oversimplification)
term = strings.TrimSuffix(term, "'s")
// TODO: add with and without trailing s
term = strings.TrimSuffix(term, "s")
// Replace certain joining characters with a dash
seps, err := regexp.Compile(`[ &_=+:]`)
if err == nil {
// TODO: for hyphenation string1-string2, add both strings or "string1 string2"
name = seps.ReplaceAllString(name, "-")
}
// Remove all other unrecognised characters - NB we do allow any printable characters
legal, err := regexp.Compile(`[^[:alnum:]-]`)
if err == nil {
name = legal.ReplaceAllString(name, "")
}
// Remove any double dashes caused by existing - in name
name = strings.Replace(name, "--", "-", -1)
term = strings.TrimSuffix(term, "-")
// Remove trailing comma
name2 := name
name2 = strings.TrimRight(name2, ",")
return name2
}
func increment(xPtr *int) {
if (xPtr != nil) {
*xPtr += 1
}
}
func add_term(term string, docid int) int {
retval := 0
// if new term
if TermMap[term] == nil {
tcount := new(int)
increment(tcount)
mm := make(map[int]*int)
TermMap[term] = mm
TermMap[term][docid] = tcount
retval = 1
}
// term is present for another docid
if TermMap[term][docid] == nil {
acount := new(int)
increment(acount)
TermMap[term][docid] = acount
} else { // term is present for this docid, just increment
gm := TermMap[term]
tcount_ptr := gm[docid]
increment(tcount_ptr)
if (tcount_ptr != nil) {
}
}
return retval
}
func add_term_doc_count(term string) int {
retval := 0
// if new term
if TermInDocsMap[term] == nil {
tcount := new(int)
increment(tcount)
TermInDocsMap[term] = tcount
retval = 1
} else {
newcount := TermInDocsMap[term]
increment(newcount)
}
return retval
}
// parse the file into terms, clean up the terms and add to our dictionary
func add_terms_to_dictionary(docid int) {
term_count := 0
// Open the file
filename := fmt.Sprintf("doc%d.txt",docid)
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
// Scan the file for words
scanner := bufio.NewScanner(file)
// Set the split function for the scanning operation.
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
// make lower case
term := strings.ToLower(scanner.Text())
cterm := clean_term(term);
// add words to dictionary
term_count += add_term(cterm, docid)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err)
}
// save the term_count: number of unique terms in the doc
DocWordCount[docid] = term_count
}
// sum how many docs each term appears in
func sum_of_docs_per_term () {
for term, docmap := range TermMap {
for _, tcount := range docmap {
add_term_doc_count(term) // how many docs have this term
tcount = tcount // complains about not using anything
}
}
}
// fill in the scores and write to .csv
func write_tfidf_values(docid int) {
var N int
var df_t int
var tf_td int
// Open the file
filename := fmt.Sprintf("doc%d.csv",docid)
file, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
// Assemble the scores
N = len(docids)
for term, docmap := range TermMap {
df_t = 0
tf_td = 0
var score float64
df_t = *(TermInDocsMap[term])
for doc, tcount := range docmap {
if doc == docid {
tf_td = *tcount
if df_t > 0 {
score = 1+ Log10( float64(tf_td)) * Log10(float64(N)/float64(df_t))
}
}
}
if (tf_td > 0) {
term_line := fmt.Sprintf("%s,%f\n",term,score)
_, err := file.WriteString(term_line);
if err != nil {
log.Fatal(err)
}
}
}
file.Sync()
file.Close()
}
func main() {
docids[0] = 1 ; docids[1] = 2; docids[2] = 3; docids[3] = 4; docids[4] = 5;
TermMap = make(map[string] map[int] *int)
TermInDocsMap = make(map[string] *int)
DocWordCount = make(map[int] int)
for i := 0; i < len(docids); i++ {
add_terms_to_dictionary(docids[i])
}
sum_of_docs_per_term ();
for i := 0; i < len(docids); i++ {
write_tfidf_values(docids[i])
}
}
| 2ed1ce1274e2a0c99dc9c5805d0daaec5bc2cc8d | [
"Markdown",
"Go"
] | 2 | Markdown | cemckenzie/tf_idf_go | c61604025d1399c07db8b286167b1b7c3df19995 | 7c01160772a48ada83dae0bd2cacf681c1a50401 |
refs/heads/master | <file_sep># Sistema de Controle de Leilão em JAVA
### Trabalho Final de Programação Orientada a Objetos
### Devido aos constantes produtos e imóveis apreendidos pela Receita Federal do Brasil, o governo Brasileiro identificou a necessidade de desenvolver um Sistema de Leilões Eletrônicos mais robusto e simples que o atual Sistema de Leilões Eletrônicos (SLE) já existente e usado através do portal eCAC.
### Visando direcionar melhor o escopo inicial deste sistema, a Receita Federal pretende direcioná-lo somente para leilões de imóveis (apartamentos, terrenos, casas e edifícios comerciais) e veículos (carros e motocicletas de passeio) apreendidos. Para tal, o sistema que está sendo solicitado deve conter:
# Funcionalidades Básicas
#### 1. Registro, consulta, atualização e remoção de imóveis a serem leiloados (dentre os tipos acima destacados) – os detalhes dos dados a serem trabalhados para representar o imóveis fazem parte da pesquisa a ser realizada sobre o domínio do sistema;
#### 2. Registro, consulta, atualização e remoção de veículos a serem leiloados (dentre os tipos acima destacados) – os detalhes dos dados a serem trabalhados para representar o imóveis fazem parte da pesquisa a ser realizada sobre o domínio do sistema;
#### 3. Registro, consulta, atualização e remoção dos leilões, constando a data de sua ocorrência (futura), local em que o leilão ocorrerá e demais detalhes pertinentes ao domínio de um leilão eletrônico, mas que também terá entrada física no local (endereço, cidade e estado) de sua ocorrência;
#### 4. Associação dos produtos registrados (imóveis e/ou veículos) ao seu respectivo leilão; a. Não deve haver produtos a serem leiloados registrados no sistema, sem sua respectiva associação a um leilão previamente registrado;
#### 5. Registro, consulta, atualização e remoção dos dados de cada Cliente autorizado a interagir com o sistema, fornecendo lances e consultando os detalhes dos produtos anunciados no leilão, bem como os leilões a serem realizados; e
#### 6. Registro, consulta, atualização e remoção das instituições financeiras responsáveis pela quitação das transações fechadas durante os leilões. Cada leilão terá uma entidade financeira associada ao mesmo (CNPJ) e seus dados deverão estar disponíveis aos clientes nas operações de consulta e detalhe do leilão.
## Funcionalidades da Operação do Sistema de Leilão Eletrônico
#### 1. Listagem dos leilões registrados no sistema, ordenados por data de ocorrência;
#### 2. Detalhamento de um leilão específico, apresentando seu detalhes (lista de produtos ordenado por nome, entidade financeira associada, dados do leilão, quantidade total de produtos e demais dados pertinentes ao domínio);
#### 3. Detalhamento de um produto associado ao leilão detalhado, apresentando todos os dados pertinentes ao detalhe do produto registrado;
#### 4. Filtro de busca de produtos em um leilão por:
##### a. Faixa de valores (min < R$ < max), sendo os valores mínimos e máximos informados pelo usuário;
##### b. Palavra chave contida no nome do produto ou na descrição do produto; e
##### c. Tipo de produto.
#### 5. Possibilitar a um cliente previamente cadastrado no sistema dar um lance de valor (R$) para um produto específico – As devidas validações deverão ser mapeadas e implementadas pelos membros do grupo em relação à regras de consistência dos lances registrados;
#### 6. Apresentação do histórico de lances realizado para um produto específico, destacando o produto, cliente e valor do lance – Ordenação pelo ID do lance correspondente;
#### 7. Sistema deverá automaticamente analisar a faixa de horário do leilão, caso o mesmo esteja ocorrendo no momento correspondente. Uma vez ultrapassado o horário de finalização, ao consultar o detalhamento do leilão, o sistema deverá apresentar a relação de produtos acompanhado de seus respectivos clientes (ganhadores do leilão, caso haja, senão deverá apresentar N/A), valor do lance vencedor (R$) e o status de FINALIZADO para o leilão;
#### 8. Todo leilão deverá ter atrelado ao mesmo três status chaves:
##### a. EM ABERTO - Para leilões registrados, porém ainda não iniciados;
##### b. EM ANDAMENTO 0 Para leilões registrados, cuja data e faixa de horário do leilão estiverem ocorrendo no exato momento de operação do sistema; e
##### c. FINALIZADO – Para leilões cujo horário atual ultrapassou os limites da faixa de horário registrada para ocorrência do leilão.
##### d. Observação: A gestão e tratamento dos status do leilão deverá ser executada automaticamente pelo sistema, ou seja, não haverá funcionalidade para indicar que o leilão foi registrado, iniciou-se ou foi finalizado.
#### 9. O sistema deverá prover também uma funcionalidade de exportação dos detalhes do leilão para um arquivo com extensão .DET contendo todas as informações do leilão, seus produtos, clientes participantes do leilão, entidade financeira associada e histórico de lances de cada produto; e
#### 10. Toda e qualquer persistência de dados da aplicação deverá ser implementada em memória, simulando os registros de Objetos que seriam persistidos na base de dados, porém mantendo-os na memória. Consultas, registros, atualização e remoções deverão ser realizadas na estrutura usada para armazenar tais registros;
#### 11. Todas as funcionalidades deverão ser implementadas minimamente através de menus e interfaces simples via console, que possibilitem informar as diversas entradas de dados, e efetivar todas as operações necessárias; e
#### 12. O código fonte do projeto do trabalho implementado deverá ter minimamente 70% de cobertura de código validados por Teste de Unidade (30% da nota total do trabalho).
### Diferenciais relevantes com Pontuação Extra:
#### 1. Implementação das funcionalidades utilizando API gráfica Swing do próprio Java, para todas as funcionalidades do trabalho (1,5 de acréscimo na media final) –Referência: Java como Programar – 6ª, 7ª ou 8ª edição – <NAME> (Há referências a biblioteca).
<file_sep>package edu.fatec.sjc;
import java.util.List;
public class Lote {
private Integer numLote;
private List <Integer> qtdeProd;
private Object tipo;
private Leilao leilao;
private Imovel imovel;
private Veiculo veiculo;
public Lote(Integer numLote, List<Integer> qtdeProd, Imovel imovel, Veiculo veiculo) {
this.numLote = numLote;
this.qtdeProd=qtdeProd;
this.imovel = imovel;
this.veiculo = veiculo;
}
public Integer getNumLote() {
return numLote;
}
public void setNumLote(Integer numLote) {
this.numLote = numLote;
}
public Object getTipo() {
return tipo;
}
public void setTipo(Object tipo) {
this.tipo = tipo;
}
public Leilao getLeilao() {
return leilao;
}
public void setLeilao(Leilao leilao) {
this.leilao = leilao;
}
public Imovel getImovel() {
return imovel;
}
public void setImovel(Imovel imovel) {
this.imovel = imovel;
}
public Veiculo getVeiculo() {
return veiculo;
}
public void setVeiculo(Veiculo veiculo) {
this.veiculo = veiculo;
}
public List<Integer> getQtdeProd() {
return qtdeProd;
}
public void setQtdeProd(List<Integer> qtdeProd) {
this.qtdeProd = qtdeProd;
}
}
<file_sep>package edu.fatec.sjc;
import java.util.ArrayList;
//import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class Model {
//INSTANCIANFO VARIÁVEIS DO TIPO SCANNER PARA LER AS ENTRADAS DO USUÁRIO E ARMAZENAR NAS VARIÁVEIS DEFINIDAS ABAIXO
private Scanner le;
// DEFININDO VARIÁVEIS UTILIZADAS NOS MÉTODOS
private String nome, senha, certDig, cnpj, registro, endereco, descricao, marca, modelo, tipo,
email;
//private Date data;
private Integer numLeilao, qtde, numLote, id, ano;
/* Instanciando enuns
TipoVeiculo tipoVeic;
TipoImovel tipoImovel;*/
//INSTANCIANDO AS CLASSES (LISTAS)
private static List<Cliente> clientes;
private static List<Imovel> imoveis;
private static List<Veiculo> veiculos;
private static List<InstituicaoFinanceira> instFinanceiras;
static List<Leilao> leiloes;
static List<Lote> lotes;
static List<Lance> lances;
//CRIANDO ARRAYLISTS DAS LISTAS INSTANCIADAS
public Model() {
clientes = new ArrayList<>();
imoveis = new ArrayList<>();
instFinanceiras = new ArrayList<>();
leiloes = new ArrayList<>();
veiculos = new ArrayList<>();
lotes = new ArrayList<>();
lances = new ArrayList<>();
//produtos = new ArrayList<>();
le = new Scanner(System.in);
}
//FUNÇÕES DE INSERÇÃO
void darLances() {
System.out.println("Numero de Certificado Digital: ");
certDig = le.next();
for (Cliente cliente : clientes) {
if (!certDig.equals(cliente.getCertificadoDigital())) {
System.out.println("Cliente não encontrado!");
break;
}
// cliente = le.next();
System.out.println("Insira o número do Leilão: ");
numLeilao = le.nextInt();
for (Leilao leilao : leiloes) {
if (numLeilao.equals(leilao.getNumeroLeilao())) {
System.out.println("Insira o valor: ");
Float valor = le.nextFloat();
lances.add(new Lance(valor, cliente, leilao));
}else{
System.out.println("Leilão não encontrado!");
break;
}
}
}
}
void inserirCliente() {
System.out.println("Nome: ");
nome = le.nextLine();
System.out.println("E-mail: ");
email = le.nextLine();
System.out.println("Senha: ");
nome = le.nextLine();
System.out.println("Numero de Certificado Digital: ");
certDig = le.nextLine();
clientes.add(new Cliente(nome, email, senha, certDig));
System.out.println("Cadastrado!!!");
}
void inserirImovel() {
System.out.println("Id: ");
id = le.nextInt();
System.out.println("Registro: ");
registro = le.next();
System.out.println("Endereço: ");
endereco = le.nextLine();
System.out.println("Digite uma das opções referente ao tipo do Imóvel:");
System.out.println("\nApartamento, Terreno, Casa, Edifício Comercial");
tipo = le.nextLine();
if(tipo.equals("Apartamento")||tipo.equals("Terreno")||tipo.equals("Casa")||tipo.equals("Edifício Comercial")||tipo.equals("Edificio Comercial")
||tipo.equals("apartamento")||tipo.equals("terreno")||tipo.equals("casa")||tipo.equals("edifício comercial")||tipo.equals("edificio comercial")) {
System.out.println("Descrição: ");
descricao = le.nextLine();
}else {
System.out.println("Tipo de imóvel não encontrado");
}
imoveis.add(new Imovel(id, registro, endereco, descricao));
System.out.println("Cadastrado!!!");
}
void inserirVeiculo() {
System.out.println("Digite uma das opções referente ao tipo do Veículo:");
System.out.println("\nCarro, Motocicleta, Bicicleta, Patinete, Skate");
tipo = le.next();
System.out.println("Id: ");
id = le.nextInt();
if(tipo.equals("Carro")||tipo.equals("Motocicleta")||tipo.equals("Bicicleta")||tipo.equals("Patinete")||tipo.equals("Skate")
||tipo.equals("carro")||tipo.equals("motocicleta")||tipo.equals("bicicleta")||tipo.equals("patinete")||tipo.equals("skate") ) {
System.out.println("Ano: ");
ano = le.nextInt();
System.out.println("Marca: ");
marca = le.next();
System.out.println("Modelo: ");
modelo = le.next();
System.out.println("Descrição: ");
descricao = le.nextLine();
descricao = le.nextLine();
}else {
System.out.println("Tipo de Veículo não encontrado");
}
veiculos.add(new Veiculo( id, tipo, marca, ano, modelo, descricao));
}
void inserirInstFin() {
System.out.println("CNPJ: ");
cnpj = le.nextLine();
System.out.println("Nome: ");
nome = le.nextLine();
System.out.println("Endereco: ");
endereco = le.nextLine();
instFinanceiras.add(new InstituicaoFinanceira(cnpj, nome, endereco));
System.out.println("Cadastrado!!!");
}
void inserirLeilao() {
System.out.println("Numero do Leilao: ");
numLeilao = le.nextInt();
System.out.println("CPNJ da Instituição Financeira: ");
cnpj = le.next();
System.out.println("Insira o número do lote: ");
numLote = le.nextInt();
for (InstituicaoFinanceira instituicaoFinanceira : instFinanceiras) {
if (!cnpj.equals(instituicaoFinanceira.getCnpj())) {
System.out.println("Instituição Financeira não encontrada!");
} else {
for (Lote lote : lotes) {
if (!numLote.equals(lote.getNumLote())) {
System.out.println("Lote não encontrado!");
} else {
/*
* System.out.println("Insira a Data: "); Date data = le.nextInt();
*/
System.out.println("Insira o Endereço: ");
endereco = le.next();
}
}
}
}
leiloes.add(new Leilao(numLeilao, numLote, cnpj, endereco));
}
@SuppressWarnings("null")
void inserirLote() {
List<Integer> produtos;
produtos = new ArrayList<>();
System.out.println("Número do Lote: ");
numLote = le.nextInt();
System.out.println("Insira a quantidade de produtos: ");
qtde = le.nextInt();
for (int i = 0; i < qtde; i++) {
System.out.println("Tipo do Lote - V para Veículos ou I para imóveis");
tipo = le.next();
if (tipo.equals("V") || tipo.equals("v") ) {
System.out.println("Insira o ID do veículo: ");
id = le.nextInt();
//System.out.println(id);
for (Veiculo veiculo : veiculos) {
if(id.equals(veiculo.getId())) {
produtos.add(veiculo.getId());
lotes.add(new Lote(numLote, produtos, null, veiculo));
System.out.println("Veiculo cadastrado");
}else {
System.out.println("Veículo não encontrado");
break;
}
}
}else {
if (tipo.equals("I") || tipo.equals("i")) {
System.out.println("Insira o ID do Imóvel: ");
id = le.nextInt();
for (Imovel imovel : imoveis) {
if(id.equals(imovel.getId())) {
produtos.add(imovel.getId());
System.out.println(produtos);
lotes.add(new Lote(numLote, produtos, imovel, null));
System.out.println("Imóvel cadastrado");
}else {
System.out.println("Imóvel não encontrado");
break;
}
}
}
}
}
System.out.println("Lista de Produtos vazia. Favor cadastrar algum Imóvel ou Veículo");
}
//FUNÇÕES DE ALTERAÇÃO
void alterarCliente() {
System.out.println("Insira o certificado Digital do Cliente: ");
certDig = le.nextLine();
for (Cliente cliente : clientes) {
if(certDig.equals(cliente.getCertificadoDigital())) {
System.out.println("Insira o nome: ");
nome = le.nextLine();
cliente.setNome(nome);
System.out.println("Insira a senha: ");
senha = le.nextLine();
cliente.setSenha(senha);
System.out.println("Insira o e-mail:");
email=le.nextLine();
cliente.setEmail(email);
System.out.println("Insira o certificado digital:");
certDig = le.nextLine();
cliente.setCertificadoDigital(certDig);
System.out.println("Dados atualizados com sucesso!");
}else {
System.out.println("Cliente não encontrado");
}
}
}
void alterarInstFin() {
System.out.println("Insira o CNPJ da instituição: ");
cnpj = le.nextLine();
for(InstituicaoFinanceira instFin: instFinanceiras ) {
if(cnpj.equals(instFin.getCnpj())) {
System.out.println("Insira o nome: ");
nome = le.nextLine();
instFin.setNome(nome);
System.out.println("Insira endereço: ");
endereco = le.nextLine();
instFin.setEndereco(endereco);
System.out.println("Dados atualizados com sucesso!");
}else {
System.out.println("Instituição Financeira não encontrado");
}
}
}
void alterarImovel() {
System.out.println("Insira o registro do Imóvel: ");
registro = le.nextLine();
for(Imovel imovel: imoveis) {
if(registro.equals(imovel.getRegistro())) {
System.out.println("Insira o endereço: ");
endereco = le.nextLine();
imovel.setEndereco(endereco);
descricao = le.nextLine();
imovel.setDescricao(descricao);
}else {
System.out.println("Imóvel não encontrado");
}
}
}
void alterarVeiculo() {
System.out.println("Insira o id do Veículo: ");
id = le.nextInt();
for(Veiculo veiculo: veiculos) {
if(id.equals(veiculo.getId())) {
System.out.println("Insira a marca: ");
marca = le.next();
veiculo.setMarca(marca);
System.out.println("Insira o modelo: ");
modelo = le.nextLine();
veiculo.setModelo(modelo);
System.out.println("Insira a descricao: ");
descricao = le.nextLine();
veiculo.setDescricao(descricao);
System.out.println("Insira o ano: ");
ano = le.nextInt();
veiculo.setAno(ano);
}else {
System.out.println("Veículo não encontrado");
}
}
}
//FUNÇÕES DE IMPRESSÃO
void imprimirCliente() {
for (Cliente Cliente : clientes) {
System.out.println(
" | Nome: " + Cliente.getNome() + " \t| Certificado Digital: " + Cliente.getCertificadoDigital());
}
}
void imprimirImoveis() {
for (Imovel Imovel : imoveis) {
System.out.println("Registro: " + Imovel.getRegistro() + " | Endereço: "
+ Imovel.getEndereco() + " \t| Descricao: " + Imovel.getDescricao());
}
}
void imprimirVeiculos() {
for (Veiculo veiculo : veiculos) {
System.out.println("ID: " + veiculo.getId() + " | Marca: " + veiculo.getMarca() + " \t| Ano: "
+ veiculo.getAno() + " \t| Modelo: " + veiculo.getModelo());
}
}
void imprimirInstFin() {
for (InstituicaoFinanceira instituicaoFinanceira : instFinanceiras) {
System.out.println("CNPJ: " + instituicaoFinanceira.getCnpj() + " | Nome: "
+ instituicaoFinanceira.getNome() + " \t| Endereço: " + instituicaoFinanceira.getEndereco());
}
}
void imprimirLeiloes() {
for (Leilao leilao : leiloes) {
System.out.println("Número do leilão: " + leilao.getNumeroLeilao() + " | Lote: " + leilao.getLoteProdutos()
+ " \t| Instituição Financeira: " + leilao.getInstFin() + " \t| Data: " + leilao.getData()
+ " \t| Endereço: " + leilao.getEndereco());
}
}
void imprimirLotes() {
for (Lote lote : lotes) {
System.out.println("Número do lote: " + lote.getNumLote() + " | Produtos: " + lote.getQtdeProd()+ " | Clientes: " + lote.getImovel()+ " | Veículo: " + lote.getVeiculo());;
}
}
void imprimirLoteEspecífico() {
System.out.println("Insira o número do Lote:");
numLote = le.nextInt();
for (Lote lote : lotes) {
if(numLote.equals(lote.getNumLote())) {
System.out.println("Número do lote: " + lote.getNumLote() + " | Produtos: " + lote.getQtdeProd() + " | Veículos: " + lote.getVeiculo()+ " | Imóveis: " + lote.getImovel());
}
}
}
void imprimirLances() {
System.out.println("Insira o certificado digital: ");
certDig = le.next();
for(Cliente cliente: clientes) {
for (Lance lance : lances) {
if(cliente.getCertificadoDigital().equals(certDig) && cliente.getCertificadoDigital().equals(lance.getCliente().getCertificadoDigital())) {
System.out.println("Valor: " + lance.getValor() + " | Cliente: " + lance.getCliente() + " | Leilao: "
+ lance.getLeilao());
}
}
}
}
//FUNÇÕES DE REMOÇÃO
void removerCliente() {
System.out.println("Insira o certificado digital: ");
String ctd = le.next();
for (int i = 0; i < clientes.size(); i++) {
if (clientes.get(i).getCertificadoDigital().equals(ctd)) {
clientes.remove(i);
}
}
System.out.println("Removido!!!");
}
void removerImovel() {
System.out.println("Insira o Registro: ");
String registro = le.next();
for (int i = 0; i < imoveis.size(); i++) {
if (imoveis.get(i).getRegistro().equals(registro)) {
imoveis.remove(i);
}
}
System.out.println("Removido!!!");
}
void removerVeiculo() {
System.out.println("Insira o ID: ");
int id = le.nextInt();
for (int i = 0; i < veiculos.size(); i++) {
if (veiculos.get(i).getId().equals(id)) {
veiculos.remove(i);
}
}
System.out.println("Removido!!!");
}
void removerInstFin() {
System.out.println("Insira o CNPJ: ");
cnpj = le.next();
for (int i = 0; i < instFinanceiras.size(); i++) {
if (instFinanceiras.get(i).getCnpj().equals(cnpj)) {
instFinanceiras.remove(i);
}
}
System.out.println("Removido!!!");
}
void removerLeilao() {
System.out.println("Insira o numero do Leilao: ");
numLeilao = le.nextInt();
for (int i = 0; i < leiloes.size(); i++) {
if (leiloes.get(i).getNumeroLeilao().equals(numLeilao)) {
leiloes.remove(i);
}
}
System.out.println("Removido!!!");
}
void removerLote() {
System.out.println("Insira o numero do Lote: ");
numLote = le.nextInt();
for (int i = 0; i < lotes.size(); i++) {
if (lotes.get(i).getNumLote().equals(numLote)) {
lotes.remove(i);
}
}
System.out.println("Removido!!!");
}
}
| 9ee4b98efab8de9286245fc04bfe2d3dd06900c2 | [
"Markdown",
"Java"
] | 3 | Markdown | danielwisouza/Sistema_de_Controle_Leilao | 9ef1e0cd9432060b4ac7e9daef797ef8c4a92ca5 | 7bd09010c6d40c64595fc1cf5143cc8ce370576f |
refs/heads/main | <file_sep>python-decouple>=3.3
watchdog>=2.0.2<file_sep>from watchdog.observers import Observer
from decouple import config as getenv
from EventHandler import EventHandler
from functions import notify
import time
event_handler = EventHandler()
observed_dir = getenv('SOURCE_DIR')
observer = Observer()
observer.schedule(event_handler, observed_dir, recursive=True)
observer.start()
notify("Hey 👋", "We will watch " + observed_dir + " for now and keep it clean.")
try:
while True:
time.sleep(60)
except KeyboardInterrupt:
observer.stop()
notify("Stopped ✋", "You are on your own now.")
observer.join()
<file_sep>SOURCE_DIR="/Users/YOURUSER/Desktop"
DESTINATION_DIR="/Users/YOURUSER/Documents"<file_sep>from decouple import config as getenv
import os
# name of the folder and tuple of file extensions
categories = {
"Bilder": ('.png', '.jpg', '.jpeg', '.gif', '.svg'),
"Fotos": ('.cr2', '.heic', '.raw', '.nef'),
"Musik": ('.mp3', '.wav', '.wma'),
"Videos": ('.mp4', '.mov', '.avi', '.mkv', '.wmv', '.webm'),
"Fonts": ('.ttf', '.otf', 'eot', '.woff'),
"Dokumente": ('.txt', '.pages', '.doc', '.pdf', '.rtf'),
"Design": ('.ai', '.psd', '.afdesign', '.xcf'),
"Coding": ('.css', '.html', '.py', '.scss', '.js', '.ts', '.yml')
}
# determine a suiting destination for the file
def get_destination(filename):
destination_dir = getenv('DESTINATION_DIR')
# individual logic here
if "Bildschirm" in filename:
return destination_dir + "/Screenshots"
# handle each category
for category in categories:
if filename.lower().endswith(categories[category]):
return destination_dir + '/' + category
return destination_dir + "/Other"
# triggers a desktop notification
def notify(title, text):
os.system("""
osascript -e 'display notification "{}" with title "{}"'
""".format(text, title))
<file_sep>from watchdog.events import FileSystemEventHandler
from functions import get_destination, notify
from decouple import config as getenv
import os
observed_dir = getenv('SOURCE_DIR')
class EventHandler(FileSystemEventHandler):
@staticmethod
def on_modified(event):
# only get files
files = [f for f in os.listdir(observed_dir) if os.path.isfile(os.path.join(observed_dir, f))]
for file in files:
old_path = observed_dir + "/" + file
new_dir = get_destination(file)
new_path = str(new_dir) + "/" + str(file)
# try to move the file
try:
os.rename(old_path, new_path)
except FileNotFoundError:
print("Error", "No such path found {0}".format(new_dir))
os.mkdir(new_dir)
os.rename(old_path, new_path)
# print amount of moved files
if len(files) > 0:
print(str(len(files)) + "were moved from" + observed_dir)
<file_sep><h1 align="center">
Desktop Cleaner Script 🧹
</h1>
<p>
This script automatically moves files from a choosen directory to defined subdirectories.
</p>
## Getting started
1. **Prerequisites**
Before you start, you should have Python 3 with Pip installed.
Then set up a virtual environment and install the required packages inside the project.
```shell
pip install -r requirements.txt
```
2. **Configure your paths**
Now you can configure your source and destination path in a _.env_ file. There is a .env.example file, that you can rename and use.
```shell
SOURCE_DIR=/Users/youruser/Desktop
DESTINATION_DIR=/Users/youruser/Documents
```
You can also change the logic on how to determine different paths for each file
in the _get_destination_ function in _functions.py_.
3. **Start the script.**
You can start the script manually or set up a cron job to do so.
```shell
python main.py
```
| e195eb47ef024138971e209f42bbda78a9897cdb | [
"Markdown",
"Python",
"Text",
"Shell"
] | 6 | Text | Cuzart/desktop_cleaner | abea71deee1d1db22c03915eb288d3c986ae86a8 | ad7e6ca6ab61b962c858ec1f51973483d9f9f172 |
refs/heads/master | <file_sep>using UnityEngine;
public class Collision : MonoBehaviour {
//as soon as a collision happens, this function will be called
public Movement movt;
void OnCollisionEnter(Collision collisioninfo){
if (collisioninfo.GetComponent<Collider>().tag == "obst")
movt.enabled = false;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour {
public Rigidbody player;
public Transform tr;
public int forceInFwdDirection = 20;
// Update is called once per frame
void FixedUpdate () {
player.AddForce (forceInFwdDirection * Time.deltaTime ,0,0);
if(Input.GetKey(KeyCode.A) )
player.AddForce (0,0,10);
if(Input.GetKey(KeyCode.D) )
player.AddForce (0,0,-10);
if(Input.GetKey(KeyCode.W) )
player.AddForce (10,0,0);
if(Input.GetKey(KeyCode.S) )
player.AddForce (-10,0,0);
}
}
<file_sep>using UnityEngine;
public class FollowerForCamera : MonoBehaviour {
public Transform sphere; //drag and drop our gameobject sphere here.
public Vector3 offset ; //set the offset vector in the inspector
void Update () {
transform.position = sphere.position - offset; //only this line causes camera to be stuck inside sphere
}
}
<file_sep># vr-iOS-dev
Language: C#:
Engine: Unity
| c3dd8f1d28c6b17963707dbd896a20769681d3c8 | [
"Markdown",
"C#"
] | 4 | C# | redgene/vr-iOS-dev | 70fb34729e0da3e440e1e75a0d61ed8349c92c1e | da55d06f9d5c547c72f37e276ef915aeda850599 |
refs/heads/master | <file_sep>const characterImg = [
"./image/luke_skywalker.jpg",
"./image/C3po.png",
"./image/r2d2.jpg",
"./image/darth_vader.jpg",
"./image/leia_organa.jpeg",
"./image/owen_lars.jpg",
"./image/beru_whitesun_lars.jpg",
"./image/r5_d4.jpg",
"./image/biggs_darklighter.png",
"./image/obi_wan_kenobi.jpeg",
"./image/anakin_skywalker.png",
"./image/wilhuff_tarkin.jpg",
"./image/chewbacca.png",
"./image/han_solo.jpg",
"./image/greedo.jpg",
"./image/jabba_desilijic_tiure.jpeg",
"./image/wedge_antilles.jpg",
"./image/jek_tono_porkins.jpg",
"./image/yoda.jpg",
"./image/palpatine.png",
"./image/boba_fett.jpg",
"./image/ig_88.jpg",
"./image/bossk.png",
"./image/lando_calrissian.jpg",
"./image/lobot.jpg",
"./image/ackbar.jpg",
"./image/mon_mothma.png",
"./image/arvel_crynyd.jpg",
"./image/wicket_systri_warrick.png",
"./image/nien_nunb.jpg",
"./image/qui_gon_jinn.jpg",
"./image/nute_gunray.jpeg",
"./image/finis_valorum.jpg",
"./image/padme_amidala.jpg",
"./image/jar_jar_binks.jpg",
"./image/roos_tarpals.jpg",
"./image/rugor_nass.jpg",
"./image/ric_olie.jpg",
"./image/watto.jpg",
"./image/sebulba.jpeg",
"./image/quarsh_panaka.png",
"./image/shmi_skywalker.jpg",
"./image/darth_maul.jpeg",
"./image/bib_fortuna.jpg",
"./image/ayla_secura.png",
"./image/ratts_tyerel.jpeg",
"./image/dud_bolt.jpg",
"./image/gasgano.png",
"./image/ben_quadinaros.png",
"./image/mace_windu.jpg",
"./image/ki_adi_mundi.jpg",
"./image/kit_fisto.jpg",
"./image/eeth_koth.png",
"./image/adi_gallia.jpg",
"./image/seasee_tiin.jpg",
"./image/yarael_poof.jpg",
"./image/plo_koon.jpg",
"./image/mas_amedda.jpg",
"./image/captain_typho.jpg",
"./image/corde.jpg",
"./image/cliegg_lars.jpg",
"./image/poggle_the_lesser.jpg",
"./image/luminara_unduli.jpg",
"./image/barriss_offee.png",
"./image/dorme.jpg",
"./image/dooku.jpeg",
"./image/bail_prestor_organa.jpg",
"./image/jango_fett.jpg",
"./image/zam_wesell.jpg",
"./image/dexter_jettster.jpg",
"./image/luma_su.jpg",
"./image/taun_we.jpg",
"./image/jocasta_nu.jpg",
"./image/r4_p17.jpg",
"./image/wat_tambor.jpg",
"./image/san_hill.jpg",
"./image/shaak_ti.jpg",
"./image/grievous.jpg",
"./image/tartful.jpg",
"./image/raymus_antilles.png",
"./image/sly_moore.jpg",
"./image/tion_medon.jpg"
]
async function fetchData() {
const api_url = "https://swapi.dev/api/people"
let page = 1
let people = []
let lastResult = []
do {
try {
const resp = await fetch(api_url + `/?page=${page}`)
const data = await resp.json()
lastResult = data
data.results.forEach(person => {
const {
name,
height,
gender,
hair_color,
mass,
skin_color,
homeworld,
url
} = person
people.push({
name,
height,
gender,
hair_color,
mass,
skin_color,
homeworld,
url
})
})
page++
} catch (err) {
console.error(`Något gick fel försök igen! ${err}`)
}
} while (lastResult.next !== null)
sendData(people)
}
fetchData()
const sendData = async data => {
const starWarsCharectersWithImage = data.map(
(starWarsCharecter, charImage) => {
starWarsCharecter.image = characterImg[charImage]
return { ...starWarsCharecter }
}
)
const html = starWarsCharectersWithImage
.map((starWarsCharecter, index) => {
let url_char = starWarsCharecter.url
url_chars = url_char.slice(28, -1)
return `
<li onclick="showChar(${url_chars} )"id="box"><img class="card_img" src="${starWarsCharecter.image}"><h4 class="card_name"> ${starWarsCharecter.name} </h4></li>`
})
.join(" ")
document.querySelector("#card").insertAdjacentHTML("afterbegin", html)
}
const showChar = async indexOfStarWarsCharecter => {
const char_api_url =
"https://swapi.dev/api/people/" + indexOfStarWarsCharecter
await fetch(char_api_url)
.then(res => {
if (!res.ok) {
console.log(res)
throw Error("ERROR")
}
return res.json()
})
.then(charstarWarsData => {
charData(charstarWarsData, indexOfStarWarsCharecter)
getWorld(charstarWarsData.homeworld)
})
.catch(error => {
console.log(error)
})
}
const charData = async (info, index) => {
if (index > 16) {
index = index - 1
}
let imgIndex = index - 1
let img = { image: characterImg[imgIndex] }
info = { ...info, ...img }
let name = info.name
let height = info.height
let image = info.image
let gender = info.gender
let birth_year = info.birth_year
let mass = info.mass
let hair_color = info.hair_color
let skin_color = info.skin_color
let output = `<h1 class="charName">${name}</h1>
<div class="charBox">
<div class="image">
<img class="charImg" src="${image}">
</div>
<div class="textInfo">
<h4 class="info">Personal data</h4>
<p class="height"><span>Height:</span> ${height}</p>
<p><span>Gender:</span> ${gender}</p>
<p><span>Birth Year:</span> ${birth_year}</p>
<p><span>Mass:</span> ${mass}</p>
<p><span>Hair color:</span> ${hair_color}</p>
<p><span>Skin color:</span> ${skin_color}</p>
</div>
</div>`
document.querySelector("#selected").innerHTML = output
document.getElementById("selected").style.display = "flex"
document.querySelector(".close").style.display = "block"
}
const infoBox = document
.querySelector(".close")
.addEventListener("click", () => {
document.getElementById("selected").style.display = "none"
document.querySelector(".close").style.display = "none"
})
const getWorld = async homeWorld => {
await fetch(homeWorld)
.then(respWorld => {
if (!respWorld.ok) {
throw Error("ERROR")
}
return respWorld.json()
})
.then(charWorld => {
sendWorld(charWorld)
})
.catch(error => {
console.log(error)
})
}
// printout world
const sendWorld = worldInfo => {
let worldName = worldInfo.name
let climate = worldInfo.climate
let diameter = worldInfo.diameter
let gravity = worldInfo.gravity
let population = worldInfo.population
let terrain = worldInfo.terrain
let output2 = `<div class="homeWorld">
<h4 class="home">Homeworld</h4>
<p class="worldName"><span>Name:</span> ${worldName}</p>
<p><span>Clicamet:</span> ${climate}</p>
<p><span>Diameter:</span> ${diameter}</p>
<p><span>Gravity:</span> ${gravity}</p>
<p class="population"><span>Population:</span> ${population}</p>
<p class="terrain"><span>Terrain:</span> ${terrain}</p>
</div>`
document.querySelector(".charBox").insertAdjacentHTML("beforeend", output2)
}
//search filter
const charList = document.querySelector("#card")
const searchChar = document.forms["search_char"].querySelector("input")
searchChar.addEventListener("keyup", function(event) {
const eventTarget = event.target.value.toLowerCase()
const characters = charList.getElementsByTagName("li")
Array.from(characters).forEach(function(character) {
const title = character.lastElementChild.innerHTML
if (title.toLowerCase().indexOf(eventTarget) != -1) {
character.style.display = "block"
} else {
character.style.display = "none"
}
})
})
| 227c8db69d1b5f42be9b14ac76911b0f040c086d | [
"JavaScript"
] | 1 | JavaScript | vanessasuthat03/star-wars | e00bb196f79cef3e66fedbe214b754a0d2a7f4db | c628967b27d5a13d01d18db9c0066c5c1dcc0bb5 |
refs/heads/master | <file_sep>import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useFetchData } from '../../hooks/fectCollection';
const ProductsBar = ({ collection }) => {
const [loading, data] = useFetchData(collection, []);
const [images, setImages] = useState(null);
const getImages = async () => {
const fetchedImages = [];
if (data) {
try {
for (let item of data[0].images) {
const res = await item.get()
fetchedImages.push(res.data().images[0]);
}
setImages(fetchedImages);
}
catch (err) {
console.log(err);
}
}
}
useEffect(() => {
getImages();
}, [data]);
if (!images) {
return (
<div className="home__productsBar">
loaging...
</div>
);
} else {
return (
<div className="home__productsBar">
<div className="headerBar mb-2">
<h5
className="d-inline-block mr-2"
style={{ fontWeight: 600 }}
>
{data ? data[0].name : ""}
</h5>
<Link to="/">Shop now</Link>
</div>
<div className="box__products">
{images
? images.map((url, index) => (
<React.Fragment key={index}>
<div className="mr-3">
<Link to="">
<img className="bar__image" src={url} alt="1" />
</Link>
</div>
<div className="mr-3">
<Link to="">
<img className="bar__image" src={url} alt="1" />
</Link>
</div>
<div className="mr-3">
<Link to="">
<img className="bar__image" src={url} alt="1" />
</Link>
</div>
</React.Fragment>))
: ''
}
</div>
</div>
);
}
};
export default ProductsBar;
<file_sep>import { createStore, compose } from 'redux';
import rootReducer from './reducers';
//const composeEnhancers =
//window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__() || compose;
export default createStore(rootReducer/*, composeEnhancers*/);;
<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import { useFetchData } from '../../hooks/fectCollection';
const MainCards = () => {
const [loading, data] = useFetchData('indicador', []);
return (
<div className="container-fluid card__component">
<div className="row">
<div className="card-box col-4 col-xl-3">
<h4 className="font-weight-bold">Shop by Category</h4>
<div className="row my-3" style={{}}>
{(data)
? data[0].content.map(({ image, name }, index) => {
return (
<div className="col-6 text-center" key={index}>
<Link className="none-underscore" to="#">
<img src={image} alt="galery" />
<p className="card__caption">{name}</p>
</Link>
</div>
);
})
:
<div >
there is no data
</div>
}
</div>
<Link
to="#"
>
show now
</Link>
</div>
<div className="card-box col-4 col-xl-3">
<h4 className="font-weight-bold"> AmazonBasic </h4>
<Link to="#">
<img
src={(data) ? data[1].image : ""}
alt="fullimg"
className="normalMainCard__img"
/>
</Link>
<Link to="#">show now</Link>
</div>
<div className="card-box col-4 col-xl-3">
<h4 className="font-weight-bold"> Electronics </h4>
<Link to="#">
<img
src={(data) ? data[1].image : ""}
alt="fullimg"
className="normalMainCard__img"
/>
</Link>
<Link to="/">show now</Link>
</div>
<div className="card-box d-none d-xl-block col-xl-3">
<h4 className="font-weight-bold mb-4">Sign in for the best experiece</h4>
<button className="btn btn-warning btn-block">Sign in</button>
</div>
</div>
</div>
);
}
export default MainCards;
<file_sep>import React, { useState, useEffect } from 'react';
import { db } from '../settings/firebase';
export const useFetchData = (collection, dependencies) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
async function fetchData() {
setLoading(true);
const fetched = [];
try {
const response = await db.collection(collection).get()
response.forEach(doc => {
fetched.push(doc.data());
});
setData(fetched);
setLoading(false);
} catch(err) {
console.log(err);
setLoading(false);
}
}
useEffect(() => {
fetchData();
}, dependencies);
return [loading, data];
}
<file_sep>const inicialState = {
isLogged: false,
}
export default function (state = inicialState, action) {
switch(action.type) {
case 'LOGGIN_IN':
return {
...state,
isLogged: true,
}
default:
return state;
}
}
<file_sep>import * as firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "clone-83616.firebaseapp.com",
databaseURL: "https://clone-83616.firebaseio.com",
projectId: "clone-83616",
storageBucket: "clone-83616.appspot.com",
messagingSenderId: "748305419788",
appId: "1:748305419788:web:d5493ef793d8399e8a2829"
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const auth = firebase.auth();
export { db, auth };
<file_sep>import { combineReducers } from 'redux';
import auth from './auth';
import card from './card';
import products from './products';
export default combineReducers({
auth,
card,
products,
});
<file_sep>import React from 'react';
import Header from '../components/commons/Header';
import MainCards from '../components/home/MainCards';
import ProductsBar from '../components/home/ProductsBar';
const Home = () => {
return (
<div className="home__container">
<Header />
<div className="banner__home">
<img
className="banner-image"
src="https://images-na.ssl-images-amazon.com/images/G/01/AmazonExports/Fuji/2020/May/Hero/Fuji_TallHero_Home_v2_en_US_1x._CB429090084_.jpg"
alt="banner"
/>
</div>
<div className="content__home">
<MainCards />
<ProductsBar collection={'indicator_bar'} />
<ProductsBar collection={'indicator_bar'} />
<MainCards />
<ProductsBar collection={'indicator_bar'} />
<br />
<br />
<br />
</div>
</div>
);
};
export default Home;
| 38804b4c9e4105cdb77de4051634fadccb17617c | [
"JavaScript"
] | 8 | JavaScript | swalisoft/amazon-clone | 521ee1f7b6e4dd55bb2a7011b9b5e8971be9a861 | 760538555600878e7284d1ccf812937d9b7335f8 |
refs/heads/master | <repo_name>SizzleBae/sizzlebae-screeps<file_sep>/src/behaviour/BTNode.ts
import { Blackboard } from "./Blackboard";
export enum BTResult {
SUCCESS, FAILURE, RUNNING
}
export type ResultTree = {
node: BTNode;
result: BTResult;
}
export abstract class BTNode {
abstract init(blackboard: Blackboard): void;
abstract run(blackboard: Blackboard): BTResult;
}
export abstract class BTNodeComposite extends BTNode {
constructor(public children: BTNode[]) {
super();
}
}
export abstract class BTNodeDecorator extends BTNode {
constructor(public child: BTNode) {
super();
}
}
<file_sep>/src/behaviour/parallel-behavior/DataRefresh.ts
// import { BTNode, BTResult } from "./BTNode";
// import { Blackboard } from "./Blackboard";
// export class DataRefresh extends BTNode {
// constructor(public refreshableAlias: string) {
// super();
// }
// run(blackboard: Blackboard, callback: (result: BTResult) => void): void {
// const refreshable = blackboard[this.refreshableAlias] as { id: Id<string> | undefined };
// if (!refreshable || !refreshable.id) {
// return callback(BTResult.PANIC);
// }
// const refreshed = Game.getObjectById(refreshable.id);
// if (!refreshed) {
// return callback(BTResult.PANIC);
// }
// blackboard[this.refreshableAlias] = refreshed;
// callback(BTResult.SUCCESS);
// }
// }
<file_sep>/src/behaviour/HasUsedCapacity.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class HasUsedCapacity extends BTNode {
constructor(public targetAlias: string, public type?: ResourceConstant) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const target = blackboard.getTarget<{ store: Store<ResourceConstant, false> }>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
if (target.store.getUsedCapacity(this.type) === 0) {
return BTResult.FAILURE;
}
return BTResult.SUCCESS;
}
}
<file_sep>/src/utils/TimeFlow.ts
export class TimeFlow {
private static actions: { [tick: string]: Function[] | undefined } = {};
static submitAction(tick: number, action: Function) {
const actions = TimeFlow.actions[tick];
if (!actions) {
TimeFlow.actions[tick] = [action];
} else {
actions.push(action);
}
}
static executeTick(currentTick: number) {
const actions = TimeFlow.actions[currentTick];
if (actions) {
actions.forEach(action => action());
}
for (const tick of Object.keys(TimeFlow.actions)) {
if (Number(tick) < currentTick) {
delete TimeFlow.actions[tick];
}
}
}
}
<file_sep>/src/behaviour/Wait.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class Wait extends BTNode {
ticksWaited = 0;
constructor(public waitTicks: number) {
super();
}
init(blackboard: Blackboard): void {
this.ticksWaited = 0;
}
run(blackboard: Blackboard): BTResult {
if (this.ticksWaited >= this.waitTicks) {
return BTResult.SUCCESS;
}
this.ticksWaited++;
return BTResult.RUNNING;
}
}
<file_sep>/src/behaviour/parallel-behavior/DataFilter.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class DataFilter<T> extends BTNode {
constructor(public arrayAlias: string, public filterFunction: (a: T, blackboard: Blackboard) => boolean) {
super();
}
run(blackboard: Blackboard): BTResult {
const array = blackboard[this.arrayAlias];
if (!array || !(array instanceof Array)) {
return BTResult.PANIC;
}
const filtered = (array as T[]).filter(a => this.filterFunction(a, blackboard));
blackboard[this.arrayAlias] = filtered;
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/parallel-behavior/Repeater.ts
import { BTNode, BTResult, BTNodeDecorator } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class Repeater extends BTNodeDecorator {
private lastTick: number = 0;
private repeats: number = 0;
constructor(public maxPerTick = 99, child: BTNode) {
super(child);
}
run(blackboard: Blackboard): BTResult {
if (this.lastTick !== Game.time) {
this.lastTick = Game.time;
this.repeats = 0;
}
return this.doRepeat(blackboard);
}
private doRepeat(blackboard: Blackboard): BTResult {
let result = this.child.run(blackboard);
if (result !== BTResult.PANIC && result !== BTResult.RUNNING) {
if (this.repeats < this.maxPerTick) {
this.repeats++;
result = this.doRepeat(blackboard);
}
}
return result;
}
}
<file_sep>/src/behaviour/IsTargetInRange.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class IsTargetInRange extends BTNode {
constructor(public targetAlias: string, public positionAlias: string, public range: number) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const target = blackboard.getTarget<RoomObject>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
const position = blackboard.getTarget<RoomPosition>(this.positionAlias);
if (!position) {
return BTResult.FAILURE;
}
if (target.pos.inRangeTo(position, this.range)) {
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/GetRoom.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class GetRoom extends BTNode {
constructor(public roomName: string, public roomAlias: string) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const room = Game.rooms[this.roomName];
blackboard.setTarget(this.roomAlias, room);
if (!room) {
return BTResult.FAILURE;
}
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/GetAgentAsTarget.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class GetAgentAsTarget extends BTNode {
constructor(public targetAlias: string) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
blackboard.setTarget(this.targetAlias, blackboard.agent);
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/parallel-behavior/DataObjectRoom.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { Utils } from "utils/Utils";
export class DataObjectRoom extends BTNode {
constructor(public objectIdAlias: string, public roomAlias: string) {
super();
}
run(blackboard: Blackboard): BTResult {
const object = Utils.identify<RoomObject>(blackboard[this.objectIdAlias], [RoomObject]);
if (!object) {
return BTResult.PANIC;
}
const room = object.room;
if (room) {
blackboard[this.roomAlias] = room;
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/parallel-behavior/ActionWalkTowards.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { TimeFlow } from "../../utils/TimeFlow";
import { Utils } from "utils/Utils";
export class ActionWalkTowards extends BTNode {
private agentLastPos!: RoomPosition;
private cachedPath?: PathStep[];
constructor(public positionAlias: string, public agentIdAlias: string, public options: FindPathOpts = {}) {
super();
}
run(blackboard: Blackboard): BTResult {
const position = Utils.extractPosition(blackboard[this.positionAlias]);
if (!position) {
return BTResult.PANIC;
}
const agent = Utils.identify<Creep>(blackboard[this.agentIdAlias], [Creep]);
if (!agent) {
return BTResult.PANIC;
}
const path = this.findPath(agent.pos, position);
const result = agent.moveByPath(path);
if (result === OK) {
return BTResult.SUCCESS
} else if (result === ERR_TIRED) {
return BTResult.RUNNING;
} else {
return BTResult.FAILURE;
}
}
// private attemptMove(agentId: Id<Creep>, position: RoomPosition) {
// const agent = Utils.identify<Creep>(agentId, [Creep]);
// if (!agent) {
// return callback(BTResult.PANIC);
// }
// const path = this.findPath(agent.pos, position);
// const result = agent.moveByPath(path);
// // const result = refreshedAgent.moveTo(position, { visualizePathStyle: {} });
// this.agentLastPos = agent.pos;
// if (result === OK) {
// TimeFlow.submitAction(Game.time + 1, () => {
// const agent = Utils.identify<Creep>(agentId, [Creep]);
// if (!agent) {
// callback(BTResult.PANIC);
// } else if (agent.pos.isEqualTo(this.agentLastPos)) {
// callback(BTResult.FAILURE);
// } else {
// callback(BTResult.SUCCESS);
// }
// });
// }
// else if (result === ERR_TIRED) {
// TimeFlow.submitAction(Game.time + 1, () => this.attemptMove(agentId, position, callback));
// } else {
// callback(BTResult.FAILURE);
// }
// }
private findPath(from: RoomPosition, to: RoomPosition): PathStep[] {
if (this.cachedPath) {
// return this.cachedPath;
}
this.cachedPath = from.findPathTo(to, this.options);
// this.cachedPath.forEach(path => Game.rooms[from.roomName].visual.circle(path.x, path.y));
return this.cachedPath;
}
}
<file_sep>/src/behaviour/TransferToTarget.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class TransferToTarget extends BTNode {
// transferredCount: number = 0;
constructor(public type: ResourceConstant, public targetAlias: string, public amount?: number) {
super();
}
init(blackboard: Blackboard): void {
// this.transferredCount = 0;
}
run(blackboard: Blackboard): BTResult {
if (blackboard.agent instanceof StructureTower) {
return BTResult.FAILURE;
}
const target = blackboard.getTarget<Creep | PowerCreep | Structure<StructureConstant>>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
// const oldCount = blackboard.agent.store[this.type];
// const remaining = this.amount ? this.amount - this.transferredCount : undefined;
const result = blackboard.agent.transfer(target, this.type, this.amount);
// const newCount = blackboard.agent.store[this.type];
// const change = newCount - oldCount;
// this.transferredCount += change;
if (result === OK) {
// if (!this.amount || this.transferredCount < this.amount) {
// return BTResult.RUNNING;
// } else {
return BTResult.SUCCESS;
// }
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/parallel-behavior/DataSort.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class DataSort<T> extends BTNode {
constructor(public arrayAlias: string, public sortFunction: (a: T, b: T, blackboard: Blackboard) => number) {
super();
}
run(blackboard: Blackboard): BTResult {
const array = blackboard[this.arrayAlias];
if (!array || !(array instanceof Array)) {
return BTResult.PANIC;
}
const sorted = (array as T[]).sort((a, b) => this.sortFunction(a, b, blackboard));
blackboard[this.arrayAlias] = sorted;
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/HarvestTarget.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class HarvestTarget extends BTNode {
constructor(public targetAlias: string = 'target') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
if (blackboard.agent instanceof StructureTower) {
return BTResult.FAILURE;
}
if (blackboard.agent.store.getFreeCapacity() === 0) {
return BTResult.FAILURE;
}
const target = blackboard.getTarget<Source | Mineral<MineralConstant> | Deposit>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
const result = blackboard.agent.harvest(target);
if (result === OK) {
return BTResult.SUCCESS;
} else {
return BTResult.FAILURE;
}
}
}
<file_sep>/src/behaviour/parallel-behavior/BehaviourTree.ts
import { BTNodeDecorator, BTResult, BTNode, BTNodeComposite } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { DebugDecorator } from "./DebugDecorater";
export class BehaviourTree extends BTNodeDecorator {
readonly blackboard: Blackboard = new Blackboard();
run(): BTResult {
return this.child.run(this.blackboard);
}
debug(): this {
this.child = this.convertNodeToDebug(this.child);
return this;
}
private convertNodeToDebug(node: BTNode): DebugDecorator {
if (node instanceof BTNodeComposite) {
node.children = node.children.map(child => this.convertNodeToDebug(child));
}
else if (node instanceof BTNodeDecorator) {
node.child = this.convertNodeToDebug(node.child);
}
return new DebugDecorator(node);
}
}
<file_sep>/src/behaviour/parallel-behavior/DataPopArray.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class DataPopArray extends BTNode {
constructor(public arrayAlias: string, public poppedAlias: string) {
super();
}
run(blackboard: Blackboard): BTResult {
const array = blackboard[this.arrayAlias];
if (!array || !(array instanceof Array)) {
return BTResult.PANIC;
}
const popped = array.pop();
if (popped) {
blackboard[this.poppedAlias] = popped;
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/UpgradeController.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class UpgradeController extends BTNode {
constructor(public targetAlias: string) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
if (blackboard.agent instanceof StructureTower) {
return BTResult.FAILURE;
}
const target = blackboard.getTarget<StructureController>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
const result = blackboard.agent.upgradeController(target);
if (result === OK) {
return BTResult.SUCCESS;
} else {
return BTResult.FAILURE;
}
}
}
<file_sep>/src/behaviour/SetPosition.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class SetPosition extends BTNode {
constructor(public position: RoomPosition, public positionAlias: string = 'position') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
blackboard.setTarget(this.positionAlias, this.position);
return BTResult.SUCCESS;
}
}
<file_sep>/src/main.ts
import { ErrorMapper } from 'utils/ErrorMapper';
import { BehaviourTree as OLDBehaviourTree } from 'behaviour/BehaviourTree';
import { Sequence as OLDSequence } from 'behaviour/Sequence';
import { GetPositionFromFlag as OLDGetPositionFromFlag } from 'behaviour/GetPositionFromFlag';
import { WalkToPosition as OLDWalkToPosition } from 'behaviour/WalkToPosition';
import { GetTargetAtPosition as OLDGetTargetAtPosition } from 'behaviour/GetTargetAtPosition';
import { HarvestTarget as OLDHarvestTarget } from 'behaviour/HarvestTarget';
import { TransferToTarget as OLDTransferToTarget } from 'behaviour/TransferToTarget';
import { GetTargetRoom as OLDGetTargetRoom } from 'behaviour/GetTargetRoom';
import { FindStackInRoom as OLDFindStackInRoom } from 'behaviour/FindStackInRoom';
import { RepeatUntilFail as OLDRepeatUntilFail } from 'behaviour/RepeatUntilFail';
import { PopStackToTarget } from 'behaviour/PopStackToTarget';
import { GetTargetPosition } from 'behaviour/GetTargetPosition';
import { BuildTarget } from 'behaviour/BuildTarget';
import { GetAgentAsTarget } from 'behaviour/GetAgentAsTarget';
import { SortStackClosestFirst } from 'behaviour/SortStackClosestFirst';
import { Selector as OLDSelector } from 'behaviour/Selector';
import { UpgradeController } from 'behaviour/UpgradeController';
import { HasFreeCapacity } from 'behaviour/HasFreeCapacity';
import { Inverter as OLDInverter } from 'behaviour/Inverter';
import { PickUpTarget } from 'behaviour/PickUpTarget';
import { DropStore } from 'behaviour/DropStore';
import { HasUsedCapacity } from 'behaviour/HasUsedCapacity';
import { Logger, LogVerbosity } from 'utils/Log';
import { WithdrawFromTarget } from 'behaviour/WithdrawFromTarget';
import { RepairTarget } from 'behaviour/RepairTarget';
import { GetTargetId } from 'behaviour/GetTargetId';
import { GetTargetFromId } from 'behaviour/GetTargetFromId';
import { SortStackWithTarget } from 'behaviour/SortStackWithTarget';
import { TargetCondition } from 'behaviour/TargetCondition';
import { AlwaysSucceed as OLDAlwaysSucceed } from 'behaviour/AlwaysSucceed';
import { Wait } from 'behaviour/Wait';
import { GetRoom } from 'behaviour/GetRoom';
import { AttackTarget } from 'behaviour/AttackTarget';
import { TimeFlow } from 'utils/TimeFlow';
import { BehaviourTree } from 'behaviour/parallel-behavior/BehaviourTree';
import { Sequence } from 'behaviour/parallel-behavior/Sequence';
import { Selector } from 'behaviour/parallel-behavior/Selector';
import { ConditionInRange } from 'behaviour/parallel-behavior/ConditionInRange';
import { Inverter } from 'behaviour/parallel-behavior/Inverter';
import { ActionWalkTowards } from 'behaviour/parallel-behavior/ActionWalkTowards';
import { ActionWait } from 'behaviour/parallel-behavior/ActionWait';
import { ActionHarvest } from 'behaviour/parallel-behavior/ActionHarvest';
import { RepeatUntilFail } from 'behaviour/parallel-behavior/RepeatUntilFail';
import { DataTypesInStore } from 'behaviour/parallel-behavior/DataTypesInStore';
import { ActionDrop } from 'behaviour/parallel-behavior/ActionDrop';
import { DataPopArray } from 'behaviour/parallel-behavior/DataPopArray';
import { DataSet } from 'behaviour/parallel-behavior/DataSet';
import { ConditionCapacity } from 'behaviour/parallel-behavior/ConditionCapacity';
import { ActionTransfer } from 'behaviour/parallel-behavior/ActionTransfer';
import { ActionWithdraw } from 'behaviour/parallel-behavior/ActionWithdraw';
import { AlwaysSucceed } from 'behaviour/parallel-behavior/AlwaysSucceed';
import { DataFindInRoom } from 'behaviour/parallel-behavior/DataFindInRoom';
import { DataObjectRoom } from 'behaviour/parallel-behavior/DataObjectRoom';
import { Repeater } from 'behaviour/parallel-behavior/Repeater';
import { DataSortByDistance } from 'behaviour/parallel-behavior/DataSortByDistance';
import { Condition } from 'behaviour/parallel-behavior/Condition';
import { DataFilter } from 'behaviour/parallel-behavior/DataFilter';
import { DataSort } from 'behaviour/parallel-behavior/DataSort';
import { ActionRepair } from 'behaviour/parallel-behavior/ActionRepair';
import { Utils } from 'utils/Utils';
export type ColonyStructure = Record<string,
Record<string, {
body: BodyPartConstant[],
behaviour: OLDBehaviourTree | BehaviourTree,
spawnMe: boolean
}>
>
const BTUpgrade = () => {
return new OLDSequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', 'energy'),
new OLDGetTargetRoom('room', 'agent'),
new OLDFindStackInRoom(FIND_MY_STRUCTURES, { filter: structure => structure.structureType === 'controller' }),
new PopStackToTarget(),
new GetTargetPosition(),
new OLDWalkToPosition('position', { range: 3 }),
new UpgradeController('target')
])
}
const BTConstruct = () => {
return new OLDSequence([
new GetAgentAsTarget('agent'),
new OLDGetTargetRoom('room', 'agent'),
new OLDFindStackInRoom(FIND_CONSTRUCTION_SITES, undefined, 'stack', 'room'),
new SortStackClosestFirst('agent', 'stack'),
new OLDRepeatUntilFail(
new OLDSequence([
new PopStackToTarget('energyContainer'),
new HasUsedCapacity('agent', 'energy'),
new GetTargetPosition('energyContainer'),
new OLDWalkToPosition('position', { range: 3 }),
new BuildTarget('energyContainer')
])
)
])
}
const BTMaintain = () => {
return new OLDSequence([
new GetAgentAsTarget('agent'),
new OLDGetTargetRoom('room', 'agent'),
new OLDFindStackInRoom(FIND_STRUCTURES, { filter: structure => structure.hits < structure.hitsMax && !(structure instanceof StructureWall) }, 'maintainables', 'room'),
new SortStackClosestFirst('agent', 'maintainables'),
new OLDRepeatUntilFail(
new OLDSequence([
new HasUsedCapacity('agent', 'energy'),
new PopStackToTarget('maintainable', 'maintainables'),
new GetTargetPosition('maintainable'),
new OLDWalkToPosition('position', { range: 3 }),
new OLDRepeatUntilFail(new OLDSequence([
new GetTargetId('maintainable', 'id'),
new GetTargetFromId('id', 'maintainable'),
new RepairTarget('maintainable')
]))
])
)
])
}
const OLDBTDeliverSpawnEnergy = () => {
return new OLDSequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', 'energy'),
new OLDGetTargetRoom('room', 'agent'),
new OLDFindStackInRoom(FIND_MY_STRUCTURES, { filter: structure => structure.structureType === 'spawn' || structure.structureType === 'extension' }, 'stack', 'room'),
new SortStackClosestFirst('agent', 'stack'),
new OLDRepeatUntilFail(
new OLDSequence([
new PopStackToTarget('energyContainer'),
new OLDSelector([
new OLDInverter(new HasFreeCapacity('energyContainer', 'energy')),
new OLDSequence([
new GetTargetPosition('energyContainer'),
new OLDWalkToPosition('position', { range: 1 }),
new OLDTransferToTarget('energy', 'energyContainer')
])
])
])
)
])
}
const BTWithdrawFromTombs = (roomAlias: string) => {
return new OLDSequence([
new GetAgentAsTarget('agent'),
new OLDFindStackInRoom(FIND_TOMBSTONES, undefined, 'tombs', roomAlias),
new OLDRepeatUntilFail(new OLDSequence([
new GetAgentAsTarget('agent'),
new HasFreeCapacity('agent'),
new PopStackToTarget('tomb', 'tombs'),
new OLDAlwaysSucceed(new OLDSequence([
new GetTargetPosition('tomb'),
new OLDWalkToPosition('position', { range: 1 }),
new WithdrawFromTarget('GO', 'tomb'),
new Wait(1),
new WithdrawFromTarget('KO', 'tomb'),
new Wait(1),
new WithdrawFromTarget('ZH', 'tomb'),
new Wait(1),
new WithdrawFromTarget('UH', 'tomb'),
new Wait(1),
new WithdrawFromTarget('energy', 'tomb')
]))
])),
]);
};
const BTWithdrawFromStructures = (roomAlias: string, structureTypes: (_Constructor<Structure<StructureConstant>>)[], resourceType: ResourceConstant) => {
return new OLDSequence([
new GetAgentAsTarget('agent'),
new OLDFindStackInRoom(FIND_STRUCTURES, { filter: structure => structureTypes.some(type => structure instanceof (type as Function)) }, 'containers', roomAlias),
new SortStackWithTarget<{ store: Store<ResourceConstant, false> }, Creep>((a, b, agent) => a.store.getUsedCapacity(resourceType) - b.store.getUsedCapacity(resourceType), 'containers', 'agent'),
new OLDRepeatUntilFail(new OLDSequence([
new GetAgentAsTarget('agent'),
new HasFreeCapacity('agent', resourceType),
new PopStackToTarget('container', 'containers'),
new OLDAlwaysSucceed(new OLDSequence([
new HasUsedCapacity('container', resourceType),
new GetTargetPosition('container'),
new OLDWalkToPosition('position', { range: 1 }),
new WithdrawFromTarget(resourceType, 'container')
]))
])),
]);
};
const BTTranferToStructures = (roomAlias: string, structureTypes: (_Constructor<Structure<StructureConstant>>)[], resourceType: ResourceConstant) => {
return new OLDSequence([
new OLDFindStackInRoom(FIND_STRUCTURES, { filter: structure => structureTypes.some(type => structure instanceof (type as Function)) }, 'containers', roomAlias),
new SortStackClosestFirst('agent', 'containers'),
new OLDRepeatUntilFail(new OLDSequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', resourceType),
new PopStackToTarget('container', 'containers'),
new OLDAlwaysSucceed(new OLDSequence([
new HasFreeCapacity('container', resourceType),
new GetTargetPosition('container'),
new OLDWalkToPosition('position', { range: 1 }),
new OLDTransferToTarget(resourceType, 'container')
]))
])),
])
}
const BTRepairStructures = (roomAlias: string, structureTypes: (_Constructor<Structure<StructureConstant>>)[], maxHitsRatio = 0.8) => {
return new OLDSequence([
new OLDFindStackInRoom(FIND_STRUCTURES, {
filter: structure => structure.hits / structure.hitsMax < maxHitsRatio && structureTypes.some(type => structure instanceof (type as Function))
}, 'maintainables', roomAlias),
new SortStackWithTarget<Structure, undefined>((a, b, target) => b.hits - a.hits, 'maintainables', 'agent'),
new OLDRepeatUntilFail(
new OLDSequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', 'energy'),
new PopStackToTarget('maintainable', 'maintainables'),
new OLDAlwaysSucceed(new OLDSequence([
new GetTargetPosition('maintainable'),
new OLDWalkToPosition('position', { range: 3 }),
new OLDRepeatUntilFail(new OLDSequence([
new GetTargetId('maintainable', 'id'),
new GetTargetFromId('id', 'maintainable'),
new RepairTarget('maintainable')
]))
]))
])
)
])
}
const BTPickupDrops = (roomAlias: string, resourceTypes?: ResourceConstant[]) => {
return new OLDSequence([
new GetAgentAsTarget('agent'),
new OLDFindStackInRoom(FIND_DROPPED_RESOURCES, { filter: dropped => resourceTypes ? resourceTypes.includes(dropped.resourceType) : true }, 'allDropped', roomAlias),
new SortStackWithTarget<Resource, Creep>((a, b, agent) => a.amount - b.amount, 'allDropped', 'agent'),
new OLDRepeatUntilFail(new OLDSequence([
new GetAgentAsTarget('agent'),
new HasFreeCapacity('agent', 'energy'),
new PopStackToTarget('dropped', 'allDropped'),
new GetTargetPosition('dropped'),
new OLDWalkToPosition('position', { range: 1 }),
new PickUpTarget('dropped'),
])),
])
}
const BTHarvestThenDrop = (sourceFlag: string) => {
return new OLDSequence([
new OLDGetPositionFromFlag(sourceFlag, 'position'),
new OLDWalkToPosition('position', { range: 1 }),
new OLDGetTargetAtPosition('source', 'harvestable'),
new GetAgentAsTarget('agent'),
new OLDGetTargetRoom('room', 'agent'),
new OLDFindStackInRoom(FIND_STRUCTURES, { filter: structure => structure instanceof StructureContainer }, 'containers', 'room'),
new SortStackClosestFirst('agent', 'containers'),
new OLDAlwaysSucceed(new PopStackToTarget('container', 'containers')),
new OLDRepeatUntilFail(new OLDSequence([
new OLDSelector([
new OLDTransferToTarget('energy', 'container'),
new DropStore('energy')
]),
new OLDHarvestTarget('harvestable'),
new Wait(1)
]))
])
}
const BTHarvest = (sourceFlag: string) => {
return new OLDSelector([
new OLDSequence([
new GetAgentAsTarget('agent'),
new OLDInverter(new HasFreeCapacity('agent', 'energy'))
]),
new OLDSequence([
new OLDGetPositionFromFlag(sourceFlag),
new OLDWalkToPosition('position', { range: 1 }),
new OLDGetTargetAtPosition('source', 'harvestable'),
new OLDRepeatUntilFail(new OLDSequence([
new OLDHarvestTarget('harvestable'),
]))
])
])
}
///////////////////////////////////////////////////////////////////////////////////////// NEW STUFF
const BTExchangeWithContainers = (containerListAlias: string, agentIdAlias: string, exchanges: { type: 'withdraw' | 'deposit', resourceType: ResourceConstant, amount?: number }[]) => {
const BTCanExchangeAny = () => new Selector(
exchanges.map(exchange => new Sequence([
new ConditionCapacity(agentIdAlias, exchange.type === 'deposit' ? 'Used' : 'Free', 'MoreThan', 0, exchange.resourceType),
new ConditionCapacity('container', exchange.type === 'deposit' ? 'Free' : 'Used', 'MoreThan', 0, exchange.resourceType)
]))
)
// const withdraws = exchanges.filter(exchange => exchange.type === 'withdraw');
// const deposits = exchanges.filter(exchange => exchange.type === 'deposit');
// const merged = withdraws
// const BTExchange = () => new Sequence([
// ])
return new RepeatUntilFail(new Sequence([
new DataFilter<string>(containerListAlias, containerId => {
const container = Utils.identify<{ store: GenericStore }>(containerId);
if (container) {
return exchanges.some(exchange =>
exchange.type === 'deposit'
? container.store.getFreeCapacity(exchange.resourceType) as number > 0
: container.store.getUsedCapacity(exchange.resourceType) as number > 0)
}
return false;
}),
new DataSortByDistance(containerListAlias, agentIdAlias),
new DataPopArray(containerListAlias, 'container'),
new DataSet('hasWalked', false),
new DataSet('canExchange', false),
new RepeatUntilFail(
new Sequence([
BTCanExchangeAny(),
new DataSet('canExchange', true),
BTWalkTo('container', 'agent', 1),
new DataSet('hasWalked', true),
new ActionWait(1)
])
),
new Selector([
new Condition(blackboard => blackboard.hasWalked as boolean),
new Condition(blackboard => !blackboard.canExchange as boolean),
new ActionWait(1)
]),
new AlwaysSucceed(true, new Sequence(exchanges.map((exchange, index) =>
new Sequence([
exchange.type === 'deposit'
? new ActionTransfer('container', agentIdAlias, exchange.resourceType, exchange.amount)
: new ActionWithdraw('container', agentIdAlias, exchange.resourceType, exchange.amount),
new ActionWait(index < exchanges.length - 1 ? 1 : 0),
])
)))
]))
}
const BTWalkTo = (positionAlias: string, agentIdAlias: string, range: number) =>
new Sequence([
new Inverter(new ConditionInRange(positionAlias, agentIdAlias, range)),
new ActionWalkTowards(positionAlias, agentIdAlias, { range }),
])
const BTDropAllInStore = (storeIdAlias: string) =>
new RepeatUntilFail(new Sequence([
new DataTypesInStore(storeIdAlias, 'storedTypes'),
new DataPopArray('storedTypes', 'storedType'),
new ActionDrop('storedType', storeIdAlias),
new ActionWait(1)
]))
const BTDropHarvest = (targetIdAlias: string, agentIdAlias: string, resourceType: ResourceConstant) =>
new Sequence([
new DataSet('resourceType', resourceType),
new RepeatUntilFail(new Sequence([
BTWalkTo(targetIdAlias, agentIdAlias, 1),
new ActionWait(1)])
),
new RepeatUntilFail(new Sequence([
new ActionHarvest(targetIdAlias, agentIdAlias),
new ActionWait(1),
new ActionDrop('resourceType', agentIdAlias),
]))
])
const BTDeliverSpawnEnergy = (roomAlias: string, agentAlias: string) => new Sequence([
new DataFindInRoom(roomAlias, 'extensions', FIND_STRUCTURES, structure => structure instanceof StructureExtension || structure instanceof StructureSpawn),
BTExchangeWithContainers('extensions', agentAlias, [{ type: 'deposit', resourceType: 'energy' }])
])
const BTFindStructuresInRoom = (roomAlias: string, resultAlias: string, types: (_Constructor<Structure<StructureConstant>>)[]) =>
new DataFindInRoom(roomAlias, resultAlias, FIND_STRUCTURES, structure => types.some(type => structure instanceof (type as () => Structure)))
const BTRepairStructuresInRoom = (roomAlias: string, agentAlias: string) =>
new Sequence([
BTFindStructuresInRoom('room', 'repairables', [StructureRoad, StructureWall, StructureRampart, StructureContainer]),
new DataFilter<Structure>('repairables', repairableId => {
const repairable = Utils.identify<Structure>(repairableId);
if (repairable) {
return repairable.hits / repairable.hitsMax < 0.8;
}
return false;
}),
new DataSort<Structure>('repairables', (a, b) => b.hits - a.hits),
new RepeatUntilFail(new Sequence([
new ConditionCapacity('agent', 'Used', 'MoreThan', 0, 'energy'),
new DataPopArray('repairables', 'repairable'),
new RepeatUntilFail(new Sequence([
BTWalkTo('repairable', 'agent', 3),
new ActionWait(1)
])),
new RepeatUntilFail(new Sequence([
new Condition(blackboard => {
const repairable = Utils.identify<Structure>(blackboard['repairable']);
if (repairable) {
return repairable.hits < repairable.hitsMax
}
return false;
}),
new ActionRepair('repairable', 'agent'),
new ActionWait(1)
]))
]))
])
const structure: ColonyStructure = {
Spawn1: {
ddss: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'work', 'work', 'carry', 'move'],
behaviour: new OLDBehaviourTree(new OLDSequence([
new GetAgentAsTarget('agent'),
new OLDGetPositionFromFlag('Upgrader1', 'position'),
new OLDWalkToPosition('position', { range: 0 }),
new OLDGetTargetRoom('room', 'agent'),
BTWithdrawFromStructures('room', [StructureStorage], 'energy'),
new OLDSequence([
BTUpgrade()
])
])),
spawnMe: true
},
ted: {
body: ['carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move'],
behaviour: new OLDBehaviourTree(new OLDSequence([
new GetRoom('E32N38', 'room'),
new OLDGetPositionFromFlag('Source3', 'position'),
new OLDWalkToPosition('position', { range: 1 }),
BTPickupDrops('room'),
BTWithdrawFromStructures('room', [StructureContainer], 'energy'),
new GetRoom('E33N38', 'room'),
BTTranferToStructures('room', [StructureStorage], 'energy')
])),
spawnMe: true
},
bob: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
new Sequence([
new DataSet('flagPos', Game.flags['Source3'].pos),
new RepeatUntilFail(
new Sequence([BTWalkTo('flagPos', 'agent', 1),
new ActionWait(1)])
),
new DataSet('source', '5bbcaecc9099fc012e6398f9'),
BTDropHarvest('source', 'agent', 'energy')
])
),
spawnMe: true
},
ned: {
body: ['work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
new Repeater(1, new Sequence([
new DataObjectRoom('agent', 'room'),
new DataFindInRoom('room', 'storages', FIND_STRUCTURES, structure => structure instanceof StructureStorage),
BTExchangeWithContainers('storages', 'agent', [{ type: 'withdraw', resourceType: 'energy' }]),
BTDeliverSpawnEnergy('room', 'agent'),
BTRepairStructuresInRoom('room', 'agent')
]))
),
spawnMe: true
},
com: {
body: ['work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
new Repeater(1, new Sequence([
new DataObjectRoom('agent', 'room'),
new DataFindInRoom('room', 'storages', FIND_STRUCTURES, structure => structure instanceof StructureStorage),
BTExchangeWithContainers('storages', 'agent', [{ type: 'withdraw', resourceType: 'energy' }]),
BTDeliverSpawnEnergy('room', 'agent'),
BTRepairStructuresInRoom('room', 'agent')
]))
),
spawnMe: true
},
krud: {
body: ['carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move'],
behaviour: new BehaviourTree(
new Repeater(1, new Sequence([
new DataObjectRoom('agent', 'room'),
new DataFindInRoom('room', 'containers', FIND_STRUCTURES, structure => structure instanceof StructureContainer),
BTExchangeWithContainers('containers', 'agent', [{ type: 'withdraw', resourceType: 'energy' }]),
new DataFindInRoom('room', 'storages', FIND_STRUCTURES, structure => structure instanceof StructureStorage),
BTExchangeWithContainers('storages', 'agent', [{ type: 'deposit', resourceType: 'energy' }]),
]))
),
spawnMe: true
},
tard: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
new Sequence([
new DataSet('source', '5bbcaeda9099fc012e639a7e'),
BTDropHarvest('source', 'agent', 'energy')
])
),
spawnMe: true
},
stud: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
new Sequence([
new DataSet('source', '5bbcaeda9099fc012e639a7f'),
BTDropHarvest('source', 'agent', 'energy')
])
),
spawnMe: true
}
}
};
const towerBehaviour = new OLDBehaviourTree(
new OLDSequence([
new OLDSequence([
new GetAgentAsTarget('agent'),
new OLDGetTargetRoom('room', 'agent'),
new OLDFindStackInRoom(FIND_HOSTILE_CREEPS, undefined, 'hostiles', 'room'),
new OLDRepeatUntilFail(new OLDSequence([
new PopStackToTarget('hostile', 'hostiles'),
new OLDRepeatUntilFail(new AttackTarget('hostile'))
]))
]),
]))
export const loop = ErrorMapper.wrapLoop(() => {
TimeFlow.executeTick(Game.time);
// console.log(`Current game tick is ${Game.time}`);
Logger.verbosity = LogVerbosity.DEBUG;
// Logger.behaviour.setAgentsFilter([Game.creeps.com]);
Logger.printTickStart();
for (const [spawnName, spawnData] of Object.entries(structure)) {
for (const [creepName, creepData] of Object.entries(spawnData)) {
const creep = Game.creeps[creepName];
if (creep) {
const behavior = creepData.behaviour;
if (behavior instanceof OLDBehaviourTree) {
behavior.tick(creep);
} else {
behavior.blackboard.agent = creep.id;
behavior.run();
}
} else if (creepData.spawnMe) {
Game.spawns[spawnName].spawnCreep(creepData.body as BodyPartConstant[], creepName);
}
}
}
for (const structure of Object.values(Game.structures)) {
if (structure instanceof StructureTower) {
towerBehaviour.tick(structure);
}
}
// Automatically delete memory of missing creeps
for (const name in Memory.creeps) {
if (!(name in Game.creeps)) {
delete Memory.creeps[name];
}
}
});
<file_sep>/src/behaviour/parallel-behavior/Selector.ts
import { BTNodeComposite, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class Selector extends BTNodeComposite {
currentIndex = 0;
run(blackboard: Blackboard): BTResult {
for (; this.currentIndex < this.children.length; this.currentIndex++) {
const currentChild = this.children[this.currentIndex];
const result = currentChild.run(blackboard);
switch (result) {
case BTResult.SUCCESS:
this.currentIndex = 0;
return BTResult.SUCCESS
case BTResult.PANIC:
this.currentIndex = 0;
return BTResult.PANIC
case BTResult.RUNNING:
return BTResult.RUNNING;
}
}
this.currentIndex = 0;
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/parallel-behavior/ActionHarvest.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { TimeFlow } from "../../utils/TimeFlow";
import { Utils } from "utils/Utils";
export class ActionHarvest extends BTNode {
constructor(public targetIdAlias: string, public agentIdAlias: string) {
super();
}
run(blackboard: Blackboard): BTResult {
const agent = Utils.identify<Creep>(blackboard[this.agentIdAlias], [Creep]);
if (!agent) {
return BTResult.PANIC;
}
const target = Utils.identify<Source | Mineral | Deposit>(blackboard[this.targetIdAlias], [Source, Mineral, Deposit]);
if (!target) {
return BTResult.PANIC;
}
const result = agent.harvest(target);
if (result === OK) {
return BTResult.SUCCESS;
} else {
return BTResult.FAILURE;
}
}
}
<file_sep>/src/behaviour/parallel-behavior/BTNode.ts
import { Blackboard } from "./Blackboard";
export enum BTResult {
SUCCESS, FAILURE, RUNNING, PANIC
}
export abstract class BTNode {
abstract run(blackboard: Blackboard): BTResult;
}
export abstract class BTNodeComposite extends BTNode {
constructor(public children: BTNode[]) {
super();
}
}
export abstract class BTNodeDecorator extends BTNode {
constructor(public child: BTNode) {
super();
}
}
<file_sep>/src/behaviour/GetRoomFromGame.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class SetPositionFromFlag extends BTNode {
constructor(public flagName: string, public positionAlias: string = 'position') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const flag = Game.flags[this.flagName];
if (flag) {
blackboard.setTarget(this.positionAlias, flag.pos);
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/SortStackClosestFirst.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class SortStackClosestFirst extends BTNode {
constructor(public targetAlias: string = 'target', public stackAlias: string = 'stack') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const stack = blackboard.getStack<RoomObject>(this.stackAlias);
if (!stack) {
return BTResult.FAILURE;
}
const target = blackboard.getTarget<RoomObject>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
const sorted = stack.sort((a, b) => target.pos.getRangeTo(b) - target.pos.getRangeTo(a));
blackboard.setStack(this.stackAlias, sorted);
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/parallel-behavior/AlwaysSucceed.ts
import { BTResult, BTNodeDecorator, BTNode, } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class AlwaysSucceed extends BTNodeDecorator {
constructor(public alwaysSucceed: boolean, child: BTNode) {
super(child)
}
run(blackboard: Blackboard): BTResult {
const result = this.child.run(blackboard);
if (result !== BTResult.RUNNING && result !== BTResult.PANIC) {
return this.alwaysSucceed ? BTResult.SUCCESS : BTResult.FAILURE
}
return result;
}
}
<file_sep>/src/behaviour/FindStackInRoom.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class FindStackInRoom<T extends FindConstant> extends BTNode {
constructor(public type: T, public options?: FilterOptions<T>, public stackAlias: string = 'stack', public roomAlias: string = 'room') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const room = blackboard.getTarget<Room>(this.roomAlias);
if (!room) {
return BTResult.FAILURE;
}
blackboard.setStack(this.stackAlias, room.find(this.type, this.options));
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/PickUpTarget.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class PickUpTarget extends BTNode {
constructor(public targetAlias: string = 'target') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
if (blackboard.agent instanceof StructureTower) {
return BTResult.FAILURE;
}
const target = blackboard.getTarget<Resource<ResourceConstant>>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
const result = blackboard.agent.pickup(target);
if (result === OK) {
return BTResult.RUNNING;
} else if (result === ERR_FULL) {
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/Inverter.ts
import { BTNode, BTResult, BTNodeDecorator } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class Inverter extends BTNodeDecorator {
constructor(child: BTNode) {
super(child);
}
init(blackboard: Blackboard): void {
this.child.init(blackboard);
}
run(blackboard: Blackboard): BTResult {
const result = this.child.run(blackboard);
if (result === BTResult.RUNNING) {
return BTResult.RUNNING;
}
if (result === BTResult.SUCCESS) {
return BTResult.FAILURE;
}
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/TargetCondition.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class TargetCondition<T> extends BTNode {
constructor(public targetAlias: string, public condition: (target: T) => boolean) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const target = blackboard.getTarget<T>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
if (this.condition(target)) {
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/parallel-behavior/ActionDrop.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { TimeFlow } from "../../utils/TimeFlow";
import { Utils } from "utils/Utils";
export class ActionDrop extends BTNode {
constructor(public resourceTypeAlias: string, public agentIdAlias: string, public amount?: number) {
super();
}
run(blackboard: Blackboard): BTResult {
const agent = Utils.identify<Creep>(blackboard[this.agentIdAlias], [Creep]);
if (!agent) {
return BTResult.PANIC;
}
const resourceType = blackboard[this.resourceTypeAlias] as ResourceConstant;
if (!resourceType || typeof resourceType !== 'string') {
return BTResult.PANIC;
}
const result = agent.drop(resourceType, this.amount);
if (result === OK) {
return BTResult.SUCCESS;
} else {
return BTResult.FAILURE;
}
}
}
<file_sep>/src/behaviour/parallel-behavior/ConditionCapacity.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { Utils } from "utils/Utils";
type CapacityType = 'Capacity' | 'Used' | 'Free';
type ConditionType = 'LessThan' | 'MoreThan' | 'EqualTo';
export class ConditionCapacity<ResourceType extends ResourceConstant> extends BTNode {
constructor(public targetIdAlias: string, public capacityType: CapacityType, public conditionType: ConditionType, public amount: number, public resourceType?: ResourceConstant) {
super();
}
run(blackboard: Blackboard): BTResult {
const target = Utils.identify<{ store: Store<ResourceType, false> }>(blackboard[this.targetIdAlias]);
if (!target || !target.store) {
return BTResult.PANIC;
}
let capacity: number | null = null;
switch (this.capacityType) {
case "Capacity":
capacity = target.store.getCapacity(this.resourceType);
break;
case "Free":
capacity = target.store.getFreeCapacity(this.resourceType);
break;
case "Used":
capacity = target.store.getUsedCapacity(this.resourceType);
break;
}
if (capacity === null) {
return BTResult.PANIC;
}
let result: boolean = false;
switch (this.conditionType) {
case "EqualTo":
result = capacity === this.amount;
break;
case "LessThan":
result = capacity < this.amount;
break;
case "MoreThan":
result = capacity > this.amount;
break;
}
if (result) {
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/parallel-behavior/Blackboard.ts
import { Logger, LogVerbosity } from "utils/Log";
export class Blackboard {
[name: string]: unknown | undefined;
// private data: Record<string, any> = {};
// get<T>(alias: string): T | undefined {
// const variable = this.data[alias];
// if (!variable) {
// Logger.print(`Attempted to use variable in blackboard that does not exits: ${alias}`, LogVerbosity.WARNING);
// }
// return variable;
// }
// set<T>(alias: string, variable: T): void {
// this.data[alias] = variable;
// }
}
<file_sep>/src/behaviour/GetTargetId.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class GetTargetId extends BTNode {
constructor(public targetAlias: string, public idAlias: string) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const target = blackboard.getTarget<any>(this.targetAlias);
if (!target || !target.id) {
return BTResult.FAILURE;
}
blackboard.setTarget(this.idAlias, target.id);
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/parallel-behavior/DataTypesInStore.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { Utils } from "utils/Utils";
export class DataTypesInStore extends BTNode {
constructor(public storeIdAlias: string, public typeArrayAlias: string) {
super();
}
run(blackboard: Blackboard): BTResult {
const container = Utils.identify<{ store: GenericStore }>(blackboard[this.storeIdAlias]);
if (!container || !container.store) {
return BTResult.PANIC;
}
const types = Object.keys(container.store);
blackboard[this.typeArrayAlias] = types;
console.log(types);
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/parallel-behavior/ConditionInRange.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { Utils } from "utils/Utils";
export class ConditionInRange extends BTNode {
constructor(public fromAlias: string, public toAlias: string, public range: number) {
super();
}
run(blackboard: Blackboard): BTResult {
const from = Utils.extractPosition(blackboard[this.fromAlias]);
if (!from) {
return BTResult.PANIC;
}
const to = Utils.extractPosition(blackboard[this.toAlias]);
if (!to) {
return BTResult.PANIC;
}
if (from.getRangeTo(to) <= this.range) {
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/BuildTarget.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class BuildTarget extends BTNode {
constructor(public targetAlias: string = 'target') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
if (blackboard.agent instanceof StructureTower) {
return BTResult.FAILURE;
}
const target = blackboard.getTarget<ConstructionSite<BuildableStructureConstant>>(this.targetAlias);
if (!target) {
console.log('Failed to run BuildTarget: Missing target')
return BTResult.FAILURE;
}
const result = blackboard.agent.build(target);
if (result === OK) {
if (blackboard.agent.store.energy > 0) {
return BTResult.RUNNING;
} else {
return BTResult.SUCCESS;
}
} else {
return BTResult.FAILURE;
}
}
}
<file_sep>/src/behaviour/AttackTarget.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class AttackTarget extends BTNode {
private hasRun: boolean = false;
constructor(public targetAlias: string) {
super();
}
init(blackboard: Blackboard): void {
this.hasRun = false;
}
run(blackboard: Blackboard): BTResult {
const target = blackboard.getTarget<AnyCreep>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
const result = this.hasRun ? OK : blackboard.agent.attack(target);
if (result === OK) {
if (this.hasRun) {
this.hasRun = false;
return BTResult.SUCCESS;
} else {
this.hasRun = true;
return BTResult.RUNNING;
}
} else {
return BTResult.FAILURE;
}
}
}
<file_sep>/src/main-test.ts
import { TimeFlow } from "utils/TimeFlow";
import { Logger, LogVerbosity } from "utils/Log";
import { ErrorMapper } from "utils/ErrorMapper";
import { Sequence } from "behaviour/parallel-behavior/Sequence";
import { DataSet } from "behaviour/parallel-behavior/DataSet";
import { ActionWalkTowards } from "behaviour/parallel-behavior/ActionWalkTowards";
import { Blackboard } from "behaviour/parallel-behavior/Blackboard";
import { ActionHarvest } from "behaviour/parallel-behavior/ActionHarvest";
import { Repeater } from "behaviour/parallel-behavior/Repeater";
import { Condition } from "behaviour/parallel-behavior/Condition";
import { ConditionInRange } from "behaviour/parallel-behavior/ConditionInRange";
import { RepeatUntilFail } from "behaviour/parallel-behavior/RepeatUntilFail";
import { BTNode } from "behaviour/parallel-behavior/BTNode";
import { BehaviourTree } from "behaviour/parallel-behavior/BehaviourTree";
import { Inverter } from "behaviour/parallel-behavior/Inverter";
import { DataFindInRoom } from "behaviour/parallel-behavior/DataFindInRoom";
import { DataObjectRoom } from "behaviour/parallel-behavior/DataObjectRoom";
import { DataPopArray } from "behaviour/parallel-behavior/DataPopArray";
import { ActionTransfer } from "behaviour/parallel-behavior/ActionTransfer";
import { DataSort } from "behaviour/parallel-behavior/DataSort";
import { Utils } from "utils/Utils";
import { ConditionCapacity } from "behaviour/parallel-behavior/ConditionCapacity";
import { ActionUpgrade } from "behaviour/parallel-behavior/ActionUpgrade";
import { Wait } from "behaviour/Wait";
import { ActionWait } from "behaviour/parallel-behavior/ActionWait";
import { DataSortByDistance } from "behaviour/parallel-behavior/DataSortByDistance";
export type ColonyStructure =
Record<string, Record<string, {
behaviour: BehaviourTree
}>>
const BTWalkTo = (positionAlias: string, agentAlias: string, options?: FindPathOpts, predicate?: BTNode) => {
const sequence = new Sequence([
new Inverter(new ConditionInRange(positionAlias, agentAlias, options ? options.range ? options.range : 0 : 0)),
new ActionWalkTowards(positionAlias, agentAlias, options),
new ActionWait(1)
])
if (predicate) {
sequence.children.unshift(predicate);
}
return new RepeatUntilFail(sequence);
}
const BTMine = (targetAlias: string, agentAlias: string) =>
new Sequence([
BTWalkTo(targetAlias, agentAlias, { range: 1 }),
new RepeatUntilFail(new Sequence([
new ConditionCapacity(agentAlias, 'Free', 'MoreThan', 0),
new ActionHarvest(targetAlias, agentAlias),
new ActionWait(1)
]))
])
const colony: ColonyStructure = {
Spawn1: {}
}
const createDefaultBehaviour = () =>
new BehaviourTree(
new Sequence([
new Sequence([
new DataObjectRoom('agent', 'room'),
new DataFindInRoom('room', 'sources', FIND_SOURCES),
new DataSortByDistance('sources', 'agent'),
new DataPopArray('sources', 'source'),
BTMine('source', 'agent')
]),
new Sequence([
new DataObjectRoom('agent', 'room'),
new DataFindInRoom('room', 'containers', FIND_STRUCTURES, structure => structure instanceof StructureSpawn || structure instanceof StructureExtension),
new RepeatUntilFail(new Sequence([
new ConditionCapacity('agent', 'Used', 'MoreThan', 0, 'energy'),
new DataPopArray('containers', 'container'),
new ConditionCapacity('container', 'Free', 'MoreThan', 0, 'energy'),
BTWalkTo('container', 'agent', { range: 1 }),
new ActionTransfer('container', 'agent', 'energy'),
]))
]),
new Sequence([
new ActionWait(1),
new DataObjectRoom('agent', 'room'),
new DataFindInRoom('room', 'controllers', FIND_STRUCTURES, structure => structure instanceof StructureController),
new DataPopArray('controllers', 'controller'),
new ConditionCapacity('agent', 'Used', 'MoreThan', 0, 'energy'),
BTWalkTo('controller', 'agent', { range: 3 }),
new RepeatUntilFail(new Sequence([
new ActionUpgrade('controller', 'agent'),
new ActionWait(1)
]))
])
])
)
export const loop = ErrorMapper.wrapLoop(() => {
Logger.verbosity = LogVerbosity.DEBUG;
Logger.printTickStart();
// Setup behaviours for creeps that dont have any
for (const [creepName, creep] of Object.entries(Game.creeps)) {
const creepData = colony['Spawn1'][creepName];
if (!creepData) {
colony['Spawn1'][creepName] = { behaviour: createDefaultBehaviour().debug() };
}
}
const spawn = Game.spawns['Spawn1'];
if (!spawn.spawning) {
spawn.spawnCreep(['work', 'carry', 'move', 'move'], 'Lauren');
}
for (const [spawnName, spawnData] of Object.entries(colony)) {
for (const [creepName, creepData] of Object.entries(spawnData)) {
const creep = Game.creeps[creepName];
if (creep) {
creepData.behaviour.blackboard.agent = creep.id;
creepData.behaviour.run();
}
}
}
TimeFlow.executeTick(Game.time);
// Automatically delete memory of missing creeps
for (const name in Memory.creeps) {
if (!(name in Game.creeps)) {
delete Memory.creeps[name];
}
}
});
<file_sep>/src/behaviour/parallel-behavior/DataFindInRoom.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class DataFindInRoom<T extends FindConstant> extends BTNode {
constructor(public roomAlias: string, public resultAlias: string, public type: T, public filter?: FilterFunction<T>) {
super();
}
run(blackboard: Blackboard): BTResult {
const room = blackboard[this.roomAlias];
if (!room || !(room instanceof Room)) {
return BTResult.PANIC;
}
const result = room.find(this.type, this.filter ? { filter: this.filter } : undefined).map((result: any) => result.id ? result.id : result);
blackboard[this.resultAlias] = result;
if (result.length > 0) {
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/Selector.ts
import { BTNode, BTResult, BTNodeComposite } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { Logger } from "utils/Log";
export class Selector extends BTNodeComposite {
currentIndex: number = 0;
childInit: boolean = false;
constructor(children: BTNode[]) {
super(children);
}
init(blackboard: Blackboard): void {
this.currentIndex = 0;
this.childInit = false;
}
run(blackboard: Blackboard, ): BTResult {
for (; this.currentIndex < this.children.length; this.currentIndex++) {
const currentChild = this.children[this.currentIndex];
if (!this.childInit) {
currentChild.init(blackboard);
this.childInit = true;
}
const result = currentChild.run(blackboard);
if (result !== BTResult.RUNNING) {
this.childInit = false;
}
if (result !== BTResult.FAILURE) {
return result;
}
}
return BTResult.FAILURE;
}
}
<file_sep>/src/main-old.ts
import { ErrorMapper } from 'utils/ErrorMapper';
import { BehaviourTree } from 'behaviour/BehaviourTree';
import { Sequence } from 'behaviour/Sequence';
import { GetPositionFromFlag as GetPositionFromFlag } from 'behaviour/GetPositionFromFlag';
import { WalkToPosition } from 'behaviour/WalkToPosition';
import { GetTargetAtPosition } from 'behaviour/GetTargetAtPosition';
import { HarvestTarget } from 'behaviour/HarvestTarget';
import { TransferToTarget } from 'behaviour/TransferToTarget';
import { GetTargetRoom } from 'behaviour/GetTargetRoom';
import { FindStackInRoom } from 'behaviour/FindStackInRoom';
import { RepeatUntilFail } from 'behaviour/RepeatUntilFail';
import { PopStackToTarget as PopStackToTarget } from 'behaviour/PopStackToTarget';
import { GetTargetPosition } from 'behaviour/GetTargetPosition';
import { BuildTarget } from 'behaviour/BuildTarget';
import { GetAgentAsTarget } from 'behaviour/GetAgentAsTarget';
import { SortStackClosestFirst } from 'behaviour/SortStackClosestFirst';
import { Selector } from 'behaviour/Selector';
import { UpgradeController } from 'behaviour/UpgradeController';
import { HasFreeCapacity } from 'behaviour/HasFreeCapacity';
import { Inverter } from 'behaviour/Inverter';
import { PickUpTarget } from 'behaviour/PickUpTarget';
import { DropStore } from 'behaviour/DropStore';
import { HasUsedCapacity } from 'behaviour/HasUsedCapacity';
import { Logger, LogVerbosity } from 'utils/Log';
import { WithdrawFromTarget } from 'behaviour/WithdrawFromTarget';
import { RepairTarget } from 'behaviour/RepairTarget';
import { GetTargetId } from 'behaviour/GetTargetId';
import { GetTargetFromId } from 'behaviour/GetTargetFromId';
import { SortStackWithTarget } from 'behaviour/SortStackWithTarget';
import { TargetCondition } from 'behaviour/TargetCondition';
import { AlwaysSucceed } from 'behaviour/AlwaysSucceed';
import { Wait } from 'behaviour/Wait';
import { GetRoom } from 'behaviour/GetRoom';
import { AttackTarget } from 'behaviour/AttackTarget';
import { TimeFlow } from 'utils/TimeFlow';
export type ColonyStructure = Record<string,
Record<string, {
body: BodyPartConstant[],
behaviour: BehaviourTree
}>
>
const BTUpgrade = () => {
return new Sequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', 'energy'),
new GetTargetRoom('room', 'agent'),
new FindStackInRoom(FIND_MY_STRUCTURES, { filter: structure => structure.structureType === 'controller' }),
new PopStackToTarget(),
new GetTargetPosition(),
new WalkToPosition('position', { range: 3 }),
new UpgradeController('target')
])
}
const BTConstruct = () => {
return new Sequence([
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
new FindStackInRoom(FIND_CONSTRUCTION_SITES, undefined, 'stack', 'room'),
new SortStackClosestFirst('agent', 'stack'),
new RepeatUntilFail(
new Sequence([
new PopStackToTarget('energyContainer'),
new HasUsedCapacity('agent', 'energy'),
new GetTargetPosition('energyContainer'),
new WalkToPosition('position', { range: 3 }),
new BuildTarget('energyContainer')
])
)
])
}
const BTMaintain = () => {
return new Sequence([
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
new FindStackInRoom(FIND_STRUCTURES, { filter: structure => structure.hits < structure.hitsMax && !(structure instanceof StructureWall) }, 'maintainables', 'room'),
new SortStackClosestFirst('agent', 'maintainables'),
new RepeatUntilFail(
new Sequence([
new HasUsedCapacity('agent', 'energy'),
new PopStackToTarget('maintainable', 'maintainables'),
new GetTargetPosition('maintainable'),
new WalkToPosition('position', { range: 3 }),
new RepeatUntilFail(new Sequence([
new GetTargetId('maintainable', 'id'),
new GetTargetFromId('id', 'maintainable'),
new RepairTarget('maintainable')
]))
])
)
])
}
const BTDeliverSpawnEnergy = () => {
return new Sequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', 'energy'),
new GetTargetRoom('room', 'agent'),
new FindStackInRoom(FIND_MY_STRUCTURES, { filter: structure => structure.structureType === 'spawn' || structure.structureType === 'extension' }, 'stack', 'room'),
new SortStackClosestFirst('agent', 'stack'),
new RepeatUntilFail(
new Sequence([
new PopStackToTarget('energyContainer'),
new Selector([
new Inverter(new HasFreeCapacity('energyContainer', 'energy')),
new Sequence([
new GetTargetPosition('energyContainer'),
new WalkToPosition('position', { range: 1 }),
new TransferToTarget('energy', 'energyContainer')
])
])
])
)
])
}
const BTWithdrawFromTombs = (roomAlias: string) => {
return new Sequence([
new GetAgentAsTarget('agent'),
new FindStackInRoom(FIND_TOMBSTONES, undefined, 'tombs', roomAlias),
new RepeatUntilFail(new Sequence([
new GetAgentAsTarget('agent'),
new HasFreeCapacity('agent'),
new PopStackToTarget('tomb', 'tombs'),
new AlwaysSucceed(new Sequence([
new GetTargetPosition('tomb'),
new WalkToPosition('position', { range: 1 }),
new WithdrawFromTarget('GO', 'tomb'),
new Wait(1),
new WithdrawFromTarget('KO', 'tomb'),
new Wait(1),
new WithdrawFromTarget('ZH', 'tomb'),
new Wait(1),
new WithdrawFromTarget('UH', 'tomb'),
new Wait(1),
new WithdrawFromTarget('energy', 'tomb')
]))
])),
]);
};
const BTWithdrawFromStructures = (roomAlias: string, structureTypes: (_Constructor<Structure<StructureConstant>>)[], resourceType: ResourceConstant) => {
return new Sequence([
new GetAgentAsTarget('agent'),
new FindStackInRoom(FIND_STRUCTURES, { filter: structure => structureTypes.some(type => structure instanceof (type as Function)) }, 'containers', roomAlias),
new SortStackWithTarget<{ store: Store<ResourceConstant, false> }, Creep>((a, b, agent) => a.store.getUsedCapacity(resourceType) - b.store.getUsedCapacity(resourceType), 'containers', 'agent'),
new RepeatUntilFail(new Sequence([
new GetAgentAsTarget('agent'),
new HasFreeCapacity('agent', resourceType),
new PopStackToTarget('container', 'containers'),
new AlwaysSucceed(new Sequence([
new HasUsedCapacity('container', resourceType),
new GetTargetPosition('container'),
new WalkToPosition('position', { range: 1 }),
new WithdrawFromTarget(resourceType, 'container')
]))
])),
]);
};
const BTTranferToStructures = (roomAlias: string, structureTypes: (_Constructor<Structure<StructureConstant>>)[], resourceType: ResourceConstant) => {
return new Sequence([
new FindStackInRoom(FIND_STRUCTURES, { filter: structure => structureTypes.some(type => structure instanceof (type as Function)) }, 'containers', roomAlias),
new SortStackClosestFirst('agent', 'containers'),
new RepeatUntilFail(new Sequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', resourceType),
new PopStackToTarget('container', 'containers'),
new AlwaysSucceed(new Sequence([
new HasFreeCapacity('container', resourceType),
new GetTargetPosition('container'),
new WalkToPosition('position', { range: 1 }),
new TransferToTarget(resourceType, 'container')
]))
])),
])
}
const BTRepairStructures = (roomAlias: string, structureTypes: (_Constructor<Structure<StructureConstant>>)[], maxHitsRatio = 0.8) => {
return new Sequence([
new FindStackInRoom(FIND_STRUCTURES, {
filter: structure => structure.hits / structure.hitsMax < maxHitsRatio && structureTypes.some(type => structure instanceof (type as Function))
}, 'maintainables', roomAlias),
new SortStackWithTarget<Structure, undefined>((a, b, target) => b.hits - a.hits, 'maintainables', 'agent'),
new RepeatUntilFail(
new Sequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', 'energy'),
new PopStackToTarget('maintainable', 'maintainables'),
new AlwaysSucceed(new Sequence([
new GetTargetPosition('maintainable'),
new WalkToPosition('position', { range: 3 }),
new RepeatUntilFail(new Sequence([
new GetTargetId('maintainable', 'id'),
new GetTargetFromId('id', 'maintainable'),
new RepairTarget('maintainable')
]))
]))
])
)
])
}
const BTPickupDrops = (roomAlias: string, resourceTypes?: ResourceConstant[]) => {
return new Sequence([
new GetAgentAsTarget('agent'),
new FindStackInRoom(FIND_DROPPED_RESOURCES, { filter: dropped => resourceTypes ? resourceTypes.includes(dropped.resourceType) : true }, 'allDropped', roomAlias),
new SortStackWithTarget<Resource, Creep>((a, b, agent) => a.amount - b.amount, 'allDropped', 'agent'),
new RepeatUntilFail(new Sequence([
new GetAgentAsTarget('agent'),
new HasFreeCapacity('agent', 'energy'),
new PopStackToTarget('dropped', 'allDropped'),
new GetTargetPosition('dropped'),
new WalkToPosition('position', { range: 1 }),
new PickUpTarget('dropped'),
])),
])
}
const BTHarvestThenDrop = (sourceFlag: string) => {
return new Sequence([
new GetPositionFromFlag(sourceFlag, 'position'),
new WalkToPosition('position', { range: 1 }),
new GetTargetAtPosition('source', 'harvestable'),
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
new FindStackInRoom(FIND_STRUCTURES, { filter: structure => structure instanceof StructureContainer }, 'containers', 'room'),
new SortStackClosestFirst('agent', 'containers'),
new AlwaysSucceed(new PopStackToTarget('container', 'containers')),
new RepeatUntilFail(new Sequence([
new Selector([
new TransferToTarget('energy', 'container'),
new DropStore('energy')
]),
new HarvestTarget('harvestable'),
new Wait(1)
]))
])
}
const BTHarvest = (sourceFlag: string) => {
return new Selector([
new Sequence([
new GetAgentAsTarget('agent'),
new Inverter(new HasFreeCapacity('agent', 'energy'))
]),
new Sequence([
new GetPositionFromFlag(sourceFlag),
new WalkToPosition('position', { range: 1 }),
new GetTargetAtPosition('source', 'harvestable'),
new RepeatUntilFail(new Sequence([
new HarvestTarget('harvestable'),
]))
])
])
}
const structure = {
Spawn1: {
ddss: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'work', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(new Sequence([
new GetAgentAsTarget('agent'),
new GetPositionFromFlag('Upgrader1', 'position'),
new WalkToPosition('position', { range: 0 }),
new GetTargetRoom('room', 'agent'),
BTWithdrawFromStructures('room', [StructureStorage], 'energy'),
new Sequence([
BTUpgrade()
])
])),
spawnMe: true
},
ted: {
body: ['carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move'],
behaviour: new BehaviourTree(new Sequence([
new GetRoom('E32N38', 'room'),
BTPickupDrops('room'),
BTWithdrawFromStructures('room', [StructureContainer], 'energy'),
new GetRoom('E33N38', 'room'),
BTTranferToStructures('room', [StructureStorage], 'energy')
])),
spawnMe: true
},
bob: {
body: ['work', 'work', 'work', 'carry', 'move', 'move'],
behaviour: new BehaviourTree(
BTHarvestThenDrop('Source3')
),
spawnMe: true
},
ned: {
body: ['work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
new Sequence([
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
BTWithdrawFromStructures('room', [StructureStorage], 'energy'),
new Sequence([
BTTranferToStructures('room', [StructureExtension, StructureSpawn], 'energy'),
BTTranferToStructures('room', [StructureTower], 'energy'),
BTConstruct(),
BTRepairStructures('room', [StructureRoad, StructureWall, StructureRampart, StructureContainer]),
BTUpgrade()
])
])),
spawnMe: true
},
com: {
body: ['work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(new Sequence([
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
BTWithdrawFromStructures('room', [StructureStorage], 'energy'),
new Sequence([
BTTranferToStructures('room', [StructureExtension, StructureSpawn], 'energy'),
BTTranferToStructures('room', [StructureTower], 'energy'),
BTConstruct(),
BTRepairStructures('room', [StructureRoad, StructureWall, StructureRampart, StructureContainer]),
BTUpgrade()
])
])),
spawnMe: true
},
krud: {
body: ['carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move'],
behaviour: new BehaviourTree(new Sequence([
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
BTPickupDrops('room'),
BTWithdrawFromStructures('room', [StructureContainer], 'energy'),
BTTranferToStructures('room', [StructureStorage], 'energy')
])),
spawnMe: true
},
tard: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
BTHarvestThenDrop('Source2')
),
spawnMe: true
},
stud: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
BTHarvestThenDrop('Source1')
),
spawnMe: true
}
}
};
const towerBehaviour = new BehaviourTree(
new Sequence([
new Sequence([
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
new FindStackInRoom(FIND_HOSTILE_CREEPS, undefined, 'hostiles', 'room'),
new RepeatUntilFail(new Sequence([
new PopStackToTarget('hostile', 'hostiles'),
new RepeatUntilFail(new AttackTarget('hostile'))
]))
]),
]))
export const loop = ErrorMapper.wrapLoop(() => {
TimeFlow.executeTick(Game.time);
// console.log(`Current game tick is ${Game.time}`);
Logger.verbosity = LogVerbosity.DEBUG;
// Logger.behaviour.setAgentsFilter([Game.creeps.com]);
Logger.printTickStart();
for (const [spawnName, spawnData] of Object.entries(structure)) {
for (const [creepName, creepData] of Object.entries(spawnData)) {
const creep = Game.creeps[creepName];
if (creep) {
creepData.behaviour.tick(creep);
} else if (creepData.spawnMe) {
Game.spawns[spawnName].spawnCreep(creepData.body as BodyPartConstant[], creepName);
}
}
}
for (const structure of Object.values(Game.structures)) {
if (structure instanceof StructureTower) {
towerBehaviour.tick(structure);
}
}
// Automatically delete memory of missing creeps
for (const name in Memory.creeps) {
if (!(name in Game.creeps)) {
delete Memory.creeps[name];
}
}
});
<file_sep>/src/behaviour/SortStackWithTarget.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class SortStackWithTarget<StackType, TargetType> extends BTNode {
constructor(public sortFunction: (a: StackType, b: StackType, target: TargetType) => number, public stackAlias: string, public targetAlias: string) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const stack = blackboard.getStack<StackType>(this.stackAlias);
if (!stack) {
return BTResult.FAILURE;
}
const target = blackboard.getTarget<TargetType>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
const sorted = stack.sort((a, b) => this.sortFunction(a, b, target));
blackboard.setStack(this.stackAlias, sorted);
return BTResult.SUCCESS;
}
}
<file_sep>/src/utils/Utils.ts
export class Utils {
static extractPosition(holder: unknown): RoomPosition | undefined {
if (holder instanceof RoomPosition) {
return holder;
}
if (typeof holder === 'string') {
holder = Game.getObjectById(holder);
}
if (holder instanceof RoomObject) {
return holder.pos;
}
return undefined;
}
static identify<T>(objectId: Id<T> | undefined | unknown, instanceOfList?: Function[]): T | undefined {
if (!objectId) {
return undefined;
}
const object = Game.getObjectById(objectId as Id<T>);
if (!object) {
return undefined;
}
if (instanceOfList && !instanceOfList.some(type => object instanceof type)) {
return undefined;
}
return object;
}
}
<file_sep>/src/behaviour/GetTargetAtPosition.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class GetTargetAtPosition extends BTNode {
constructor(public type: "constructionSite" | "creep" | "energy" | "exit" | "flag" | "mineral" | "deposit" | "nuke" | "resource" | "source" | "structure" | "terrain" | "tombstone" | "powerCreep" | "ruin"
, public targetAlias: string = 'target', public positionAlias: string = 'position') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const position = blackboard.getTarget<RoomPosition>(this.positionAlias);
if (!position) {
console.log('Failed to init GetTargetAtPosition: Missing position')
return BTResult.FAILURE;
}
blackboard.setTarget(this.targetAlias, Game.rooms[position.roomName].lookForAt(this.type, position)[0]);
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/Blackboard.ts
import { Logger, LogVerbosity } from "utils/Log";
export type Agent = Creep | StructureTower;
export class Blackboard {
private targets: Record<string, any> = {};
private stacks: Record<string, any[]> = {};
constructor(public agent: Agent) {
}
setStack<T>(stackAlias: string, stack: T[]) {
this.stacks[stackAlias] = stack;
}
setTarget<T>(targetAlias: string, target: T) {
this.targets[targetAlias] = target;
}
getTarget<T>(targetAlias: string): T | undefined {
if (!this.targets[targetAlias]) {
// Logger.print(`Attempted to use target variable in blackboard that does not exits: ${targetAlias}`, LogVerbosity.WARNING);
}
return this.targets[targetAlias];
}
getStack<T>(stackAlias: string): T[] | undefined {
if (!this.stacks[stackAlias]) {
// Logger.print(`Attempted to use stack variable in blackboard that does not exits: ${stackAlias}`, LogVerbosity.WARNING);
}
return this.stacks[stackAlias];
}
}
<file_sep>/src/behaviour/BehaviourTree.ts
import { Blackboard } from "./Blackboard";
import { BTResult, BTNode, BTNodeComposite, BTNodeDecorator } from "./BTNode";
// import { DebugDecorator } from "./DebugDecorator";
export class BehaviourTree {
blackboard?: Blackboard;
lastResult = BTResult.SUCCESS;
constructor(public root: BTNode) { }
tick(agent: Creep | StructureTower): BTResult {
if (!this.blackboard) {
this.blackboard = new Blackboard(agent);
}
this.blackboard.agent = agent;
if (this.lastResult !== BTResult.RUNNING) {
this.root.init(this.blackboard);
}
this.lastResult = this.root.run(this.blackboard);
return this.lastResult;
}
// debug(): this {
// this.root = this.convertNodeToDebug(this.root);
// return this;
// }
// convertNodeToDebug(node: BTNode): DebugDecorator {
// if (node instanceof BTNodeComposite) {
// node.children = node.children.map(child => this.convertNodeToDebug(child));
// // node.children = node.children.map(child => new DebugDecorator(child));
// }
// else if (node instanceof BTNodeDecorator) {
// node.child = this.convertNodeToDebug(node.child);
// // node.child = new DebugDecorator(node);
// }
// return new DebugDecorator(node);
// }
}
<file_sep>/src/behaviour/parallel-behavior/Condition.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class Condition extends BTNode {
constructor(public predicate: (blackboard: Blackboard) => boolean) {
super();
}
run(blackboard: Blackboard): BTResult {
if (this.predicate(blackboard)) {
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/DropStore.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class DropStore extends BTNode {
constructor(public type: ResourceConstant) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
if (blackboard.agent instanceof StructureTower) {
return BTResult.FAILURE;
}
const result = blackboard.agent.drop(this.type);
return BTResult.SUCCESS;
}
}
<file_sep>/src/types.d.ts
// example declaration file - remove these and add your own custom typings
interface CreepMemory {
role?: string;
function?: (creep: Creep) => void;
room?: string;
harvester?: {
task: 'gather' | 'deliver'
}
working?: boolean;
}
interface Memory {
uuid: number;
log: any;
}
// `global` extension samples
declare namespace NodeJS {
interface Global {
log: any;
}
}
<file_sep>/src/behaviour/RefreshTarget.ts
import { BTNode, BTResult, BTNodeDecorator } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class RefreshTarget extends BTNode {
constructor(public targetAlias: string) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const target = blackboard.getTarget<{ id: Id<string> }>(this.targetAlias);
if (!target || !target.id) {
return BTResult.FAILURE;
}
const refreshed = Game.getObjectById(target.id);
if (!refreshed) {
return BTResult.FAILURE;
}
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/parallel-behavior/ActionWait.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { TimeFlow } from "../../utils/TimeFlow";
export class ActionWait extends BTNode {
private waitUntil?: number;
constructor(public ticks: number) {
super();
}
run(blackboard: Blackboard): BTResult {
if (this.waitUntil) {
if (Game.time >= this.waitUntil) {
this.waitUntil = undefined;
return BTResult.SUCCESS;
}
} else {
if (this.ticks === 0) {
return BTResult.SUCCESS;
}
this.waitUntil = Game.time + this.ticks;
}
return BTResult.RUNNING;
}
}
<file_sep>/src/behaviour/GetTargetFromId.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class GetTargetFromId extends BTNode {
constructor(public idAlias: string, public targetAlias: string) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const id = blackboard.getTarget<string>(this.idAlias);
if (!id) {
return BTResult.FAILURE;
}
const target = Game.getObjectById(id);
if (!target) {
return BTResult.FAILURE;
}
blackboard.setTarget(this.targetAlias, target);
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/PopStackToTarget.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class PopStackToTarget extends BTNode {
constructor(public targetAlias: string = 'target', public stackAlias: string = 'stack') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const stack = blackboard.getStack(this.stackAlias);
if (!stack) {
return BTResult.FAILURE;
}
const target = stack.pop();
if (!target) {
return BTResult.FAILURE;
}
blackboard.setTarget(this.targetAlias, target);
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/parallel-behavior/RepeatUntilFail.ts
import { BTResult, BTNodeDecorator } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class RepeatUntilFail extends BTNodeDecorator {
run(blackboard: Blackboard): BTResult {
let result: BTResult;
do {
result = this.child.run(blackboard);
}
while (result === BTResult.SUCCESS)
if (result === BTResult.FAILURE) {
return BTResult.SUCCESS;
}
return result;
}
}
<file_sep>/src/main-backup.ts
import { ErrorMapper } from 'utils/ErrorMapper';
import { BehaviourTree } from 'behaviour/BehaviourTree';
import { Sequence } from 'behaviour/Sequence';
import { GetPositionFromFlag as GetPositionFromFlag } from 'behaviour/GetPositionFromFlag';
import { WalkToPosition } from 'behaviour/WalkToPosition';
import { GetTargetAtPosition } from 'behaviour/GetTargetAtPosition';
import { HarvestTarget } from 'behaviour/HarvestTarget';
import { TransferToTarget } from 'behaviour/TransferToTarget';
import { GetTargetRoom } from 'behaviour/GetTargetRoom';
import { FindStackInRoom } from 'behaviour/FindStackInRoom';
import { RepeatUntilFail } from 'behaviour/RepeatUntilFail';
import { PopStackToTarget } from 'behaviour/PopStackToTarget';
import { GetTargetPosition } from 'behaviour/GetTargetPosition';
import { BuildTarget } from 'behaviour/BuildTarget';
import { GetAgentAsTarget } from 'behaviour/GetAgentAsTarget';
import { SortStackClosestFirst } from 'behaviour/SortStackClosestFirst';
import { Selector } from 'behaviour/Selector';
import { UpgradeController } from 'behaviour/UpgradeController';
import { HasFreeCapacity } from 'behaviour/HasFreeCapacity';
import { Inverter } from 'behaviour/Inverter';
import { PickUpTarget } from 'behaviour/PickUpTarget';
import { DropStore } from 'behaviour/DropStore';
import { HasUsedCapacity } from 'behaviour/HasUsedCapacity';
import { Logger, LogVerbosity } from 'utils/Log';
import { WithdrawFromTarget } from 'behaviour/WithdrawFromTarget';
import { RepairTarget } from 'behaviour/RepairTarget';
import { GetTargetId } from 'behaviour/GetTargetId';
import { GetTargetFromId } from 'behaviour/GetTargetFromId';
import { SortStackWithTarget } from 'behaviour/SortStackWithTarget';
import { TargetCondition } from 'behaviour/TargetCondition';
import { AlwaysSucceed } from 'behaviour/AlwaysSucceed';
import { AttackTarget } from 'behaviour/AttackTarget';
import { GetRoom } from 'behaviour/GetRoom';
// import { WalkTowardsPosition } from 'behaviour/WalkTowardsPosition';
import { Wait } from 'behaviour/Wait';
import { SetPosition } from 'behaviour/SetPosition';
import { RefreshTarget } from 'behaviour/RefreshTarget';
import { IsTargetInRange } from 'behaviour/IsTargetInRange';
export type ColonyStructure = Record<string,
Record<string, {
body: BodyPartConstant[],
behaviour: BehaviourTree
}>
>
const BTUpgrade = () => {
return new Sequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', 'energy'),
new GetTargetRoom('room', 'agent'),
new FindStackInRoom(FIND_MY_STRUCTURES, { filter: structure => structure.structureType === 'controller' }),
new PopStackToTarget(),
new GetTargetPosition(),
new WalkToPosition('position', { range: 3 }),
new UpgradeController('target')
])
}
const BTConstruct = (roomAlias: string) => {
return new Sequence([
new FindStackInRoom(FIND_CONSTRUCTION_SITES, undefined, 'sites', roomAlias),
new RepeatUntilFail(
new Sequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', 'energy'),
new SortStackClosestFirst('agent', 'sites'),
new PopStackToTarget('site', 'sites'),
new AlwaysSucceed(new Sequence([
new GetTargetPosition('site'),
new WalkToPosition('position', { range: 3 }),
new BuildTarget('site')
]))
])
)
])
}
const BTRepairStructures = (roomAlias: string, structureTypes: (_Constructor<Structure<StructureConstant>>)[], maxHitsRatio = 0.8) => {
return new Sequence([
new FindStackInRoom(FIND_STRUCTURES, {
filter: structure => structure.hits / structure.hitsMax < maxHitsRatio && structureTypes.some(type => structure instanceof (type as Function))
}, 'maintainables', roomAlias),
new SortStackWithTarget<Structure, undefined>((a, b, target) => b.hits - a.hits, 'maintainables', 'agent'),
new RepeatUntilFail(
new Sequence([
new GetAgentAsTarget('agent'),
new HasUsedCapacity('agent', 'energy'),
new PopStackToTarget('maintainable', 'maintainables'),
new SortStackClosestFirst('agent', 'maintainables'),
new AlwaysSucceed(new Sequence([
new GetTargetPosition('maintainable'),
new WalkToPosition('position', { range: 3 }),
new RepeatUntilFail(new Sequence([
new GetTargetId('maintainable', 'id'),
new GetTargetFromId('id', 'maintainable'),
new RepairTarget('maintainable')
]))
]))
])
)
])
}
const BTWithdrawFromStructures = (roomAlias: string, structureTypes: (_Constructor<Structure<StructureConstant>>)[], resourceType: ResourceConstant) => {
return new Sequence([
new GetAgentAsTarget('agent'),
new FindStackInRoom(FIND_STRUCTURES, { filter: structure => structureTypes.some(type => structure instanceof (type as Function)) }, 'containers', roomAlias),
new SortStackWithTarget<{ store: Store<ResourceConstant, false> }, Creep>((a, b, agent) => a.store.getUsedCapacity(resourceType) - b.store.getUsedCapacity(resourceType), 'containers', 'agent'),
new RepeatUntilFail(new Sequence([
new GetAgentAsTarget('agent'),
new PopStackToTarget('container', 'containers'),
new SortStackClosestFirst('agent', 'containers'),
new AlwaysSucceed(new Sequence([
new GetTargetPosition('container'),
new RepeatUntilFail(new Sequence([
new RefreshTarget('agent'),
new HasFreeCapacity('agent', resourceType),
new RefreshTarget('container'),
new HasUsedCapacity('container', resourceType),
new WalkToPosition('position', { range: 1 }),
// new WalkTowardsPosition('position', { range: 1 }),
// new Inverter(new IsTargetInRange('agent', 'position', 1)),
new Wait(1)
])),
new WithdrawFromTarget(resourceType, 'container')
]))
])),
]);
};
const BTTranferToStructures = (roomAlias: string, structureTypes: (_Constructor<Structure<StructureConstant>>)[], resourceType: ResourceConstant) => {
return new Sequence([
new FindStackInRoom(FIND_STRUCTURES, { filter: structure => structureTypes.some(type => structure instanceof (type as Function)) }, 'containers', roomAlias),
new RepeatUntilFail(new Sequence([
new GetAgentAsTarget('agent'),
new SortStackClosestFirst('agent', 'containers'),
new PopStackToTarget('container', 'containers'),
new GetTargetPosition('container', 'position'),
new RepeatUntilFail(new Sequence([
new WalkToPosition('position', { range: 1 }),
new RefreshTarget('agent'),
new HasUsedCapacity('agent', resourceType),
new RefreshTarget('container'),
new HasFreeCapacity('container', resourceType),
new TransferToTarget(resourceType, 'container'),
]))
])),
])
}
const BTPickupDrops = (roomAlias: string, resourceTypes?: ResourceConstant[]) => {
return new Sequence([
new GetAgentAsTarget('agent'),
new FindStackInRoom(FIND_DROPPED_RESOURCES, { filter: dropped => resourceTypes ? resourceTypes.includes(dropped.resourceType) : true }, 'allDropped', roomAlias),
new SortStackWithTarget<Resource, Creep>((a, b, agent) => a.amount - b.amount, 'allDropped', 'agent'),
new RepeatUntilFail(new Sequence([
new GetAgentAsTarget('agent'),
new HasFreeCapacity('agent', 'energy'),
new PopStackToTarget('dropped', 'allDropped'),
new GetTargetPosition('dropped'),
new WalkToPosition('position', { range: 1 }),
new PickUpTarget('dropped'),
])),
])
}
const BTHarvestThenDrop = (sourceFlag: string) => {
return new Sequence([
new GetPositionFromFlag(sourceFlag),
BTWalkTo('position', { range: 1 }),
new GetTargetAtPosition('source', 'harvestable'),
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
new FindStackInRoom(FIND_STRUCTURES, { filter: structure => structure instanceof StructureContainer }, 'containers', 'room'),
new SortStackClosestFirst('agent', 'containers'),
new AlwaysSucceed(new PopStackToTarget('container', 'containers')),
new RepeatUntilFail(new Sequence([
new Selector([
new TransferToTarget('energy', 'container'),
new DropStore('energy')
]),
new HarvestTarget('harvestable'),
new Wait(1)
]))
])
}
const BTWalkTo = (positionAlias: string, options: FindPathOpts) =>
new WalkToPosition('position', { range: 1 })
// new RepeatUntilFail(new Sequence([
// new GetAgentAsTarget('agent'),
// new Inverter(new IsTargetInRange('agent', positionAlias, options.range ? options.range : 0)),
// new Wait(1)
// ]))
const BTHarvest = (sourceFlag: string) => {
return new Selector([
new Sequence([
new GetAgentAsTarget('agent'),
new Inverter(new HasFreeCapacity('agent', 'energy'))
]),
new Sequence([
new GetPositionFromFlag(sourceFlag),
new WalkToPosition('position', { range: 1 }),
new GetTargetAtPosition('source', 'harvestable'),
new RepeatUntilFail(new Sequence([
new HarvestTarget('harvestable'),
]))
])
])
}
const structure: Record<string, Record<string, { body: string[], behaviour: BehaviourTree, spawnMe: boolean }>> = {
Spawn1: {
ddss: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'work', 'work', 'work', 'work', 'work', 'carry', 'carry', 'carry', 'move'],
behaviour: new BehaviourTree(new Sequence([
new GetRoom('E33N38', 'room'),
BTWithdrawFromStructures('room', [StructureStorage], 'energy'),
new GetPositionFromFlag('Upgrader1', 'position'),
new WalkToPosition('position', { range: 0 }),
new FindStackInRoom(FIND_MY_STRUCTURES, { filter: structure => structure instanceof StructureController }, 'controllers', 'room'),
new PopStackToTarget('controller', 'controllers'),
new RepeatUntilFail(new Sequence([
new UpgradeController('controller'),
new Wait(1)
]))
])),
spawnMe: true
},
ted: {
body: ['carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move'],
behaviour: new BehaviourTree(new Sequence([
new GetRoom('E32N38', 'room'),
BTPickupDrops('room'),
BTWithdrawFromStructures('room', [StructureContainer], 'energy'),
new GetRoom('E33N38', 'room'),
BTTranferToStructures('room', [StructureStorage], 'energy')
])),
spawnMe: true
},
bob: {
body: ['work', 'work', 'work', 'carry', 'move', 'move'],
behaviour: new BehaviourTree(
BTHarvestThenDrop('Source3')
),
spawnMe: true
},
ned: {
body: ['work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
new Sequence([
new GetRoom('E33N38', 'room'),
BTWithdrawFromStructures('room', [StructureStorage], 'energy'),
new Sequence([
BTTranferToStructures('room', [StructureExtension, StructureSpawn], 'energy'),
BTTranferToStructures('room', [StructureTower], 'energy'),
new GetRoom('E32N38', 'room'),
BTConstruct('room'),
BTRepairStructures('room', [StructureRoad, StructureContainer, StructureRampart, StructureWall]),
new GetRoom('E33N38', 'room'),
BTConstruct('room'),
BTRepairStructures('room', [StructureRoad, StructureContainer, StructureRampart, StructureWall]),
BTUpgrade()
])
])).debug(),
spawnMe: true
},
com: {
body: ['work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
new Sequence([
new GetRoom('E33N38', 'room'),
BTWithdrawFromStructures('room', [StructureStorage], 'energy'),
new Sequence([
BTTranferToStructures('room', [StructureExtension, StructureSpawn], 'energy'),
BTTranferToStructures('room', [StructureTower], 'energy'),
new GetRoom('E33N38', 'room'),
BTConstruct('room'),
BTRepairStructures('room', [StructureRoad, StructureContainer, StructureRampart, StructureWall]),
new GetRoom('E32N38', 'room'),
BTConstruct('room'),
BTRepairStructures('room', [StructureRoad, StructureContainer, StructureRampart, StructureWall]),
BTUpgrade()
])
])),
// new Sequence([
// new GetRoom('E33N38', 'room'),
// new GetPositionFromFlag('Controller', 'controllerPos'),
// new GetTargetAtPosition('structure', 'controller', 'controllerPos'),
// new SetPosition(new RoomPosition(1, 10, 'E33N38'), 'position'),
// new RepeatUntilFail(new Sequence([
// new WalkTowardsPosition('position', { range: 1 }),
// new AlwaysSucceed(new UpgradeController('controller')),
// new Wait(1)
// ])),
// ])).debug(),
spawnMe: true
},
krud: {
body: ['carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move', 'carry', 'carry', 'move'],
behaviour: new BehaviourTree(new Sequence([
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
BTPickupDrops('room'),
BTWithdrawFromStructures('room', [StructureContainer], 'energy'),
BTTranferToStructures('room', [StructureStorage], 'energy')
])),
spawnMe: true
},
tard: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
BTHarvestThenDrop('Source2')
),
spawnMe: true
},
stud: {
body: ['work', 'work', 'work', 'work', 'work', 'work', 'carry', 'move'],
behaviour: new BehaviourTree(
BTHarvestThenDrop('Source1')
),
spawnMe: true
}
}
};
const towerBehaviour = new BehaviourTree(
new Sequence([
new Sequence([
new GetAgentAsTarget('agent'),
new GetTargetRoom('room', 'agent'),
new FindStackInRoom(FIND_HOSTILE_CREEPS, undefined, 'hostiles', 'room'),
new RepeatUntilFail(new Sequence([
new PopStackToTarget('hostile', 'hostiles'),
new RepeatUntilFail(new AttackTarget('hostile'))
]))
]),
]))
export const loop = ErrorMapper.wrapLoop(() => {
// console.log(`Current game tick is ${Game.time}`);
Logger.verbosity = LogVerbosity.DEBUG;
// Logger.behaviour.setAgentsFilter([Game.creeps.com]);
Logger.printTickStart();
// console.log(Game.creeps.bob.pos.getRangeTo(Game.creeps.stud.pos));
for (const [spawnName, spawnData] of Object.entries(structure)) {
for (const [creepName, creepData] of Object.entries(spawnData)) {
const creep = Game.creeps[creepName];
if (creep) {
creepData.behaviour.tick(creep);
} else if (creepData.spawnMe) {
Game.spawns[spawnName].spawnCreep(creepData.body as BodyPartConstant[], creepName);
}
}
}
for (const structure of Object.values(Game.structures)) {
if (structure instanceof StructureTower) {
towerBehaviour.tick(structure);
}
}
// Automatically delete memory of missing creeps
for (const name in Memory.creeps) {
if (!(name in Game.creeps)) {
delete Memory.creeps[name];
}
}
});
<file_sep>/src/behaviour/GetTargetPosition.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class GetTargetPosition extends BTNode {
constructor(public targetAlias: string = 'target', public positionAlias = 'position') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const target = blackboard.getTarget<RoomObject>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
if (!target.pos) {
return BTResult.FAILURE;
}
blackboard.setTarget(this.positionAlias, target.pos);
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/WalkTowardsPosition.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class WalkTowardsPosition extends BTNode {
private path: PathStep[] | undefined;
private lastTowards: RoomPosition | undefined;
private lastPosition: RoomPosition | undefined;
private hasQueuedMove = false;
private fails = 0;
// private pathFinderOptions: PathFinderOpts = {
// roomCallback: (roomName: string) => {
// const matrix = new PathFinder.CostMatrix()
// const room = Game.rooms[roomName];
// if (room) {
// const lookAt = room.lookAtArea(0, 0, 0, 0);
// for (let y = 0; y < 50; y++) {
// for (let x = 0; x < 50; x++) {
// let cost = 0;
// lookAt[y][x].forEach(obj => {
// if (obj.structure) {
// if (obj.structure.structureType === 'road') {
// }
// }
// })
// }
// }
// matrix.set()
// }
// return matrix;
// }
// };
constructor(public positionAlias: string, public options: FindPathOpts = { range: 0 }) {
super();
}
init(blackboard: Blackboard): void {
this.fails = 0;
this.hasQueuedMove = false;
if (!(blackboard.agent instanceof Creep)) {
return;
}
const position = blackboard.getTarget<RoomPosition>(this.positionAlias);
if (!position) {
return;
}
this.findPath(blackboard.agent.pos, position, false);
}
run(blackboard: Blackboard): BTResult {
if (!(blackboard.agent instanceof Creep)) {
return BTResult.FAILURE;
}
if (!this.path) {
return BTResult.FAILURE;
}
const position = blackboard.getTarget<RoomPosition>(this.positionAlias);
if (!position) {
return BTResult.FAILURE;
}
if (this.path.length === 0) {
return BTResult.SUCCESS;
}
if (this.fails > 2) {
return BTResult.FAILURE;
}
if (this.lastPosition && this.hasQueuedMove && this.lastPosition.isEqualTo(blackboard.agent.pos)) {
this.fails++;
this.hasQueuedMove = false;
this.findPath(blackboard.agent.pos, position, false);
}
this.lastPosition = blackboard.agent.pos;
if (this.lastTowards && !position.isEqualTo(this.lastTowards)) {
this.findPath(blackboard.agent.pos, position, false);
}
const result = blackboard.agent.moveByPath(this.path);
if (result === OK) {
this.hasQueuedMove = true;
}
if (result === ERR_TIRED || result === OK) {
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
private findPath(from: RoomPosition, towards: RoomPosition, ignoreCreeps: boolean) {
this.lastTowards = towards;
this.path = from.findPathTo(towards, Object.assign({ ignoreCreeps }, this.options));
}
}
<file_sep>/src/behaviour/parallel-behavior/DataSortByDistance.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { Utils } from "utils/Utils";
export class DataSortByDistance extends BTNode {
constructor(public arrayAlias: string, public targetIdAlias: string) {
super();
}
run(blackboard: Blackboard): BTResult {
const array = blackboard[this.arrayAlias];
if (!array || !(array instanceof Array)) {
return BTResult.PANIC;
}
const target = Utils.extractPosition(blackboard[this.targetIdAlias]);
if (!target) {
return BTResult.PANIC;
}
let arrayContainsInvalidPosition = false;
const sorted = array.sort((a, b) => {
const aPos = Utils.extractPosition(a);
const bPos = Utils.extractPosition(b);
if (aPos && bPos) {
return target.getRangeTo(bPos) - target.getRangeTo(aPos);
}
arrayContainsInvalidPosition = true;
return 0;
})
if (arrayContainsInvalidPosition) {
return BTResult.PANIC;
}
blackboard[this.arrayAlias] = sorted;
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/parallel-behavior/BTLogger.ts
// import { BTNodeVisitor } from "./BTNodeVisitor";
// import { BTNode, BTNodeDecorator, BTNodeComposite, BTState } from "./BTNode";
// import { Logger, LogVerbosity } from "utils/Log";
// import { Utils } from "utils/Utils";
// export class BTLogger extends BTNodeVisitor {
// private indentLevel = 0;
// visitNode(node: BTNode): void {
// this.printNode(node, true);
// }
// visitDecorator(node: BTNodeDecorator): void {
// this.printNode(node, false);
// this.indentLevel++;
// node.child.accept(this);
// this.indentLevel--;
// this.printNode(node, true);
// }
// visitComposite(node: BTNodeComposite): void {
// this.printNode(node, false);
// this.indentLevel++;
// node.children.forEach(child => child.accept(this));
// this.indentLevel--;
// this.printNode(node, true);
// }
// private printNode(node: BTNode, withState: boolean) {
// Logger.print(`${this.getIndentString()}${node.constructor.name} ${withState ? Utils.btStateToString(node.state) : ''}`, LogVerbosity.DEBUG);
// }
// private getIndentString(): string {
// return new Array(this.indentLevel).fill('| ').join('');
// }
// }
<file_sep>/src/behaviour/parallel-behavior/BTNodeVisitor.ts
// import { BTNode, BTNodeComposite, BTNodeDecorator } from "./BTNode";
// export abstract class BTNodeVisitor {
// abstract visitNode(node: BTNode): void;
// abstract visitDecorator(node: BTNodeDecorator): void;
// abstract visitComposite(node: BTNodeComposite): void;
// }
<file_sep>/src/behaviour/RepeatUntilFail.ts
import { BTNode, BTResult, BTNodeDecorator } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class RepeatUntilFail extends BTNodeDecorator {
childInit = false;
constructor(child: BTNode) {
super(child);
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
let result: BTResult;
do {
if (!this.childInit) {
this.child.init(blackboard);
this.childInit = true;
}
result = this.child.run(blackboard);
if (result === BTResult.RUNNING) {
return BTResult.RUNNING;
}
this.childInit = false;
} while (result === BTResult.SUCCESS)
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/HasFreeCapacity.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class HasFreeCapacity extends BTNode {
constructor(public targetAlias: string, public type?: ResourceConstant) {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const target = blackboard.getTarget<{ store: Store<ResourceConstant, false> }>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
const test = Game.getObjectById((target as any).id as string);
if ((test as any).store.getFreeCapacity(this.type) > 0) {
return BTResult.SUCCESS;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/parallel-behavior/DataSet.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class DataSet<T> extends BTNode {
constructor(public alias: string, public data: T) {
super();
}
run(blackboard: Blackboard): BTResult {
blackboard[this.alias] = this.data;
return BTResult.SUCCESS;
}
}
<file_sep>/src/behaviour/parallel-behavior/ActionTransfer.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { TimeFlow } from "../../utils/TimeFlow";
import { Utils } from "utils/Utils";
export class ActionTransfer extends BTNode {
constructor(public targetIdAlias: string, public agentIdAlias: string, public resourceType: ResourceConstant, public amount?: number) {
super();
}
run(blackboard: Blackboard): BTResult {
const agent = Utils.identify<Creep>(blackboard[this.agentIdAlias], [Creep]);
if (!agent) {
return BTResult.PANIC;
}
const target = Utils.identify<Creep | Structure | PowerCreep>(blackboard[this.targetIdAlias], [Creep, Structure, PowerCreep]);
if (!target) {
return BTResult.PANIC;
}
const result = agent.transfer(target, this.resourceType, this.amount);
if (result === OK) {
return BTResult.SUCCESS;
} else {
return BTResult.FAILURE;
}
}
}
<file_sep>/src/behaviour/WalkToPosition.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class WalkToPosition extends BTNode {
public options: MoveToOpts;
private initialPath: PathStep[] | undefined;
constructor(public positionAlias: string = 'position', options?: MoveToOpts, ) {
super();
if (options) {
this.options = options;
} else {
this.options = {};
}
if (!this.options.plainCost) {
this.options.plainCost = 5;
}
if (!this.options.swampCost) {
this.options.swampCost = 10;
}
}
init(blackboard: Blackboard): void {
if (!(blackboard.agent instanceof Creep)) {
return;
}
const position = blackboard.getTarget<RoomPosition>(this.positionAlias);
if (!position) {
return;
}
const options = Object.assign<MoveToOpts, MoveToOpts>({ ignoreCreeps: true }, this.options)
this.initialPath = blackboard.agent.room.findPath(blackboard.agent.pos, position, options)
}
run(blackboard: Blackboard): BTResult {
if (blackboard.agent instanceof StructureTower) {
return BTResult.FAILURE;
}
const position = blackboard.getTarget<RoomPosition>(this.positionAlias);
if (!position) {
return BTResult.FAILURE;
}
let range = 0;
if (this.options && this.options.range) {
range = this.options.range;
}
if (blackboard.agent.pos.getRangeTo(position) <= range) {
return BTResult.SUCCESS;
}
const result = blackboard.agent.moveTo(position, this.options);
if (result === OK || result === ERR_TIRED) {
return BTResult.RUNNING;
}
return BTResult.FAILURE;
}
}
<file_sep>/src/behaviour/parallel-behavior/Parallel.ts
// import { BTNodeComposite, BTResult, BTState } from "./BTNode";
// import { Blackboard } from "./Blackboard";
// export class Parallel extends BTNodeComposite {
// run(blackboard: Blackboard, callback: (result: BTResult) => void): void {
// const results: BTResult[] = [];
// this.children.forEach(child => {
// child.state = BTState.EXECUTING;
// child.run(blackboard, result => {
// child.state = result as number;
// results.push(result);
// if (results.length === this.children.length) {
// let parallellResult = BTResult.SUCCESS;
// results.forEach(result => {
// if (result > parallellResult) {
// parallellResult = result;
// }
// })
// callback(result);
// }
// })
// });
// }
// }
<file_sep>/src/utils/Log.ts
import { DebugDecorator } from "behaviour/parallel-behavior/DebugDecorater";
import { BTNodeComposite, BTResult, BTNodeDecorator } from "behaviour/parallel-behavior/BTNode";
export enum LogVerbosity {
MESSAGE, WARNING, ERROR, DEBUG
}
export interface Log {
}
export class BehaviorLog implements Log {
// private agentsIdFilter: string[] = [];
private indentLevel = 0;
beginNode(node: DebugDecorator) {
const indent = Array(this.indentLevel).fill('| ').join('');
if (node.child instanceof BTNodeComposite || node.child instanceof BTNodeDecorator) {
Logger.print(`${indent}${node.child.constructor.name}`, LogVerbosity.DEBUG);
this.indentLevel++;
}
}
endNode(node: DebugDecorator, result: BTResult) {
if (node.child instanceof BTNodeComposite || node.child instanceof BTNodeDecorator) {
this.indentLevel--;
}
const indent = Array(this.indentLevel).fill('| ').join('');
Logger.print(`${indent}${node.child.constructor.name} - ${this.resultToString(result).toUpperCase()}`, LogVerbosity.DEBUG);
}
// agentToString(agent: Agent): string {
// if (agent instanceof Creep) {
// return agent.name;
// } else if (agent instanceof StructureTower) {
// return `tower-${agent.id}`
// }
// return 'unknown-agent-type';
// }
resultToString(result: BTResult): string {
switch (result) {
case BTResult.FAILURE:
return 'failure'
case BTResult.SUCCESS:
return 'success'
case BTResult.RUNNING:
return 'running'
case BTResult.PANIC:
return 'panic'
}
}
}
export class Logger {
static readonly behaviour: BehaviorLog = new BehaviorLog();
static verbosity: LogVerbosity = LogVerbosity.MESSAGE;
static printTickStart() {
console.log(`_________________________${Game.time}_________________________`)
}
static print(message: string, verbosity: LogVerbosity) {
if (verbosity <= this.verbosity) {
console.log(message);
}
}
}
<file_sep>/src/behaviour/DebugDecorator.ts
import { BTNode, BTResult, BTNodeDecorator } from "./BTNode";
import { Blackboard } from "./Blackboard";
import { Logger } from "utils/Log";
export class DebugDecorator extends BTNodeDecorator {
constructor(child: BTNode) {
super(child);
}
init(blackboard: Blackboard): void {
this.child.init(blackboard);
}
run(blackboard: Blackboard): BTResult {
Logger.behaviour.beginNode(this);
const result = this.child.run(blackboard);
Logger.behaviour.endNode(this, result);
return result;
}
}
<file_sep>/src/behaviour/GetTargetRoom.ts
import { BTNode, BTResult } from "./BTNode";
import { Blackboard } from "./Blackboard";
export class GetTargetRoom extends BTNode {
constructor(public roomAlias: string = 'room', public targetAlias: string = 'target') {
super();
}
init(blackboard: Blackboard): void {
}
run(blackboard: Blackboard): BTResult {
const target = blackboard.getTarget<RoomObject>(this.targetAlias);
if (!target) {
return BTResult.FAILURE;
}
blackboard.setTarget(this.roomAlias, target.room);
return BTResult.SUCCESS;
}
}
| dc563390b2651802557cf4f4d1804e85884d4045 | [
"TypeScript"
] | 70 | TypeScript | SizzleBae/sizzlebae-screeps | cc8bdc4c95f288d040faaf0e9062399a1213f940 | 833127fab9d164995439be14d5afdcbf4dff4cd4 |
refs/heads/master | <file_sep>import cv2
import numpy as np
from cv2 import imwrite
img = cv2.imread('C:\Users\Dawen\Desktop\code\green.png') ##read image from source
resxtwo = cv2.resize(img,None,None, fx=2, fy=2,interpolation = cv2.INTER_AREA) ##orginal image size multipled by 2 in X & Y dimensions
resdivtwo = cv2.resize(img,None,None, fx=0.5, fy=0.5,interpolation = cv2.INTER_AREA)## ' ' divided by (1/2) in X & Y dimensions
cv2.imwrite('green_resize_mult2.png',resxtwo) ###saved as resized x2 file
cv2.imwrite('green_resize_div2.png',resdivtwo) ###saved as resized /2 file
##read-resize-write: success
<file_sep>// HexToRGB.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
const unsigned int redHex = 0xFF0000;
const unsigned int greenHex = 0x00FF00;
const unsigned int blueHex = 0x0000FF;
void createColoredImage(int R, int G, int B);
int main()
{
//32 bits
cout << "Enter hex color code: \n";
unsigned int RGBA_Value;
cin >> std::hex >> RGBA_Value;
//RGBA:
//Blue: bits 0 .. 7
//Green: bits 8 .. 15
//Red: bits 16 .. 24
unsigned char R = (RGBA_Value & redHex) >> 16;
unsigned char G = (RGBA_Value & greenHex) >> 8;
unsigned char B = (RGBA_Value & blueHex);
cout << "RGB: " << static_cast<int>(R) << ", " << static_cast<int>(G) << ", " << static_cast<int>(B) << endl;
createColoredImage(static_cast<int>(R), static_cast<int>(G), static_cast<int>(B));
system("PAUSE");
return 0;
}
void createColoredImage(int R, int G, int B) {
Mat image(200, 200, CV_8UC3, Scalar(R, G, B));
imshow("color", image);
waitKey(0);
cvReleaseData;
cvReleaseImage;
}<file_sep>import cv2
import numpy as np
my_image = cv2.imread('C:\Users\Dawen\Desktop\code\pudge.png') ##read image
gray_image = cv2.cvtColor(my_image, cv2.COLOR_BGR2GRAY) ##convert my_image to gray image, store as "gray_image"
##create 2 seperate display windows to show the images
cv2.imshow("gray scale", gray_image) ##display gray image
cv2.imshow("pudge", my_image) ##display original
cv2.waitKey(0)
cv2.destroyAllWindows
del my_image
<file_sep>import urllib
import cv2
import numpy as np
import os
def storePositives():
url = ""
imageURLs = urllib.urlopen(url).read().decode('ascii', 'ignore').encode('ascii', 'ignore')
if not os.path.exists("pos"):
os.makedirs("pos")
picIndex = 1
for i in imageURLs.split('\n'):
try:
urllib.urlretrieve(i,"/pos/"+str(picIndex)+'.jpg')
img = cv2.imread("/pos/"+str(picIndex)+'.jpg', cv2.IMREAD_GRAYSCALE)
resized = cv2.resize(img, (100, 100))
cv2.imwrite("/pos/"+str(picIndex)+'.jpg', resized)
picIndex += 1
except Exception as err:
print err
pass
def storeNegatives():
url = ""
imageURLs = urllib.urlopen(url).read().decode('ascii', 'ignore').encode('ascii', 'ignore')
if not os.path.exists("/neg"):
os.makedirs("/neg")
picIndex = 1
for i in imageURLs.split('\n'):
try:
urllib.urlretrieve(i,"/neg/"+str(picIndex)+'.jpg')
img = cv2.imread("/neg/"+str(picIndex)+'.jpg', cv2.IMREAD_GRAYSCALE)
resized = cv2.resize(img, (100, 100))
cv2.imwrite("/neg/"+str(picIndex)+'.jpg', resized)
picIndex += 1
except Exception as err:
print err
pass
if __name__ == "__main__":
storePositives()
storeNegatives()<file_sep>
import numpy as np
import cv2
my_image = cv2.imread("C:\Users\Dawen\Desktop\code\Tuskar.png") ##read image from source/location
cv2.namedWindow("my image", cv2.WINDOW_AUTOSIZE) ##create a name for the window box
cv2.imshow("my image", my_image) ##display image in highgui with name for image
cv2.waitKey(0) ##awaits keystroke before closing display gui
cv2.destroyWindow ##destry/close display window (gui)
<file_sep>#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;
//
int main() {
//load and convert image into gray image
Mat image = imread("/home/dzou/CLionProjects/ObjectDetection/lemur.jpg", CV_LOAD_IMAGE_GRAYSCALE);
Mat CannyImage;
vector<Vec4i> hierarchy;
vector<vector<Point>> contours;
//blur image to reduce the amount of noise before using Canny edge detection
bilateralFilter(image, CannyImage, 0, 175, 3, 0);
//Canny detection
Canny(image, CannyImage, 100, 150, 3);
dilate(CannyImage, CannyImage, Mat::ones(2,2,CV_8UC1));
//find contours
findContours( CannyImage, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE ,Point(0, 0));
Mat contouredImage( image.size(), CV_8UC3, Scalar(0) );
//draw
for (int i = 0; i< contours.size(); i++) {
drawContours( contouredImage, contours, i, (255,255,255), 1, 8, hierarchy, 1, Point(0,0) );
}
//display results
imshow("normal image", image);
imshow("Contoured Image", contouredImage);
waitKey();
image.release();
return 0;
}
<file_sep>import numpy
import cv2
img_color = cv2.imread('C:\Users\MyComputer-DZ\Desktop\Code\Python\Pudge.png')
img_rgb = img_color
## blur and convert to gray image
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
img_blur = cv2.medianBlur(img_gray, 7)
### find edges on image
img_edge = cv2.adaptiveThreshold(img_blur, 255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY, 9, 2)
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
## display image
cv2.namedWindow("my image")
cv2.imshow("edges of pudge", img_edge)
## save output image
cv2.imwrite('edged_out_pudge.png', img_edge)
## await response & release resources
cv2.waitKey(0)
cv2.destroyAllWindows
## output image : https://github.com/DzouOnionGardener/OnionPy/blob/master/edged_out_pudge.png
<file_sep>import cv2
import numpy as np
my_image = cv2.imread("C:\Users\Dawen\Desktop\code\Tuskar.png")
blurred = cv2.blur(my_image,(15,15),0)
G_blurred = cv2.GaussianBlur(my_image, (15,15),0)
cv2.imshow("blurred image", blurred)
cv2.imshow("gausian blurred image", G_blurred)
cv2.waitKey(1)
cv2.destroyAllWindows
## output : https://github.com/DzouOnionGardener/OnionPy/blob/master/blur%20vs%20g-blur.png ##
<file_sep>import cv2
import numpy as np
def main():
xml_file = 'cars.xml'
car_classifier = cv2.CascadeClassifier(xml_file)
camera = cv2.VideoCapture("Baltimore.mp4")
print("video file read")
while (cv2.waitKey(1) != 27):
ret, frame = camera.read()
if not ret or frame is None:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
car = car_classifier.detectMultiScale(gray, 1.1, 3)
for (x, y, w, h) in car:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.imshow("capture", frame)
print("stopping")
camera.release()
cv2.destroyAllWindows()
return
if __name__ == "__main__":
main()
<file_sep>[Image and Video Processing in Python](http://pythonforengineers.com/image-and-video-processing-in-python/)

next step, work on localized object detection
http://dhoiem.web.engr.illinois.edu/publications/cvpr2012_objectsegmentation_qieyun.pdf
| ce095da58716ba72cee1a67b76e2ebaa975dc82f | [
"Markdown",
"Python",
"C++"
] | 10 | Python | DzouOnionGardener/opencv | 1c31a6a218936ee489439413b1e5e239891e74ac | e81c100160b2a1ccf0b798ca60c9135d27261e47 |
refs/heads/master | <file_sep>import Eris from 'eris';
import v from 'voca';
import { join, pick } from 'lodash';
import moment from 'moment';
import covid from 'novelcovid';
import schedule from 'node-schedule';
import { token, channels } from './config.json';
import { formatQuery, formatCountry, formatState } from './format';
const COMMAND = {
HELP: 'help',
SHOW: 'show',
};
const SCOPE = {
WORLD: 'world',
COUNTRY: 'country',
STATE: 'state',
};
const BOT_NAME = 'cbot';
const bot = new Eris(token);
function getHelp(channelId) {
const helpMessage = 'How to speak to me:\n\n'
+ `\`!${BOT_NAME} {command} {your query}\`\n\n`
+ 'Commands:\n\n'
+ `1. \`!${BOT_NAME} show world\`\n`
+ ' Gets latest case numbers worldwide.\n\n'
+ `2. \`!${BOT_NAME} show country [country name]\`\n`
+ ' Gets latest case numbers for the specified country.\n\n'
+ ' Example:\n'
+ ` \`!${BOT_NAME} show country us\`\n\n`
+ `3. \`!${BOT_NAME} show state [state name]\`\n`
+ ' Gets latest case numbers for the specified US state.\n\n'
+ ' Example:\n'
+ ` \`!${BOT_NAME} show state oregon\`\n`
+ ' OR\n'
+ ` \`!${BOT_NAME} show state or\`\n\n`
+ `3. \`!${BOT_NAME} help\`\n`
+ ' Prints this help message.\n\n'
+ 'Stay healthy! This bot loves you very much.';
bot.createMessage(channelId, helpMessage);
}
function getUnknown(channelId) {
bot.createMessage(channelId, `Unknown command or command missing. Type \`!${BOT_NAME} help\` for a list of commands.`);
}
async function getWorldData(channelId) {
try {
const {
cases, deaths, recovered, updated,
} = await covid.getAll();
const active = cases - deaths - recovered;
const dateLastUpdated = moment(updated).fromNow();
const message = `As of ${dateLastUpdated}, the current worldwide COVID-19 numbers are:\n\n`
+ `Total Cases: ${cases.toLocaleString('en')}\n`
+ `Deaths: ${deaths.toLocaleString('en')}\n`
+ `Recovered: ${recovered.toLocaleString('en')}\n`
+ `Active Cases: ${active.toLocaleString('en')}`;
bot.createMessage(channelId, message);
} catch (error) {
bot.createMessage(channelId, 'My apologies. I wasn\'t able to get the worldwide numbers.');
}
}
async function getCountryData(channelId, query) {
const country = formatQuery(join(query, ' '));
try {
const data = await covid.getCountry(country);
const {
cases,
todayCases,
deaths,
todayDeaths,
recovered,
active,
critical,
casesPerOneMillion,
} = pick(data, ['cases', 'todayCases', 'deaths', 'todayDeaths', 'recovered', 'active', 'critical', 'casesPerOneMillion']);
const formattedCountry = formatCountry(country);
const message = `As of the latest update, the current COVID-19 numbers in ${formattedCountry} are:\n\n`
+ `Total Cases: ${cases.toLocaleString('en')}\n`
+ `Deaths: ${deaths.toLocaleString('en')}\n`
+ `Critical Condition: ${critical.toLocaleString('en')}\n`
+ `Recovered: ${recovered.toLocaleString('en')}\n`
+ `Active Cases: ${active.toLocaleString('en')}\n`
+ `Cases Per Million: ${casesPerOneMillion.toLocaleString('en')}\n\n`
+ `New Cases Today: ${todayCases.toLocaleString('en')}\n`
+ `New Deaths Today: ${todayDeaths.toLocaleString('en')}`;
bot.createMessage(channelId, message);
} catch (error) {
bot.createMessage(channelId, `My apologies. I wasn't able to get the numbers for ${country}.`);
}
}
async function getStateData(channelId, query) {
const state = v.titleCase(formatState(join(query, ' ')));
try {
const data = await covid.getState(state);
const {
cases,
todayCases,
deaths,
todayDeaths,
active,
} = pick(data, ['cases', 'todayCases', 'deaths', 'todayDeaths', 'active']);
const recovered = cases - deaths - active;
const message = `As of the latest update, the current COVID-19 numbers in ${state} are:\n\n`
+ `Total Cases: ${cases.toLocaleString('en')}\n`
+ `Deaths: ${deaths.toLocaleString('en')}\n`
+ `Recovered: ${recovered.toLocaleString('en')}\n`
+ `Active Cases: ${active.toLocaleString('en')}\n\n`
+ `New Cases Today: ${todayCases.toLocaleString('en')}\n`
+ `New Deaths Today: ${todayDeaths.toLocaleString('en')}`;
bot.createMessage(channelId, message);
} catch (err) {
bot.createMessage(channelId, `My apologies. I wasn't able to get the numbers for ${state}.`);
}
}
async function update(channelId) {
try {
const or = await covid.getState('Oregon');
or.recovered = or.cases - or.deaths - or.active;
const oregonMessage = 'Oregon:\n\n'
+ `Total Cases: ${or.cases.toLocaleString('en')}\n`
+ `Deaths: ${or.deaths.toLocaleString('en')}\n`
+ `Recovered: ${or.recovered.toLocaleString('en')}\n`
+ `Active Cases: ${or.active.toLocaleString('en')}\n\n`
+ `New Cases Today: ${or.todayCases.toLocaleString('en')}\n`
+ `New Deaths Today: ${or.todayDeaths.toLocaleString('en')}\n\n`;
const wa = await covid.getState('Washington');
wa.recovered = wa.cases - wa.deaths - wa.active;
const washingtonMessage = 'Washington:\n\n'
+ `Total Cases: ${wa.cases.toLocaleString('en')}\n`
+ `Deaths: ${wa.deaths.toLocaleString('en')}\n`
+ `Recovered: ${wa.recovered.toLocaleString('en')}\n`
+ `Active Cases: ${wa.active.toLocaleString('en')}\n\n`
+ `New Cases Today: ${wa.todayCases.toLocaleString('en')}\n`
+ `New Deaths Today: ${wa.todayDeaths.toLocaleString('en')}`;
const fullMessage = oregonMessage + washingtonMessage;
bot.createMessage(channelId, fullMessage);
} catch (err) {
bot.createMessage(channelId, 'My apologies. I wasn\'t able to get the latest numbers for Oregon and Washington.');
}
}
bot.on('ready', () => { // When the bot is ready
console.log('Ready!'); // Log "Ready!"
});
bot.on('messageCreate', async (msg) => { // When a message is created
const message = v.lowerCase(msg.content);
if (v.startsWith(message, `!${BOT_NAME}`)) {
const messageWords = v.words(message).slice(1);
const [command, scope, ...query] = messageWords;
if (channels.allowed.includes(msg.channel.id)) {
switch (command) {
case COMMAND.SHOW:
switch (scope) {
case SCOPE.WORLD:
getWorldData(msg.channel.id, query);
break;
case SCOPE.COUNTRY:
getCountryData(msg.channel.id, query);
break;
case SCOPE.STATE:
getStateData(msg.channel.id, query);
break;
default:
getUnknown(msg.channel.id);
}
break;
case COMMAND.HELP:
getHelp(msg.channel.id);
break;
default:
getUnknown(msg.channel.id);
}
}
}
});
bot.connect(); // Get the bot to connect to Discord
schedule.scheduleJob('0 15 * * *', () => {
const updateMessage = 'This is the CRC COVID-19 Data Bot.\n'
+ `Here are the latest COVID-19 numbers in the Pacific Northwest this morning (${moment().format('D/MM/YYYY')}).`;
// bot.createMessage(channels.pnw, updateMessage);
// update(channels.pnw); // Oregon and Washington update
bot.createMessage(channels.test, updateMessage);
update(channels.test); // test Oregon and Washington update
});
schedule.scheduleJob('0 23 * * *', () => {
const updateMessage = 'This is the CRC COVID-19 Data Bot.\n'
+ `Here are the latest COVID-19 numbers in the Pacific Northwest this afternoon (${moment().format('D/MM/YYYY')}).`;
// bot.createMessage(channels.pnw, updateMessage);
// update(channels.pnw); // Oregon and Washington update
bot.createMessage(channels.test, updateMessage);
update(channels.test); // test Oregon and Washington update
});
| 8d35c87417c8657a029b340f734ffbe5108b8001 | [
"JavaScript"
] | 1 | JavaScript | merryMellody/covid-data-bot | 8b012c0b08ea938c879d382bb4ef27961e0735ec | 546edda6d52fd1eef6c3586a93fa4aefded22226 |
refs/heads/master | <repo_name>EleonoraDellamico/Minimal-Shop<file_sep>/js/index.js
console.log('eli');
function ToggleMenu() {
const element = document.getElementById('container-menu');
element.classList.toggle('showMenu');
element.addEventListener('click', ToggleMenu);
}
| d25574fc68051071a75f651eed116c6eba32a6b5 | [
"JavaScript"
] | 1 | JavaScript | EleonoraDellamico/Minimal-Shop | f2e4896a218e0a71549101cca53bb63cf7e1ebf6 | ab99f8ddb508a8989fa705e424963f0811e7778a |
refs/heads/master | <file_sep><?php
/**
* @file
*/
function modterms_manage_suggestions_form() {
// Grab available suggestions.
$suggestions = modterms_suggestions_get_all();
if (count($suggestions)) {
$header = array('term' => 'Terms Needing Approval', 'node' => 'Attached To', 'uid' => 'Who Created');
$options = array();
foreach ($suggestions as $suggestion) {
$node = node_load($suggestion->nid);
$nodelink = l($node->title, 'node/' . $node->nid);
$user = user_load($suggestion->uid);
$options[$suggestion->mtid] = array('term' => $suggestion->name, 'node' => $nodelink, 'uid' => $user->name);
}
$form['table'] = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
);
$form['controls'] = array(
'#type' => 'fieldset',
'#title' => t('Admin Controls'),
'#description' => t('Approve or deny the selected suggestions.')
);
$form['controls']['operation'] = array(
'#type' => 'select',
'#title' => t('With selected'),
'#options' => array(
'new-term' => t('Approve as new terms'),
'deny' => t('Deny and delete'),
),
'#prefix' => '<div class="container-inline">'
);
$form['controls']['submit'] = array(
'#type' => 'submit',
'#value' => t('Update'),
'#suffix' => '</div>'
);
}
else {
$form['message'] = array(
'#type' => 'markup',
'#markup' => t('There are no terms waiting for approval.')
);
}
return $form;
}
function modterms_manage_suggestions_form_submit($form, &$form_state) {
$mtids = array_filter($form_state['values']['table']);
//object_log('modterms manage', $mtids);
foreach ($mtids as $mtid) {
$suggestion = modterms_get_suggestion($mtid);
//object_log('modterms got', $suggestion);
switch ($form_state['values']['operation']) {
case 'new-term':
$term = modterms_suggestion_save_term($suggestion, $mtid);
//object_log('modterms new term', $term);
// Associate nodes that have made the suggestion with this term.
modterms_association_register($suggestion[$mtid]->fname, $suggestion[$mtid]->nid, $term->tid);
// Delete all instances of this suggestion from the unitag table (for
// this vocabulary).
modterms_suggestion_delete($mtid);
modterms_notify_submitter('approved', $userid, $modterm);
drupal_set_message(t('Suggested terms have been approved and added to the appropriate taxonomy.'));
break;
case 'deny':
$userid = $suggestion[$mtid]->uid;
$modterm = $suggestion[$mtid]->name;
modterms_suggestion_delete($mtid);
modterms_notify_submitter('denied', $userid, $modterm);
drupal_set_message(t('Suggested terms have been deleted, and the user notified.'));
break;
}
}
}
function modterms_notify_approver() {
//Find submitters organic groups.
$usergroup = og_get_groups_by_user();
//object_log('modterms notify approver user group', $usergroup);
//Find all group adminstrators (they should be the site managers) of the submitter's groups
foreach ($usergroup as $value) {
$adminmails = '';
$adminids = modterms_get_all_admin_group($value);
foreach ($adminids as $adminid) {
$aduser = user_load($adminid);
$adminmails .= $aduser->mail . ', ';
}
drupal_mail('modterms', 'modterms_submitted', $adminmails, language_default());
}
}
function modterms_get_all_admin_group($gid) {
$uids = array();
$role_admin = array('administrator member'); //TO DO look at ogranic group roles
$query = db_select('og_users_roles', 'ogur');
$query->innerJoin('og_role', 'ogr', 'ogur.rid = ogr.rid');
$rids = $query->fields('ogur', array('uid'))->condition('ogur.gid', $gid, '=')->condition('ogr.name', $role_admin, 'IN')->execute();
foreach ($rids as $item) {
$uids[] = $item->uid;
}
return $uids;
}
function modterms_notify_submitter($note, $userid, $modterm) {
$user = user_load($userid);
switch ($note) {
case 'denied':
$mail_key = 'modterms_deny';
break;
case 'approved':
$mail_key = 'modterms_approve';
break;
}
drupal_mail('modterms', $mail_key, $user->mail, user_preferred_language($user), array('account' => $user, 'term' => $modterm));
}
function modterms_mail($key, &$message, $params) {
if ($key == 'modterms_deny') {
$message['subject'] = t('Suggested term, @term_name, has been denied.', array('@term_name' => $params['term']));
$message['body'][] = t('Your submitted term, @term_name, to the MDC research site has been denied by the site managers.', array('@term_name' => $params['term']));
$message['body'][] = '';
$message['body'][] = t('Feel free to suggest more terms by adding them to the appropriate content.');
}
if ($key == 'modterms_approve') {
$message['subject'] = t('Suggested term, @term_name, has been accepted.', array('@term_name' => $params['term']));
$message['body'][] = t('Your submitted term, @term_name, to the MDC research site has been accepted by the site managers.', array('@term_name' => $params['term']));
}
if ($key == 'modterms_submitted') {
$message['subject'] = t('A new term has been submitted for approval.');
$message['body'][] = t('Please visit the <a href="@administer-page">term moderation page</a> to review new term submissions.', array('@administer-page' => url('admin/modterms/manage')));
}
}
function modterms_get_suggestion($mtid) {
$result = db_query("SELECT * FROM {modterms} m WHERE m.mtid = :mtid", array(':mtid' => $mtid));
//TO DO: check to see if better way for result return
$suggestion = array();
foreach ($result as $row) {
$suggestion[$row->mtid] = $row;
}
return $suggestion;
}
function modterms_suggestion_save_term($suggestion, $mtid) {
$newterm = new stdClass();
$newterm->vid = $suggestion[$mtid]->vid;
$newterm->name = $suggestion[$mtid]->name;
$newterm->parent = 0;
taxonomy_term_save($newterm);
$vid = $suggestion[$mtid]->vid; // Vocabulary ID
$vocab = taxonomy_vocabulary_load($vid);
$vocab_name = $vocab->machine_name;
$savedterm = taxonomy_get_term_by_name($newterm->name, $vocab_name);
//returns an array with key the tid, so simply grabbing the key
$newterm->tid = key($savedterm);
return ($newterm);
}
function modterms_association_register($fname, $nid, $tid) {
//Load the node
$node = node_load($nid);
//Find the number of term reference field ($fname)
$count = count($node->{$fname}[$node->language]);
//Add new term to the node term reference field ($fname)
$node->{$fname}[$node->language][$count]['tid'] = $tid;
//Save the node
node_save($node);
}
function modterms_suggestion_delete($mtid) {
//Query to remove the row from the modterms table
db_delete('modterms')->condition('mtid', $mtid)->execute();
}
function modterms_suggestions_get_all($pager = 25) {
$result = db_query("SELECT * FROM {modterms} m WHERE m.mtid <> 0 ORDER BY m.name ASC");
$suggestions = array();
foreach ($result as $row) {
$suggestions[$row->mtid] = $row;
}
return $suggestions;
}
<file_sep># mdc-research
This repository stores custom module code used by the MDC on its research site.
Others may use the code but it is coded towards MDC setup.
| bf1425fe1c5c8211b21613776079334ab6e161e7 | [
"Markdown",
"PHP"
] | 2 | PHP | MO-Department-of-Conservation/mdc-research | 26d7a710c466cdd4eca7acef8b827c53ad1a66e3 | 7f44391cdf5fcede5dd7365c0b2c86e9772ee355 |
refs/heads/master | <file_sep>#!/bin/bash
if ! [[ -x "$(command -v perl)" && -x "$(command -v node)" ]]; then
# echo 'Please check README.txt for installation instructions.' >&2
echo -e '\nPlease check https://github.com/mpapec/balin for installation instructions.\n' >&2
exit 1
fi
exec perl -x "$0" "$@"
#!perl
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use FindBin;
STDOUT->autoflush;
# onle one instance of watcher
use Fcntl ':flock';
flock(DATA, LOCK_EX|LOCK_NB) or die "$0 already running!\n";
umask(0077);
my $cfg_file = "$ENV{HOME}/.balin";
my $CFG = do $cfg_file;
if (!$CFG) {
# node module checks
eval { bsv()->("check", $_) } or die "Install module: npm install $_\n" for qw(bsv datapay);
unlink $cfg_file;
$CFG = setup();
print "Writing config file to $cfg_file (change default tx FEE there)\n";
open my $fh, ">", $cfg_file or die "$! $cfg_file";
print $fh serialize($CFG);
close $fh or die $!
}
print "Remember to fund onchain logs sometimes: $CFG->{address}\n";
my $q= ask("Start watching logs", "y", [qw(y n)]);
if ($q eq "y") {
print "going into background, ps -ef|grep $0 to find me..\n";
daemonize();
watcher();
}
#die Dumper my $pair = $bsv->("generate");
exit;
sub tail_file {
my ($file, %arg) = @_;
my $fh;
my $line;
return sub {
if (!$fh) {
my $ok = open $fh, "<", $file;
$ok &&= seek $fh, 0,2;
if (!$ok) { $fh = undef; die "$! $file" }
}
seek($fh, 0, 1) if !defined $line;
$line = <$fh>;
return $line;
};
}
sub watcher {
#
my $logfile = "$CFG->{data_dir}/balin.log";
open my $log, ">>", $logfile or die "$! $logfile";
$log->autoflush;
print $log scalar(gmtime), " watcher started\n";
my $bsv = bsv(
# pay => { key => "<KEY>", fee => 140 }
pay => { key => $CFG->{WIF}, fee => $CFG->{fee} }
);
my $tail = tail_file($CFG->{node_log});
while (1) {
my $arr = eval { [ $tail->() ] };
if (!$arr) {
print $log scalar(gmtime), " ", $@;
sleep 10; next;
}
my ($line) = @$arr;
if (!defined $line) { sleep 1; next; }
# print $line;
# not interested in other content
$line =~ /UpdateTip/i or next;
my %h = grep defined, $line =~ /(\S+) = (?:["'] (.+?) ["'] | (\S+) ) /xg;
my ($ts) = $line =~ /^( \d{4} - \d\d - \d\d . \S+ )/x; # or next;
$h{ts} = $ts;
# print Dumper \%h;
# print $log Dumper \%h;
my $tx = eval {
$bsv->("insert", [ "/dev/null", join ",", @h{qw( ts best )} ]);
};
my $now = gmtime;
if ($tx) {
chomp($tx);
print $log "$now wrote $h{best} to $tx tx\n";
}
else {
print $log "$now could NOT write $h{best} due $@\n";
}
}
}
sub setup {
my %ret;
my $log_file = "$ENV{HOME}/.bitcoin/bitcoind.log";
$ret{node_log} = $log_file if -f $log_file;
while (1) {
$ret{node_log} = ask("Path to node log", $ret{node_log});
open my $fh, "<", $ret{node_log} and last;
print "Can't read from '$ret{node_log}' file!\n"
}
while (1) {
$ret{data_dir} = ask("Path to my working data folder", $FindBin::Bin);
open my $fh, ">", "$ret{data_dir}/writable" and last;
print "Can't write to '$ret{data_dir}'!\n"
}
$ret{fee} = 330;
@ret{qw(address WIF)} = split ' ', bsv()->("generate");
print "\n\nSend at least \$0.10 to >> $ret{address} << before start\n\n";
#my $q= ask("bude", "n", [qw(y n)]); die $q;
return \%ret;
}
sub ask {
my ($question, $default, $pick) = @_;
my %look;
if ($pick) {
@look{ @$pick } = 1 .. @$pick;
local $" = "/";
my $opt = "? [@$pick]";
if (defined $default) { $opt =~ s/( \b$default\b )/\U$1/x; }
$question .= $opt;
}
else {
my $opt = defined $default ? "? [$default]" : "? []";
$question .= $opt;
}
while (1) {
print $question, " ";
my $in = $pick ? lc(<STDIN>) : <STDIN>;
chomp($in);
$in = $default if !length($in);
next if $pick and !$look{$in};
return $in if defined $in;
}
}
sub bsv {
my %arg = @_;
return sub {
my ($method, $opt) = @_;
if ($method eq "insert") {
my %p = ref($opt) eq "ARRAY" ? (%arg, data => $opt) : (%arg, %$opt);
return node( q<require("datapay").send(JSON.parse(process.argv[1]), function(err,val) { console.log(err||val); process.exit(!!err*1) })>, to_json(\%p) );
}
if ($method eq "generate") {
return node( q<b=require("bsv"); p=b.PrivateKey.fromRandom(); console.log(b.Address.fromPrivateKey(p).toString(), p.toWIF())> );
}
if ($method eq "check") {
return node(qq<require("$opt")>);
}
die "unknown method $method";
};
}
sub serialize {
my ($r) = @_;
use Data::Dumper;
local $Data::Dumper::Useqq =1;
# local $Data::Dumper::Pair = ":";
local $Data::Dumper::Terse =1;
# local $Data::Dumper::Indent =0;
return Dumper $r;
}
sub to_json {
my ($r) = @_;
use Data::Dumper;
local $Data::Dumper::Useqq =1;
local $Data::Dumper::Pair = ":";
local $Data::Dumper::Terse =1;
local $Data::Dumper::Indent =0;
return Dumper $r;
}
sub node {
my @arg = @_ or die "nothing to do";
my $param = join " ", map { qq('$_') } @arg;
my $flag = $arg[0] =~ /console[.]log/ ? "-e" : "-p";
my $cmd = qq(node $flag $param);
my $ret = qx(cd $FindBin::Bin && $cmd 2>&1);
# chomp($ret);
my $err;
if ($? == -1) {
$err = "failed to execute: $!\n";
}
elsif ($? & 127) {
$err = sprintf "child died with signal %d, %s coredump\n",
($? & 127), ($? & 128) ? 'with' : 'without';
}
elsif ($? >> 8) {
$err = sprintf "Error code %d when executing $cmd\n", $? >> 8;
}
if ($err) { warn $err; die $ret; }
return $ret;
}
sub daemonize {
exit if fork // die $!;
POSIX::setsid() or die $!;
exit if fork // die $!;
# umask 0; chdir '/';
#POSIX::close($_)
# for 0 .. (POSIX::sysconf(&POSIX::_SC_OPEN_MAX) ||1024);
open STDIN , '<', '/dev/null';
open STDOUT, '>', '/dev/null';
open STDERR, '>', '/dev/null';
}
sub fasync(&) {
my ($worker) = @_;
use POSIX ":sys_wait_h";
my $pid = fork() // die "can't fork!";
if (!$pid) {
$worker->();
exit(0);
}
return sub {
my ($flags, $parm) = @_;
$flags //= WNOHANG;
return $pid if $flags eq "pid";
return kill($parm //"TERM", $pid) if $flags eq "kill";
return waitpid($pid, $flags);
}
}
__DATA__
# Centos
yum install -y sudo
curl -sL https://rpm.nodesource.com/setup_10.x | sudo bash -
sudo yum install -y perl-Data-Dumper nodejs
npm install bsv datapay
# Ubuntu
apt-get update && apt-get install -y sudo curl
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs perl
npm install bsv datapay
#print qx(node -e 'console.log(JSON.stringify(
#JSON.parse(process.argv[1]), null, 2
#))' '$j' 2>&1);
#print qx(node -e '"console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 1))"' '$j' );
<file_sep># balin
Write BSV node logs as OP_RETURN data on the chain
# Ubuntu
```
apt-get update && apt-get install -y sudo curl
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs perl
npm install bsv datapay
```
# Centos
```
yum install -y sudo
curl -sL https://rpm.nodesource.com/setup_10.x | sudo bash -
sudo yum install -y perl-Data-Dumper nodejs
npm install bsv datapay
```
| 66cfbaf5d503d55998e757eb307f5f50930ecefd | [
"Markdown",
"Shell"
] | 2 | Shell | mpapec/balin | d4205c1b95a81757dd6803342f29520fe976ab39 | 6f69b3870c508238096968be5d3c2e072a72425b |
refs/heads/master | <repo_name>jnm2/example-devices-and-printers<file_sep>/src-csharp6/Native/SafeHandleArray.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Example.Native
{
/// <summary>
/// Allows you to marshal a <see cref="SafeHandle"/> array even though the marshaler is not equipped to marshal it directly.
/// </summary>
public sealed class SafeHandleArray : SafeHandle
{
private readonly SafeHandle[] handlesPrivate;
private GCHandle dangerousHandleArrayHandle;
private readonly bool[] mustReleaseArray;
/// <summary>
/// The number of handles in the array.
/// </summary>
public int Length => handlesPrivate.Length;
/// <summary>
/// Initializes a <see cref="SafeHandleArray"/> and copies the given <paramref name="handles"/> into it.
/// </summary>
public SafeHandleArray(params SafeHandle[] handles) : this(Initialize(handles))
{
}
/// <summary>
/// Initializes a <see cref="SafeHandleArray"/> and copies the given <paramref name="handles"/> into it.
/// </summary>
public SafeHandleArray(IEnumerable<SafeHandle> handles) : this(Initialize(handles))
{
}
private struct InitializationParamaters
{
public readonly SafeHandle[] HandlesPrivate;
public readonly GCHandle DangerousHandleArrayHandle;
public readonly bool[] MustReleaseArray;
public InitializationParamaters(SafeHandle[] handlesPrivate, GCHandle dangerousHandleArrayHandle, bool[] mustReleaseArray)
{
HandlesPrivate = handlesPrivate;
DangerousHandleArrayHandle = dangerousHandleArrayHandle;
MustReleaseArray = mustReleaseArray;
}
}
private static InitializationParamaters Initialize(IEnumerable<SafeHandle> handles)
{
var privateHandles = handles.ToArray(); // Create a private copy so that it cannot be mutated
var dangerousHandleArray = new IntPtr[privateHandles.Length];
var mustReleaseArray = new bool[privateHandles.Length];
for (var i = 0; i < privateHandles.Length; i++)
{
privateHandles[i].DangerousAddRef(ref mustReleaseArray[i]);
dangerousHandleArray[i] = privateHandles[i].DangerousGetHandle();
}
return new InitializationParamaters(privateHandles, GCHandle.Alloc(dangerousHandleArray, GCHandleType.Pinned), mustReleaseArray);
}
private SafeHandleArray(InitializationParamaters parameters)
: base(parameters.DangerousHandleArrayHandle.AddrOfPinnedObject(), true)
{
handlesPrivate = parameters.HandlesPrivate;
dangerousHandleArrayHandle = parameters.DangerousHandleArrayHandle;
mustReleaseArray = parameters.MustReleaseArray;
}
protected override bool ReleaseHandle()
{
for (var i = 0; i < handlesPrivate.Length; i++)
if (mustReleaseArray[i])
handlesPrivate[i].DangerousRelease();
dangerousHandleArrayHandle.Free();
return true;
}
/// <summary>When overridden in a derived class, gets a value indicating whether the handle value is invalid.</summary>
/// <returns>true if the handle value is invalid; otherwise, false.</returns>
public override bool IsInvalid => handle == IntPtr.Zero;
}
}
<file_sep>/src/Native/WinErrorCode.cs
namespace Example.Native
{
// From winerror.h
/* Generated by LinqPad snippet:
var matches = new Regex(@"#define ERROR_(?<name>\w+)\s+(?<code>\d+)L")
.Matches(File.ReadAllText(@"C:\Program Files (x86)\Windows Kits\10\Include\10.0.10586.0\shared\winerror.h"));
var sb = new StringBuilder("public enum WinErrorCode : ushort\r\n{");
for (var i = 0; i < matches.Count; i++)
{
sb.Append(i == 0 ? "\r\n " : ",\r\n ");
var doLowerCaseNext = false;
foreach (var c in matches[i].Groups["name"].Value)
{
if (c != '_') sb.Append(doLowerCaseNext ? char.ToLower(c) : c);
doLowerCaseNext = char.IsLetter(c);
}
sb.Append(" = ").Append(matches[i].Groups["code"].Value);
}
sb.Append("\r\n}").ToString().Dump();
*/
public enum WinErrorCode : ushort
{
Success = 0,
InvalidFunction = 1,
FileNotFound = 2,
PathNotFound = 3,
TooManyOpenFiles = 4,
AccessDenied = 5,
InvalidHandle = 6,
ArenaTrashed = 7,
NotEnoughMemory = 8,
InvalidBlock = 9,
BadEnvironment = 10,
BadFormat = 11,
InvalidAccess = 12,
InvalidData = 13,
Outofmemory = 14,
InvalidDrive = 15,
CurrentDirectory = 16,
NotSameDevice = 17,
NoMoreFiles = 18,
WriteProtect = 19,
BadUnit = 20,
NotReady = 21,
BadCommand = 22,
Crc = 23,
BadLength = 24,
Seek = 25,
NotDosDisk = 26,
SectorNotFound = 27,
OutOfPaper = 28,
WriteFault = 29,
ReadFault = 30,
GenFailure = 31,
SharingViolation = 32,
LockViolation = 33,
WrongDisk = 34,
SharingBufferExceeded = 36,
HandleEof = 38,
HandleDiskFull = 39,
NotSupported = 50,
RemNotList = 51,
DupName = 52,
BadNetpath = 53,
NetworkBusy = 54,
DevNotExist = 55,
TooManyCmds = 56,
AdapHdwErr = 57,
BadNetResp = 58,
UnexpNetErr = 59,
BadRemAdap = 60,
PrintqFull = 61,
NoSpoolSpace = 62,
PrintCancelled = 63,
NetnameDeleted = 64,
NetworkAccessDenied = 65,
BadDevType = 66,
BadNetName = 67,
TooManyNames = 68,
TooManySess = 69,
SharingPaused = 70,
ReqNotAccep = 71,
RedirPaused = 72,
FileExists = 80,
CannotMake = 82,
FailI24 = 83,
OutOfStructures = 84,
AlreadyAssigned = 85,
InvalidPassword = 86,
InvalidParameter = 87,
NetWriteFault = 88,
NoProcSlots = 89,
TooManySemaphores = 100,
ExclSemAlreadyOwned = 101,
SemIsSet = 102,
TooManySemRequests = 103,
InvalidAtInterruptTime = 104,
SemOwnerDied = 105,
SemUserLimit = 106,
DiskChange = 107,
DriveLocked = 108,
BrokenPipe = 109,
OpenFailed = 110,
BufferOverflow = 111,
DiskFull = 112,
NoMoreSearchHandles = 113,
InvalidTargetHandle = 114,
InvalidCategory = 117,
InvalidVerifySwitch = 118,
BadDriverLevel = 119,
CallNotImplemented = 120,
SemTimeout = 121,
InsufficientBuffer = 122,
InvalidName = 123,
InvalidLevel = 124,
NoVolumeLabel = 125,
ModNotFound = 126,
ProcNotFound = 127,
WaitNoChildren = 128,
ChildNotComplete = 129,
DirectAccessHandle = 130,
NegativeSeek = 131,
SeekOnDevice = 132,
IsJoinTarget = 133,
IsJoined = 134,
IsSubsted = 135,
NotJoined = 136,
NotSubsted = 137,
JoinToJoin = 138,
SubstToSubst = 139,
JoinToSubst = 140,
SubstToJoin = 141,
BusyDrive = 142,
SameDrive = 143,
DirNotRoot = 144,
DirNotEmpty = 145,
IsSubstPath = 146,
IsJoinPath = 147,
PathBusy = 148,
IsSubstTarget = 149,
SystemTrace = 150,
InvalidEventCount = 151,
TooManyMuxwaiters = 152,
InvalidListFormat = 153,
LabelTooLong = 154,
TooManyTcbs = 155,
SignalRefused = 156,
Discarded = 157,
NotLocked = 158,
BadThreadidAddr = 159,
BadArguments = 160,
BadPathname = 161,
SignalPending = 162,
MaxThrdsReached = 164,
LockFailed = 167,
Busy = 170,
DeviceSupportInProgress = 171,
CancelViolation = 173,
AtomicLocksNotSupported = 174,
InvalidSegmentNumber = 180,
InvalidOrdinal = 182,
AlreadyExists = 183,
InvalidFlagNumber = 186,
SemNotFound = 187,
InvalidStartingCodeseg = 188,
InvalidStackseg = 189,
InvalidModuletype = 190,
InvalidExeSignature = 191,
ExeMarkedInvalid = 192,
BadExeFormat = 193,
IteratedDataExceeds64k = 194,
InvalidMinallocsize = 195,
DynlinkFromInvalidRing = 196,
IoplNotEnabled = 197,
InvalidSegdpl = 198,
AutodatasegExceeds64k = 199,
Ring2SegMustBeMovable = 200,
RelocChainXeedsSeglim = 201,
InfloopInRelocChain = 202,
EnvvarNotFound = 203,
NoSignalSent = 205,
FilenameExcedRange = 206,
Ring2StackInUse = 207,
MetaExpansionTooLong = 208,
InvalidSignalNumber = 209,
Thread1Inactive = 210,
Locked = 212,
TooManyModules = 214,
NestingNotAllowed = 215,
ExeMachineTypeMismatch = 216,
ExeCannotModifySignedBinary = 217,
ExeCannotModifyStrongSignedBinary = 218,
FileCheckedOut = 220,
CheckoutRequired = 221,
BadFileType = 222,
FileTooLarge = 223,
FormsAuthRequired = 224,
VirusInfected = 225,
VirusDeleted = 226,
PipeLocal = 229,
BadPipe = 230,
PipeBusy = 231,
NoData = 232,
PipeNotConnected = 233,
MoreData = 234,
VcDisconnected = 240,
InvalidEaName = 254,
EaListInconsistent = 255,
NoMoreItems = 259,
CannotCopy = 266,
Directory = 267,
EasDidntFit = 275,
EaFileCorrupt = 276,
EaTableFull = 277,
InvalidEaHandle = 278,
EasNotSupported = 282,
NotOwner = 288,
TooManyPosts = 298,
PartialCopy = 299,
OplockNotGranted = 300,
InvalidOplockProtocol = 301,
DiskTooFragmented = 302,
DeletePending = 303,
IncompatibleWithGlobalShortNameRegistrySetting = 304,
ShortNamesNotEnabledOnVolume = 305,
SecurityStreamIsInconsistent = 306,
InvalidLockRange = 307,
ImageSubsystemNotPresent = 308,
NotificationGuidAlreadyDefined = 309,
InvalidExceptionHandler = 310,
DuplicatePrivileges = 311,
NoRangesProcessed = 312,
NotAllowedOnSystemFile = 313,
DiskResourcesExhausted = 314,
InvalidToken = 315,
DeviceFeatureNotSupported = 316,
MrMidNotFound = 317,
ScopeNotFound = 318,
UndefinedScope = 319,
InvalidCap = 320,
DeviceUnreachable = 321,
DeviceNoResources = 322,
DataChecksumError = 323,
IntermixedKernelEaOperation = 324,
FileLevelTrimNotSupported = 326,
OffsetAlignmentViolation = 327,
InvalidFieldInParameterList = 328,
OperationInProgress = 329,
BadDevicePath = 330,
TooManyDescriptors = 331,
ScrubDataDisabled = 332,
NotRedundantStorage = 333,
ResidentFileNotSupported = 334,
CompressedFileNotSupported = 335,
DirectoryNotSupported = 336,
NotReadFromCopy = 337,
FtWriteFailure = 338,
FtDiScanRequired = 339,
InvalidKernelInfoVersion = 340,
InvalidPepInfoVersion = 341,
ObjectNotExternallyBacked = 342,
ExternalBackingProviderUnknown = 343,
CompressionNotBeneficial = 344,
StorageTopologyIdMismatch = 345,
BlockedByParentalControls = 346,
BlockTooManyReferences = 347,
MarkedToDisallowWrites = 348,
EnclaveFailure = 349,
FailNoactionReboot = 350,
FailShutdown = 351,
FailRestart = 352,
MaxSessionsReached = 353,
NetworkAccessDeniedEdp = 354,
DeviceHintNameBufferTooSmall = 355,
EdpPolicyDeniesOperation = 356,
ThreadModeAlreadyBackground = 400,
ThreadModeNotBackground = 401,
ProcessModeAlreadyBackground = 402,
ProcessModeNotBackground = 403,
CapauthzNotDevunlocked = 450,
CapauthzChangeType = 451,
CapauthzNotProvisioned = 452,
CapauthzNotAuthorized = 453,
CapauthzNoPolicy = 454,
CapauthzDbCorrupted = 455,
DeviceHardwareError = 483,
InvalidAddress = 487,
UserProfileLoad = 500,
ArithmeticOverflow = 534,
PipeConnected = 535,
PipeListening = 536,
VerifierStop = 537,
AbiosError = 538,
Wx86Warning = 539,
Wx86Error = 540,
TimerNotCanceled = 541,
Unwind = 542,
BadStack = 543,
InvalidUnwindTarget = 544,
InvalidPortAttributes = 545,
PortMessageTooLong = 546,
InvalidQuotaLower = 547,
DeviceAlreadyAttached = 548,
InstructionMisalignment = 549,
ProfilingNotStarted = 550,
ProfilingNotStopped = 551,
CouldNotInterpret = 552,
ProfilingAtLimit = 553,
CantWait = 554,
CantTerminateSelf = 555,
UnexpectedMmCreateErr = 556,
UnexpectedMmMapError = 557,
UnexpectedMmExtendErr = 558,
BadFunctionTable = 559,
NoGuidTranslation = 560,
InvalidLdtSize = 561,
InvalidLdtOffset = 563,
InvalidLdtDescriptor = 564,
TooManyThreads = 565,
ThreadNotInProcess = 566,
PagefileQuotaExceeded = 567,
LogonServerConflict = 568,
SynchronizationRequired = 569,
NetOpenFailed = 570,
IoPrivilegeFailed = 571,
ControlCExit = 572,
MissingSystemfile = 573,
UnhandledException = 574,
AppInitFailure = 575,
PagefileCreateFailed = 576,
InvalidImageHash = 577,
NoPagefile = 578,
IllegalFloatContext = 579,
NoEventPair = 580,
DomainCtrlrConfigError = 581,
IllegalCharacter = 582,
UndefinedCharacter = 583,
FloppyVolume = 584,
BiosFailedToConnectInterrupt = 585,
BackupController = 586,
MutantLimitExceeded = 587,
FsDriverRequired = 588,
CannotLoadRegistryFile = 589,
DebugAttachFailed = 590,
SystemProcessTerminated = 591,
DataNotAccepted = 592,
VdmHardError = 593,
DriverCancelTimeout = 594,
ReplyMessageMismatch = 595,
LostWritebehindData = 596,
ClientServerParametersInvalid = 597,
NotTinyStream = 598,
StackOverflowRead = 599,
ConvertToLarge = 600,
FoundOutOfScope = 601,
AllocateBucket = 602,
MarshallOverflow = 603,
InvalidVariant = 604,
BadCompressionBuffer = 605,
AuditFailed = 606,
TimerResolutionNotSet = 607,
InsufficientLogonInfo = 608,
BadDllEntrypoint = 609,
BadServiceEntrypoint = 610,
IpAddressConflict1 = 611,
IpAddressConflict2 = 612,
RegistryQuotaLimit = 613,
NoCallbackActive = 614,
PwdTooShort = 615,
PwdTooRecent = 616,
PwdHistoryConflict = 617,
UnsupportedCompression = 618,
InvalidHwProfile = 619,
InvalidPlugplayDevicePath = 620,
QuotaListInconsistent = 621,
EvaluationExpiration = 622,
IllegalDllRelocation = 623,
DllInitFailedLogoff = 624,
ValidateContinue = 625,
NoMoreMatches = 626,
RangeListConflict = 627,
ServerSidMismatch = 628,
CantEnableDenyOnly = 629,
FloatMultipleFaults = 630,
FloatMultipleTraps = 631,
Nointerface = 632,
DriverFailedSleep = 633,
CorruptSystemFile = 634,
CommitmentMinimum = 635,
PnpRestartEnumeration = 636,
SystemImageBadSignature = 637,
PnpRebootRequired = 638,
InsufficientPower = 639,
MultipleFaultViolation = 640,
SystemShutdown = 641,
PortNotSet = 642,
DsVersionCheckFailure = 643,
RangeNotFound = 644,
NotSafeModeDriver = 646,
FailedDriverEntry = 647,
DeviceEnumerationError = 648,
MountPointNotResolved = 649,
InvalidDeviceObjectParameter = 650,
McaOccured = 651,
DriverDatabaseError = 652,
SystemHiveTooLarge = 653,
DriverFailedPriorUnload = 654,
VolsnapPrepareHibernate = 655,
HibernationFailure = 656,
PwdTooLong = 657,
FileSystemLimitation = 665,
AssertionFailure = 668,
AcpiError = 669,
WowAssertion = 670,
PnpBadMpsTable = 671,
PnpTranslationFailed = 672,
PnpIrqTranslationFailed = 673,
PnpInvalidId = 674,
WakeSystemDebugger = 675,
HandlesClosed = 676,
ExtraneousInformation = 677,
RxactCommitNecessary = 678,
MediaCheck = 679,
GuidSubstitutionMade = 680,
StoppedOnSymlink = 681,
Longjump = 682,
PlugplayQueryVetoed = 683,
UnwindConsolidate = 684,
RegistryHiveRecovered = 685,
DllMightBeInsecure = 686,
DllMightBeIncompatible = 687,
DbgExceptionNotHandled = 688,
DbgReplyLater = 689,
DbgUnableToProvideHandle = 690,
DbgTerminateThread = 691,
DbgTerminateProcess = 692,
DbgControlC = 693,
DbgPrintexceptionC = 694,
DbgRipexception = 695,
DbgControlBreak = 696,
DbgCommandException = 697,
ObjectNameExists = 698,
ThreadWasSuspended = 699,
ImageNotAtBase = 700,
RxactStateCreated = 701,
SegmentNotification = 702,
BadCurrentDirectory = 703,
FtReadRecoveryFromBackup = 704,
FtWriteRecovery = 705,
ImageMachineTypeMismatch = 706,
ReceivePartial = 707,
ReceiveExpedited = 708,
ReceivePartialExpedited = 709,
EventDone = 710,
EventPending = 711,
CheckingFileSystem = 712,
FatalAppExit = 713,
PredefinedHandle = 714,
WasUnlocked = 715,
ServiceNotification = 716,
WasLocked = 717,
LogHardError = 718,
AlreadyWin32 = 719,
ImageMachineTypeMismatchExe = 720,
NoYieldPerformed = 721,
TimerResumeIgnored = 722,
ArbitrationUnhandled = 723,
CardbusNotSupported = 724,
MpProcessorMismatch = 725,
Hibernated = 726,
ResumeHibernation = 727,
FirmwareUpdated = 728,
DriversLeakingLockedPages = 729,
WakeSystem = 730,
Wait1 = 731,
Wait2 = 732,
Wait3 = 733,
Wait63 = 734,
AbandonedWait0 = 735,
AbandonedWait63 = 736,
UserApc = 737,
KernelApc = 738,
Alerted = 739,
ElevationRequired = 740,
Reparse = 741,
OplockBreakInProgress = 742,
VolumeMounted = 743,
RxactCommitted = 744,
NotifyCleanup = 745,
PrimaryTransportConnectFailed = 746,
PageFaultTransition = 747,
PageFaultDemandZero = 748,
PageFaultCopyOnWrite = 749,
PageFaultGuardPage = 750,
PageFaultPagingFile = 751,
CachePageLocked = 752,
CrashDump = 753,
BufferAllZeros = 754,
ReparseObject = 755,
ResourceRequirementsChanged = 756,
TranslationComplete = 757,
NothingToTerminate = 758,
ProcessNotInJob = 759,
ProcessInJob = 760,
VolsnapHibernateReady = 761,
FsfilterOpCompletedSuccessfully = 762,
InterruptVectorAlreadyConnected = 763,
InterruptStillConnected = 764,
WaitForOplock = 765,
DbgExceptionHandled = 766,
DbgContinue = 767,
CallbackPopStack = 768,
CompressionDisabled = 769,
Cantfetchbackwards = 770,
Cantscrollbackwards = 771,
Rowsnotreleased = 772,
BadAccessorFlags = 773,
ErrorsEncountered = 774,
NotCapable = 775,
RequestOutOfSequence = 776,
VersionParseError = 777,
Badstartposition = 778,
MemoryHardware = 779,
DiskRepairDisabled = 780,
InsufficientResourceForSpecifiedSharedSectionSize = 781,
SystemPowerstateTransition = 782,
SystemPowerstateComplexTransition = 783,
McaException = 784,
AccessAuditByPolicy = 785,
AccessDisabledNoSaferUiByPolicy = 786,
AbandonHiberfile = 787,
LostWritebehindDataNetworkDisconnected = 788,
LostWritebehindDataNetworkServerError = 789,
LostWritebehindDataLocalDiskError = 790,
BadMcfgTable = 791,
DiskRepairRedirected = 792,
DiskRepairUnsuccessful = 793,
CorruptLogOverfull = 794,
CorruptLogCorrupted = 795,
CorruptLogUnavailable = 796,
CorruptLogDeletedFull = 797,
CorruptLogCleared = 798,
OrphanNameExhausted = 799,
OplockSwitchedToNewHandle = 800,
CannotGrantRequestedOplock = 801,
CannotBreakOplock = 802,
OplockHandleClosed = 803,
NoAceCondition = 804,
InvalidAceCondition = 805,
FileHandleRevoked = 806,
ImageAtDifferentBase = 807,
EncryptedIoNotPossible = 808,
FileMetadataOptimizationInProgress = 809,
QuotaActivity = 810,
HandleRevoked = 811,
CallbackInvokeInline = 812,
CpuSetInvalid = 813,
EaAccessDenied = 994,
OperationAborted = 995,
IoIncomplete = 996,
IoPending = 997,
Noaccess = 998,
Swaperror = 999,
StackOverflow = 1001,
InvalidMessage = 1002,
CanNotComplete = 1003,
InvalidFlags = 1004,
UnrecognizedVolume = 1005,
FileInvalid = 1006,
FullscreenMode = 1007,
NoToken = 1008,
Baddb = 1009,
Badkey = 1010,
Cantopen = 1011,
Cantread = 1012,
Cantwrite = 1013,
RegistryRecovered = 1014,
RegistryCorrupt = 1015,
RegistryIoFailed = 1016,
NotRegistryFile = 1017,
KeyDeleted = 1018,
NoLogSpace = 1019,
KeyHasChildren = 1020,
ChildMustBeVolatile = 1021,
NotifyEnumDir = 1022,
DependentServicesRunning = 1051,
InvalidServiceControl = 1052,
ServiceRequestTimeout = 1053,
ServiceNoThread = 1054,
ServiceDatabaseLocked = 1055,
ServiceAlreadyRunning = 1056,
InvalidServiceAccount = 1057,
ServiceDisabled = 1058,
CircularDependency = 1059,
ServiceDoesNotExist = 1060,
ServiceCannotAcceptCtrl = 1061,
ServiceNotActive = 1062,
FailedServiceControllerConnect = 1063,
ExceptionInService = 1064,
DatabaseDoesNotExist = 1065,
ServiceSpecificError = 1066,
ProcessAborted = 1067,
ServiceDependencyFail = 1068,
ServiceLogonFailed = 1069,
ServiceStartHang = 1070,
InvalidServiceLock = 1071,
ServiceMarkedForDelete = 1072,
ServiceExists = 1073,
AlreadyRunningLkg = 1074,
ServiceDependencyDeleted = 1075,
BootAlreadyAccepted = 1076,
ServiceNeverStarted = 1077,
DuplicateServiceName = 1078,
DifferentServiceAccount = 1079,
CannotDetectDriverFailure = 1080,
CannotDetectProcessAbort = 1081,
NoRecoveryProgram = 1082,
ServiceNotInExe = 1083,
NotSafebootService = 1084,
EndOfMedia = 1100,
FilemarkDetected = 1101,
BeginningOfMedia = 1102,
SetmarkDetected = 1103,
NoDataDetected = 1104,
PartitionFailure = 1105,
InvalidBlockLength = 1106,
DeviceNotPartitioned = 1107,
UnableToLockMedia = 1108,
UnableToUnloadMedia = 1109,
MediaChanged = 1110,
BusReset = 1111,
NoMediaInDrive = 1112,
NoUnicodeTranslation = 1113,
DllInitFailed = 1114,
ShutdownInProgress = 1115,
NoShutdownInProgress = 1116,
IoDevice = 1117,
SerialNoDevice = 1118,
IrqBusy = 1119,
MoreWrites = 1120,
CounterTimeout = 1121,
FloppyIdMarkNotFound = 1122,
FloppyWrongCylinder = 1123,
FloppyUnknownError = 1124,
FloppyBadRegisters = 1125,
DiskRecalibrateFailed = 1126,
DiskOperationFailed = 1127,
DiskResetFailed = 1128,
EomOverflow = 1129,
NotEnoughServerMemory = 1130,
PossibleDeadlock = 1131,
MappedAlignment = 1132,
SetPowerStateVetoed = 1140,
SetPowerStateFailed = 1141,
TooManyLinks = 1142,
OldWinVersion = 1150,
AppWrongOs = 1151,
SingleInstanceApp = 1152,
RmodeApp = 1153,
InvalidDll = 1154,
NoAssociation = 1155,
DdeFail = 1156,
DllNotFound = 1157,
NoMoreUserHandles = 1158,
MessageSyncOnly = 1159,
SourceElementEmpty = 1160,
DestinationElementFull = 1161,
IllegalElementAddress = 1162,
MagazineNotPresent = 1163,
DeviceReinitializationNeeded = 1164,
DeviceRequiresCleaning = 1165,
DeviceDoorOpen = 1166,
DeviceNotConnected = 1167,
NotFound = 1168,
NoMatch = 1169,
SetNotFound = 1170,
PointNotFound = 1171,
NoTrackingService = 1172,
NoVolumeId = 1173,
UnableToRemoveReplaced = 1175,
UnableToMoveReplacement = 1176,
UnableToMoveReplacement2 = 1177,
JournalDeleteInProgress = 1178,
JournalNotActive = 1179,
PotentialFileFound = 1180,
JournalEntryDeleted = 1181,
ShutdownIsScheduled = 1190,
ShutdownUsersLoggedOn = 1191,
BadDevice = 1200,
ConnectionUnavail = 1201,
DeviceAlreadyRemembered = 1202,
NoNetOrBadPath = 1203,
BadProvider = 1204,
CannotOpenProfile = 1205,
BadProfile = 1206,
NotContainer = 1207,
ExtendedError = 1208,
InvalidGroupname = 1209,
InvalidComputername = 1210,
InvalidEventname = 1211,
InvalidDomainname = 1212,
InvalidServicename = 1213,
InvalidNetname = 1214,
InvalidSharename = 1215,
InvalidPasswordname = <PASSWORD>,
InvalidMessagename = 1217,
InvalidMessagedest = 1218,
SessionCredentialConflict = 1219,
RemoteSessionLimitExceeded = 1220,
DupDomainname = 1221,
NoNetwork = 1222,
Cancelled = 1223,
UserMappedFile = 1224,
ConnectionRefused = 1225,
GracefulDisconnect = 1226,
AddressAlreadyAssociated = 1227,
AddressNotAssociated = 1228,
ConnectionInvalid = 1229,
ConnectionActive = 1230,
NetworkUnreachable = 1231,
HostUnreachable = 1232,
ProtocolUnreachable = 1233,
PortUnreachable = 1234,
RequestAborted = 1235,
ConnectionAborted = 1236,
Retry = 1237,
ConnectionCountLimit = 1238,
LoginTimeRestriction = 1239,
LoginWkstaRestriction = 1240,
IncorrectAddress = 1241,
AlreadyRegistered = 1242,
ServiceNotFound = 1243,
NotAuthenticated = 1244,
NotLoggedOn = 1245,
Continue = 1246,
AlreadyInitialized = 1247,
NoMoreDevices = 1248,
NoSuchSite = 1249,
DomainControllerExists = 1250,
OnlyIfConnected = 1251,
OverrideNochanges = 1252,
BadUserProfile = 1253,
NotSupportedOnSbs = 1254,
ServerShutdownInProgress = 1255,
HostDown = 1256,
NonAccountSid = 1257,
NonDomainSid = 1258,
ApphelpBlock = 1259,
AccessDisabledByPolicy = 1260,
RegNatConsumption = 1261,
CscshareOffline = 1262,
PkinitFailure = 1263,
SmartcardSubsystemFailure = 1264,
DowngradeDetected = 1265,
MachineLocked = 1271,
SmbGuestLogonBlocked = 1272,
CallbackSuppliedInvalidData = 1273,
SyncForegroundRefreshRequired = 1274,
DriverBlocked = 1275,
InvalidImportOfNonDll = 1276,
AccessDisabledWebblade = 1277,
AccessDisabledWebbladeTamper = 1278,
RecoveryFailure = 1279,
AlreadyFiber = 1280,
AlreadyThread = 1281,
StackBufferOverrun = 1282,
ParameterQuotaExceeded = 1283,
DebuggerInactive = 1284,
DelayLoadFailed = 1285,
VdmDisallowed = 1286,
UnidentifiedError = 1287,
InvalidCruntimeParameter = 1288,
BeyondVdl = 1289,
IncompatibleServiceSidType = 1290,
DriverProcessTerminated = 1291,
ImplementationLimit = 1292,
ProcessIsProtected = 1293,
ServiceNotifyClientLagging = 1294,
DiskQuotaExceeded = 1295,
ContentBlocked = 1296,
IncompatibleServicePrivilege = 1297,
AppHang = 1298,
InvalidLabel = 1299,
NotAllAssigned = 1300,
SomeNotMapped = 1301,
NoQuotasForAccount = 1302,
LocalUserSessionKey = 1303,
NullLmPassword = <PASSWORD>,
UnknownRevision = 1305,
RevisionMismatch = 1306,
InvalidOwner = 1307,
InvalidPrimaryGroup = 1308,
NoImpersonationToken = 1309,
CantDisableMandatory = 1310,
NoLogonServers = 1311,
NoSuchLogonSession = 1312,
NoSuchPrivilege = 1313,
PrivilegeNotHeld = 1314,
InvalidAccountName = 1315,
UserExists = 1316,
NoSuchUser = 1317,
GroupExists = 1318,
NoSuchGroup = 1319,
MemberInGroup = 1320,
MemberNotInGroup = 1321,
LastAdmin = 1322,
WrongPassword = <PASSWORD>,
IllFormedPassword = <PASSWORD>,
PasswordRestriction = 1325,
LogonFailure = 1326,
AccountRestriction = 1327,
InvalidLogonHours = 1328,
InvalidWorkstation = 1329,
PasswordExpired = 1330,
AccountDisabled = 1331,
NoneMapped = 1332,
TooManyLuidsRequested = 1333,
LuidsExhausted = 1334,
InvalidSubAuthority = 1335,
InvalidAcl = 1336,
InvalidSid = 1337,
InvalidSecurityDescr = 1338,
BadInheritanceAcl = 1340,
ServerDisabled = 1341,
ServerNotDisabled = 1342,
InvalidIdAuthority = 1343,
AllottedSpaceExceeded = 1344,
InvalidGroupAttributes = 1345,
BadImpersonationLevel = 1346,
CantOpenAnonymous = 1347,
BadValidationClass = 1348,
BadTokenType = 1349,
NoSecurityOnObject = 1350,
CantAccessDomainInfo = 1351,
InvalidServerState = 1352,
InvalidDomainState = 1353,
InvalidDomainRole = 1354,
NoSuchDomain = 1355,
DomainExists = 1356,
DomainLimitExceeded = 1357,
InternalDbCorruption = 1358,
InternalError = 1359,
GenericNotMapped = 1360,
BadDescriptorFormat = 1361,
NotLogonProcess = 1362,
LogonSessionExists = 1363,
NoSuchPackage = 1364,
BadLogonSessionState = 1365,
LogonSessionCollision = 1366,
InvalidLogonType = 1367,
CannotImpersonate = 1368,
RxactInvalidState = 1369,
RxactCommitFailure = 1370,
SpecialAccount = 1371,
SpecialGroup = 1372,
SpecialUser = 1373,
MembersPrimaryGroup = 1374,
TokenAlreadyInUse = 1375,
NoSuchAlias = 1376,
MemberNotInAlias = 1377,
MemberInAlias = 1378,
AliasExists = 1379,
LogonNotGranted = 1380,
TooManySecrets = 1381,
SecretTooLong = 1382,
InternalDbError = 1383,
TooManyContextIds = 1384,
LogonTypeNotGranted = 1385,
NtCrossEncryptionRequired = 1386,
NoSuchMember = 1387,
InvalidMember = 1388,
TooManySids = 1389,
LmCrossEncryptionRequired = 1390,
NoInheritance = 1391,
FileCorrupt = 1392,
DiskCorrupt = 1393,
NoUserSessionKey = 1394,
LicenseQuotaExceeded = 1395,
WrongTargetName = 1396,
MutualAuthFailed = 1397,
TimeSkew = 1398,
CurrentDomainNotAllowed = 1399,
InvalidWindowHandle = 1400,
InvalidMenuHandle = 1401,
InvalidCursorHandle = 1402,
InvalidAccelHandle = 1403,
InvalidHookHandle = 1404,
InvalidDwpHandle = 1405,
TlwWithWschild = 1406,
CannotFindWndClass = 1407,
WindowOfOtherThread = 1408,
HotkeyAlreadyRegistered = 1409,
ClassAlreadyExists = 1410,
ClassDoesNotExist = 1411,
ClassHasWindows = 1412,
InvalidIndex = 1413,
InvalidIconHandle = 1414,
PrivateDialogIndex = 1415,
ListboxIdNotFound = 1416,
NoWildcardCharacters = 1417,
ClipboardNotOpen = 1418,
HotkeyNotRegistered = 1419,
WindowNotDialog = 1420,
ControlIdNotFound = 1421,
InvalidComboboxMessage = 1422,
WindowNotCombobox = 1423,
InvalidEditHeight = 1424,
DcNotFound = 1425,
InvalidHookFilter = 1426,
InvalidFilterProc = 1427,
HookNeedsHmod = 1428,
GlobalOnlyHook = 1429,
JournalHookSet = 1430,
HookNotInstalled = 1431,
InvalidLbMessage = 1432,
SetcountOnBadLb = 1433,
LbWithoutTabstops = 1434,
DestroyObjectOfOtherThread = 1435,
ChildWindowMenu = 1436,
NoSystemMenu = 1437,
InvalidMsgboxStyle = 1438,
InvalidSpiValue = 1439,
ScreenAlreadyLocked = 1440,
HwndsHaveDiffParent = 1441,
NotChildWindow = 1442,
InvalidGwCommand = 1443,
InvalidThreadId = 1444,
NonMdichildWindow = 1445,
PopupAlreadyActive = 1446,
NoScrollbars = 1447,
InvalidScrollbarRange = 1448,
InvalidShowwinCommand = 1449,
NoSystemResources = 1450,
NonpagedSystemResources = 1451,
PagedSystemResources = 1452,
WorkingSetQuota = 1453,
PagefileQuota = 1454,
CommitmentLimit = 1455,
MenuItemNotFound = 1456,
InvalidKeyboardHandle = 1457,
HookTypeNotAllowed = 1458,
RequiresInteractiveWindowstation = 1459,
Timeout = 1460,
InvalidMonitorHandle = 1461,
IncorrectSize = 1462,
SymlinkClassDisabled = 1463,
SymlinkNotSupported = 1464,
XmlParseError = 1465,
XmldsigError = 1466,
RestartApplication = 1467,
WrongCompartment = 1468,
AuthipFailure = 1469,
NoNvramResources = 1470,
NotGuiProcess = 1471,
EventlogFileCorrupt = 1500,
EventlogCantStart = 1501,
LogFileFull = 1502,
EventlogFileChanged = 1503,
ContainerAssigned = 1504,
JobNoContainer = 1505,
InvalidTaskName = 1550,
InvalidTaskIndex = 1551,
ThreadAlreadyInTask = 1552,
InstallServiceFailure = 1601,
InstallUserexit = 1602,
InstallFailure = 1603,
InstallSuspend = 1604,
UnknownProduct = 1605,
UnknownFeature = 1606,
UnknownComponent = 1607,
UnknownProperty = 1608,
InvalidHandleState = 1609,
BadConfiguration = 1610,
IndexAbsent = 1611,
InstallSourceAbsent = 1612,
InstallPackageVersion = 1613,
ProductUninstalled = 1614,
BadQuerySyntax = 1615,
InvalidField = 1616,
DeviceRemoved = 1617,
InstallAlreadyRunning = 1618,
InstallPackageOpenFailed = 1619,
InstallPackageInvalid = 1620,
InstallUiFailure = 1621,
InstallLogFailure = 1622,
InstallLanguageUnsupported = 1623,
InstallTransformFailure = 1624,
InstallPackageRejected = 1625,
FunctionNotCalled = 1626,
FunctionFailed = 1627,
InvalidTable = 1628,
DatatypeMismatch = 1629,
UnsupportedType = 1630,
CreateFailed = 1631,
InstallTempUnwritable = 1632,
InstallPlatformUnsupported = 1633,
InstallNotused = 1634,
PatchPackageOpenFailed = 1635,
PatchPackageInvalid = 1636,
PatchPackageUnsupported = 1637,
ProductVersion = 1638,
InvalidCommandLine = 1639,
InstallRemoteDisallowed = 1640,
SuccessRebootInitiated = 1641,
PatchTargetNotFound = 1642,
PatchPackageRejected = 1643,
InstallTransformRejected = 1644,
InstallRemoteProhibited = 1645,
PatchRemovalUnsupported = 1646,
UnknownPatch = 1647,
PatchNoSequence = 1648,
PatchRemovalDisallowed = 1649,
InvalidPatchXml = 1650,
PatchManagedAdvertisedProduct = 1651,
InstallServiceSafeboot = 1652,
FailFastException = 1653,
InstallRejected = 1654,
DynamicCodeBlocked = 1655,
NotSameObject = 1656,
InvalidUserBuffer = 1784,
UnrecognizedMedia = 1785,
NoTrustLsaSecret = 1786,
NoTrustSamAccount = 1787,
TrustedDomainFailure = 1788,
TrustedRelationshipFailure = 1789,
TrustFailure = 1790,
NetlogonNotStarted = 1792,
AccountExpired = 1793,
RedirectorHasOpenHandles = 1794,
PrinterDriverAlreadyInstalled = 1795,
UnknownPort = 1796,
UnknownPrinterDriver = 1797,
UnknownPrintprocessor = 1798,
InvalidSeparatorFile = 1799,
InvalidPriority = 1800,
InvalidPrinterName = 1801,
PrinterAlreadyExists = 1802,
InvalidPrinterCommand = 1803,
InvalidDatatype = 1804,
InvalidEnvironment = 1805,
NologonInterdomainTrustAccount = 1807,
NologonWorkstationTrustAccount = 1808,
NologonServerTrustAccount = 1809,
DomainTrustInconsistent = 1810,
ServerHasOpenHandles = 1811,
ResourceDataNotFound = 1812,
ResourceTypeNotFound = 1813,
ResourceNameNotFound = 1814,
ResourceLangNotFound = 1815,
NotEnoughQuota = 1816,
InvalidTime = 1901,
InvalidFormName = 1902,
InvalidFormSize = 1903,
AlreadyWaiting = 1904,
PrinterDeleted = 1905,
InvalidPrinterState = 1906,
PasswordMustChange = 1907,
DomainControllerNotFound = 1908,
AccountLockedOut = 1909,
NoSitename = 1919,
CantAccessFile = 1920,
CantResolveFilename = 1921,
KmDriverBlocked = 1930,
ContextExpired = 1931,
PerUserTrustQuotaExceeded = 1932,
AllUserTrustQuotaExceeded = 1933,
UserDeleteTrustQuotaExceeded = 1934,
AuthenticationFirewallFailed = 1935,
RemotePrintConnectionsBlocked = 1936,
NtlmBlocked = 1937,
PasswordChangeRequired = <PASSWORD>,
InvalidPixelFormat = 2000,
BadDriver = 2001,
InvalidWindowStyle = 2002,
MetafileNotSupported = 2003,
TransformNotSupported = 2004,
ClippingNotSupported = 2005,
InvalidCmm = 2010,
InvalidProfile = 2011,
TagNotFound = 2012,
TagNotPresent = 2013,
DuplicateTag = 2014,
ProfileNotAssociatedWithDevice = 2015,
ProfileNotFound = 2016,
InvalidColorspace = 2017,
IcmNotEnabled = 2018,
DeletingIcmXform = 2019,
InvalidTransform = 2020,
ColorspaceMismatch = 2021,
InvalidColorindex = 2022,
ProfileDoesNotMatchDevice = 2023,
ConnectedOtherPassword = <PASSWORD>,
ConnectedOtherPasswordDefault = <PASSWORD>,
BadUsername = 2202,
NotConnected = 2250,
OpenFiles = 2401,
ActiveConnections = 2402,
DeviceInUse = 2404,
UnknownPrintMonitor = 3000,
PrinterDriverInUse = 3001,
SpoolFileNotFound = 3002,
SplNoStartdoc = 3003,
SplNoAddjob = 3004,
PrintProcessorAlreadyInstalled = 3005,
PrintMonitorAlreadyInstalled = 3006,
InvalidPrintMonitor = 3007,
PrintMonitorInUse = 3008,
PrinterHasJobsQueued = 3009,
SuccessRebootRequired = 3010,
SuccessRestartRequired = 3011,
PrinterNotFound = 3012,
PrinterDriverWarned = 3013,
PrinterDriverBlocked = 3014,
PrinterDriverPackageInUse = 3015,
CoreDriverPackageNotFound = 3016,
FailRebootRequired = 3017,
FailRebootInitiated = 3018,
PrinterDriverDownloadNeeded = 3019,
PrintJobRestartRequired = 3020,
InvalidPrinterDriverManifest = 3021,
PrinterNotShareable = 3022,
RequestPaused = 3050,
IoReissueAsCached = 3950,
WinsInternal = 4000,
CanNotDelLocalWins = 4001,
StaticInit = 4002,
IncBackup = 4003,
FullBackup = 4004,
RecNonExistent = 4005,
RplNotAllowed = 4006,
DhcpAddressConflict = 4100,
WmiGuidNotFound = 4200,
WmiInstanceNotFound = 4201,
WmiItemidNotFound = 4202,
WmiTryAgain = 4203,
WmiDpNotFound = 4204,
WmiUnresolvedInstanceRef = 4205,
WmiAlreadyEnabled = 4206,
WmiGuidDisconnected = 4207,
WmiServerUnavailable = 4208,
WmiDpFailed = 4209,
WmiInvalidMof = 4210,
WmiInvalidReginfo = 4211,
WmiAlreadyDisabled = 4212,
WmiReadOnly = 4213,
WmiSetFailure = 4214,
NotAppcontainer = 4250,
AppcontainerRequired = 4251,
NotSupportedInAppcontainer = 4252,
InvalidPackageSidLength = 4253,
InvalidMedia = 4300,
InvalidLibrary = 4301,
InvalidMediaPool = 4302,
DriveMediaMismatch = 4303,
MediaOffline = 4304,
LibraryOffline = 4305,
Empty = 4306,
NotEmpty = 4307,
MediaUnavailable = 4308,
ResourceDisabled = 4309,
InvalidCleaner = 4310,
UnableToClean = 4311,
ObjectNotFound = 4312,
DatabaseFailure = 4313,
DatabaseFull = 4314,
MediaIncompatible = 4315,
ResourceNotPresent = 4316,
InvalidOperation = 4317,
MediaNotAvailable = 4318,
DeviceNotAvailable = 4319,
RequestRefused = 4320,
InvalidDriveObject = 4321,
LibraryFull = 4322,
MediumNotAccessible = 4323,
UnableToLoadMedium = 4324,
UnableToInventoryDrive = 4325,
UnableToInventorySlot = 4326,
UnableToInventoryTransport = 4327,
TransportFull = 4328,
ControllingIeport = 4329,
UnableToEjectMountedMedia = 4330,
CleanerSlotSet = 4331,
CleanerSlotNotSet = 4332,
CleanerCartridgeSpent = 4333,
UnexpectedOmid = 4334,
CantDeleteLastItem = 4335,
MessageExceedsMaxSize = 4336,
VolumeContainsSysFiles = 4337,
IndigenousType = 4338,
NoSupportingDrives = 4339,
CleanerCartridgeInstalled = 4340,
IeportFull = 4341,
FileOffline = 4350,
RemoteStorageNotActive = 4351,
RemoteStorageMediaError = 4352,
NotAReparsePoint = 4390,
ReparseAttributeConflict = 4391,
InvalidReparseData = 4392,
ReparseTagInvalid = 4393,
ReparseTagMismatch = 4394,
ReparsePointEncountered = 4395,
AppDataNotFound = 4400,
AppDataExpired = 4401,
AppDataCorrupt = 4402,
AppDataLimitExceeded = 4403,
AppDataRebootRequired = 4404,
SecurebootRollbackDetected = 4420,
SecurebootPolicyViolation = 4421,
SecurebootInvalidPolicy = 4422,
SecurebootPolicyPublisherNotFound = 4423,
SecurebootPolicyNotSigned = 4424,
SecurebootNotEnabled = 4425,
SecurebootFileReplaced = 4426,
OffloadReadFltNotSupported = 4440,
OffloadWriteFltNotSupported = 4441,
OffloadReadFileNotSupported = 4442,
OffloadWriteFileNotSupported = 4443,
VolumeNotSisEnabled = 4500,
SystemIntegrityRollbackDetected = 4550,
SystemIntegrityPolicyViolation = 4551,
SystemIntegrityInvalidPolicy = 4552,
SystemIntegrityPolicyNotSigned = 4553,
VsmNotInitialized = 4560,
VsmDmaProtectionNotInUse = 4561,
DependentResourceExists = 5001,
DependencyNotFound = 5002,
DependencyAlreadyExists = 5003,
ResourceNotOnline = 5004,
HostNodeNotAvailable = 5005,
ResourceNotAvailable = 5006,
ResourceNotFound = 5007,
ShutdownCluster = 5008,
CantEvictActiveNode = 5009,
ObjectAlreadyExists = 5010,
ObjectInList = 5011,
GroupNotAvailable = 5012,
GroupNotFound = 5013,
GroupNotOnline = 5014,
HostNodeNotResourceOwner = 5015,
HostNodeNotGroupOwner = 5016,
ResmonCreateFailed = 5017,
ResmonOnlineFailed = 5018,
ResourceOnline = 5019,
QuorumResource = 5020,
NotQuorumCapable = 5021,
ClusterShuttingDown = 5022,
InvalidState = 5023,
ResourcePropertiesStored = 5024,
NotQuorumClass = 5025,
CoreResource = 5026,
QuorumResourceOnlineFailed = 5027,
QuorumlogOpenFailed = 5028,
ClusterlogCorrupt = 5029,
ClusterlogRecordExceedsMaxsize = 5030,
ClusterlogExceedsMaxsize = 5031,
ClusterlogChkpointNotFound = 5032,
ClusterlogNotEnoughSpace = 5033,
QuorumOwnerAlive = 5034,
NetworkNotAvailable = 5035,
NodeNotAvailable = 5036,
AllNodesNotAvailable = 5037,
ResourceFailed = 5038,
ClusterInvalidNode = 5039,
ClusterNodeExists = 5040,
ClusterJoinInProgress = 5041,
ClusterNodeNotFound = 5042,
ClusterLocalNodeNotFound = 5043,
ClusterNetworkExists = 5044,
ClusterNetworkNotFound = 5045,
ClusterNetinterfaceExists = 5046,
ClusterNetinterfaceNotFound = 5047,
ClusterInvalidRequest = 5048,
ClusterInvalidNetworkProvider = 5049,
ClusterNodeDown = 5050,
ClusterNodeUnreachable = 5051,
ClusterNodeNotMember = 5052,
ClusterJoinNotInProgress = 5053,
ClusterInvalidNetwork = 5054,
ClusterNodeUp = 5056,
ClusterIpaddrInUse = 5057,
ClusterNodeNotPaused = 5058,
ClusterNoSecurityContext = 5059,
ClusterNetworkNotInternal = 5060,
ClusterNodeAlreadyUp = 5061,
ClusterNodeAlreadyDown = 5062,
ClusterNetworkAlreadyOnline = 5063,
ClusterNetworkAlreadyOffline = 5064,
ClusterNodeAlreadyMember = 5065,
ClusterLastInternalNetwork = 5066,
ClusterNetworkHasDependents = 5067,
InvalidOperationOnQuorum = 5068,
DependencyNotAllowed = 5069,
ClusterNodePaused = 5070,
NodeCantHostResource = 5071,
ClusterNodeNotReady = 5072,
ClusterNodeShuttingDown = 5073,
ClusterJoinAborted = 5074,
ClusterIncompatibleVersions = 5075,
ClusterMaxnumOfResourcesExceeded = 5076,
ClusterSystemConfigChanged = 5077,
ClusterResourceTypeNotFound = 5078,
ClusterRestypeNotSupported = 5079,
ClusterResnameNotFound = 5080,
ClusterNoRpcPackagesRegistered = 5081,
ClusterOwnerNotInPreflist = 5082,
ClusterDatabaseSeqmismatch = 5083,
ResmonInvalidState = 5084,
ClusterGumNotLocker = 5085,
QuorumDiskNotFound = 5086,
DatabaseBackupCorrupt = 5087,
ClusterNodeAlreadyHasDfsRoot = 5088,
ResourcePropertyUnchangeable = 5089,
NoAdminAccessPoint = 5090,
ClusterMembershipInvalidState = 5890,
ClusterQuorumlogNotFound = 5891,
ClusterMembershipHalt = 5892,
ClusterInstanceIdMismatch = 5893,
ClusterNetworkNotFoundForIp = 5894,
ClusterPropertyDataTypeMismatch = 5895,
ClusterEvictWithoutCleanup = 5896,
ClusterParameterMismatch = 5897,
NodeCannotBeClustered = 5898,
ClusterWrongOsVersion = 5899,
ClusterCantCreateDupClusterName = 5900,
CluscfgAlreadyCommitted = 5901,
CluscfgRollbackFailed = 5902,
CluscfgSystemDiskDriveLetterConflict = 5903,
ClusterOldVersion = 5904,
ClusterMismatchedComputerAcctName = 5905,
ClusterNoNetAdapters = 5906,
ClusterPoisoned = 5907,
ClusterGroupMoving = 5908,
ClusterResourceTypeBusy = 5909,
ResourceCallTimedOut = 5910,
InvalidClusterIpv6Address = 5911,
ClusterInternalInvalidFunction = 5912,
ClusterParameterOutOfBounds = 5913,
ClusterPartialSend = 5914,
ClusterRegistryInvalidFunction = 5915,
ClusterInvalidStringTermination = 5916,
ClusterInvalidStringFormat = 5917,
ClusterDatabaseTransactionInProgress = 5918,
ClusterDatabaseTransactionNotInProgress = 5919,
ClusterNullData = 5920,
ClusterPartialRead = 5921,
ClusterPartialWrite = 5922,
ClusterCantDeserializeData = 5923,
DependentResourcePropertyConflict = 5924,
ClusterNoQuorum = 5925,
ClusterInvalidIpv6Network = 5926,
ClusterInvalidIpv6TunnelNetwork = 5927,
QuorumNotAllowedInThisGroup = 5928,
DependencyTreeTooComplex = 5929,
ExceptionInResourceCall = 5930,
ClusterRhsFailedInitialization = 5931,
ClusterNotInstalled = 5932,
ClusterResourcesMustBeOnlineOnTheSameNode = 5933,
ClusterMaxNodesInCluster = 5934,
ClusterTooManyNodes = 5935,
ClusterObjectAlreadyUsed = 5936,
NoncoreGroupsFound = 5937,
FileShareResourceConflict = 5938,
ClusterEvictInvalidRequest = 5939,
ClusterSingletonResource = 5940,
ClusterGroupSingletonResource = 5941,
ClusterResourceProviderFailed = 5942,
ClusterResourceConfigurationError = 5943,
ClusterGroupBusy = 5944,
ClusterNotSharedVolume = 5945,
ClusterInvalidSecurityDescriptor = 5946,
ClusterSharedVolumesInUse = 5947,
ClusterUseSharedVolumesApi = 5948,
ClusterBackupInProgress = 5949,
NonCsvPath = 5950,
CsvVolumeNotLocal = 5951,
ClusterWatchdogTerminating = 5952,
ClusterResourceVetoedMoveIncompatibleNodes = 5953,
ClusterInvalidNodeWeight = 5954,
ClusterResourceVetoedCall = 5955,
ResmonSystemResourcesLacking = 5956,
ClusterResourceVetoedMoveNotEnoughResourcesOnDestination = 5957,
ClusterResourceVetoedMoveNotEnoughResourcesOnSource = 5958,
ClusterGroupQueued = 5959,
ClusterResourceLockedStatus = 5960,
ClusterSharedVolumeFailoverNotAllowed = 5961,
ClusterNodeDrainInProgress = 5962,
ClusterDiskNotConnected = 5963,
DiskNotCsvCapable = 5964,
ResourceNotInAvailableStorage = 5965,
ClusterSharedVolumeRedirected = 5966,
ClusterSharedVolumeNotRedirected = 5967,
ClusterCannotReturnProperties = 5968,
ClusterResourceContainsUnsupportedDiffAreaForSharedVolumes = 5969,
ClusterResourceIsInMaintenanceMode = 5970,
ClusterAffinityConflict = 5971,
ClusterResourceIsReplicaVirtualMachine = 5972,
ClusterUpgradeIncompatibleVersions = 5973,
ClusterUpgradeFixQuorumNotSupported = 5974,
ClusterUpgradeRestartRequired = 5975,
ClusterUpgradeInProgress = 5976,
ClusterUpgradeIncomplete = 5977,
ClusterNodeInGracePeriod = 5978,
ClusterCsvIoPauseTimeout = 5979,
NodeNotActiveClusterMember = 5980,
ClusterResourceNotMonitored = 5981,
ClusterResourceDoesNotSupportUnmonitored = 5982,
ClusterResourceIsReplicated = 5983,
ClusterNodeIsolated = 5984,
ClusterNodeQuarantined = 5985,
ClusterDatabaseUpdateConditionFailed = 5986,
ClusterSpaceDegraded = 5987,
ClusterTokenDelegationNotSupported = 5988,
ClusterCsvInvalidHandle = 5989,
ClusterCsvSupportedOnlyOnCoordinator = 5990,
EncryptionFailed = 6000,
DecryptionFailed = 6001,
FileEncrypted = 6002,
NoRecoveryPolicy = 6003,
NoEfs = 6004,
WrongEfs = 6005,
NoUserKeys = 6006,
FileNotEncrypted = 6007,
NotExportFormat = 6008,
FileReadOnly = 6009,
DirEfsDisallowed = 6010,
EfsServerNotTrusted = 6011,
BadRecoveryPolicy = 6012,
EfsAlgBlobTooBig = 6013,
VolumeNotSupportEfs = 6014,
EfsDisabled = 6015,
EfsVersionNotSupport = 6016,
CsEncryptionInvalidServerResponse = 6017,
CsEncryptionUnsupportedServer = 6018,
CsEncryptionExistingEncryptedFile = 6019,
CsEncryptionNewEncryptedFile = 6020,
CsEncryptionFileNotCse = 6021,
EncryptionPolicyDeniesOperation = 6022,
NoBrowserServersFound = 6118,
LogSectorInvalid = 6600,
LogSectorParityInvalid = 6601,
LogSectorRemapped = 6602,
LogBlockIncomplete = 6603,
LogInvalidRange = 6604,
LogBlocksExhausted = 6605,
LogReadContextInvalid = 6606,
LogRestartInvalid = 6607,
LogBlockVersion = 6608,
LogBlockInvalid = 6609,
LogReadModeInvalid = 6610,
LogNoRestart = 6611,
LogMetadataCorrupt = 6612,
LogMetadataInvalid = 6613,
LogMetadataInconsistent = 6614,
LogReservationInvalid = 6615,
LogCantDelete = 6616,
LogContainerLimitExceeded = 6617,
LogStartOfLog = 6618,
LogPolicyAlreadyInstalled = 6619,
LogPolicyNotInstalled = 6620,
LogPolicyInvalid = 6621,
LogPolicyConflict = 6622,
LogPinnedArchiveTail = 6623,
LogRecordNonexistent = 6624,
LogRecordsReservedInvalid = 6625,
LogSpaceReservedInvalid = 6626,
LogTailInvalid = 6627,
LogFull = 6628,
CouldNotResizeLog = 6629,
LogMultiplexed = 6630,
LogDedicated = 6631,
LogArchiveNotInProgress = 6632,
LogArchiveInProgress = 6633,
LogEphemeral = 6634,
LogNotEnoughContainers = 6635,
LogClientAlreadyRegistered = 6636,
LogClientNotRegistered = 6637,
LogFullHandlerInProgress = 6638,
LogContainerReadFailed = 6639,
LogContainerWriteFailed = 6640,
LogContainerOpenFailed = 6641,
LogContainerStateInvalid = 6642,
LogStateInvalid = 6643,
LogPinned = 6644,
LogMetadataFlushFailed = 6645,
LogInconsistentSecurity = 6646,
LogAppendedFlushFailed = 6647,
LogPinnedReservation = 6648,
InvalidTransaction = 6700,
TransactionNotActive = 6701,
TransactionRequestNotValid = 6702,
TransactionNotRequested = 6703,
TransactionAlreadyAborted = 6704,
TransactionAlreadyCommitted = 6705,
TmInitializationFailed = 6706,
ResourcemanagerReadOnly = 6707,
TransactionNotJoined = 6708,
TransactionSuperiorExists = 6709,
CrmProtocolAlreadyExists = 6710,
TransactionPropagationFailed = 6711,
CrmProtocolNotFound = 6712,
TransactionInvalidMarshallBuffer = 6713,
CurrentTransactionNotValid = 6714,
TransactionNotFound = 6715,
ResourcemanagerNotFound = 6716,
EnlistmentNotFound = 6717,
TransactionmanagerNotFound = 6718,
TransactionmanagerNotOnline = 6719,
TransactionmanagerRecoveryNameCollision = 6720,
TransactionNotRoot = 6721,
TransactionObjectExpired = 6722,
TransactionResponseNotEnlisted = 6723,
TransactionRecordTooLong = 6724,
ImplicitTransactionNotSupported = 6725,
TransactionIntegrityViolated = 6726,
TransactionmanagerIdentityMismatch = 6727,
RmCannotBeFrozenForSnapshot = 6728,
TransactionMustWritethrough = 6729,
TransactionNoSuperior = 6730,
HeuristicDamagePossible = 6731,
TransactionalConflict = 6800,
RmNotActive = 6801,
RmMetadataCorrupt = 6802,
DirectoryNotRm = 6803,
TransactionsUnsupportedRemote = 6805,
LogResizeInvalidSize = 6806,
ObjectNoLongerExists = 6807,
StreamMiniversionNotFound = 6808,
StreamMiniversionNotValid = 6809,
MiniversionInaccessibleFromSpecifiedTransaction = 6810,
CantOpenMiniversionWithModifyIntent = 6811,
CantCreateMoreStreamMiniversions = 6812,
RemoteFileVersionMismatch = 6814,
HandleNoLongerValid = 6815,
NoTxfMetadata = 6816,
LogCorruptionDetected = 6817,
CantRecoverWithHandleOpen = 6818,
RmDisconnected = 6819,
EnlistmentNotSuperior = 6820,
RecoveryNotNeeded = 6821,
RmAlreadyStarted = 6822,
FileIdentityNotPersistent = 6823,
CantBreakTransactionalDependency = 6824,
CantCrossRmBoundary = 6825,
TxfDirNotEmpty = 6826,
IndoubtTransactionsExist = 6827,
TmVolatile = 6828,
RollbackTimerExpired = 6829,
TxfAttributeCorrupt = 6830,
EfsNotAllowedInTransaction = 6831,
TransactionalOpenNotAllowed = 6832,
LogGrowthFailed = 6833,
TransactedMappingUnsupportedRemote = 6834,
TxfMetadataAlreadyPresent = 6835,
TransactionScopeCallbacksNotSet = 6836,
TransactionRequiredPromotion = 6837,
CannotExecuteFileInTransaction = 6838,
TransactionsNotFrozen = 6839,
TransactionFreezeInProgress = 6840,
NotSnapshotVolume = 6841,
NoSavepointWithOpenFiles = 6842,
DataLostRepair = 6843,
SparseNotAllowedInTransaction = 6844,
TmIdentityMismatch = 6845,
FloatedSection = 6846,
CannotAcceptTransactedWork = 6847,
CannotAbortTransactions = 6848,
BadClusters = 6849,
CompressionNotAllowedInTransaction = 6850,
VolumeDirty = 6851,
NoLinkTrackingInTransaction = 6852,
OperationNotSupportedInTransaction = 6853,
ExpiredHandle = 6854,
TransactionNotEnlisted = 6855,
CtxWinstationNameInvalid = 7001,
CtxInvalidPd = 7002,
CtxPdNotFound = 7003,
CtxWdNotFound = 7004,
CtxCannotMakeEventlogEntry = 7005,
CtxServiceNameCollision = 7006,
CtxClosePending = 7007,
CtxNoOutbuf = 7008,
CtxModemInfNotFound = 7009,
CtxInvalidModemname = 7010,
CtxModemResponseError = 7011,
CtxModemResponseTimeout = 7012,
CtxModemResponseNoCarrier = 7013,
CtxModemResponseNoDialtone = 7014,
CtxModemResponseBusy = 7015,
CtxModemResponseVoice = 7016,
CtxTdError = 7017,
CtxWinstationNotFound = 7022,
CtxWinstationAlreadyExists = 7023,
CtxWinstationBusy = 7024,
CtxBadVideoMode = 7025,
CtxGraphicsInvalid = 7035,
CtxLogonDisabled = 7037,
CtxNotConsole = 7038,
CtxClientQueryTimeout = 7040,
CtxConsoleDisconnect = 7041,
CtxConsoleConnect = 7042,
CtxShadowDenied = 7044,
CtxWinstationAccessDenied = 7045,
CtxInvalidWd = 7049,
CtxShadowInvalid = 7050,
CtxShadowDisabled = 7051,
CtxClientLicenseInUse = 7052,
CtxClientLicenseNotSet = 7053,
CtxLicenseNotAvailable = 7054,
CtxLicenseClientInvalid = 7055,
CtxLicenseExpired = 7056,
CtxShadowNotRunning = 7057,
CtxShadowEndedByModeChange = 7058,
ActivationCountExceeded = 7059,
CtxWinstationsDisabled = 7060,
CtxEncryptionLevelRequired = 7061,
CtxSessionInUse = 7062,
CtxNoForceLogoff = 7063,
CtxAccountRestriction = 7064,
RdpProtocolError = 7065,
CtxCdmConnect = 7066,
CtxCdmDisconnect = 7067,
CtxSecurityLayerError = 7068,
TsIncompatibleSessions = 7069,
TsVideoSubsystemError = 7070,
DsNotInstalled = 8200,
DsMembershipEvaluatedLocally = 8201,
DsNoAttributeOrValue = 8202,
DsInvalidAttributeSyntax = 8203,
DsAttributeTypeUndefined = 8204,
DsAttributeOrValueExists = 8205,
DsBusy = 8206,
DsUnavailable = 8207,
DsNoRidsAllocated = 8208,
DsNoMoreRids = 8209,
DsIncorrectRoleOwner = 8210,
DsRidmgrInitError = 8211,
DsObjClassViolation = 8212,
DsCantOnNonLeaf = 8213,
DsCantOnRdn = 8214,
DsCantModObjClass = 8215,
DsCrossDomMoveError = 8216,
DsGcNotAvailable = 8217,
SharedPolicy = 8218,
PolicyObjectNotFound = 8219,
PolicyOnlyInDs = 8220,
PromotionActive = 8221,
NoPromotionActive = 8222,
DsOperationsError = 8224,
DsProtocolError = 8225,
DsTimelimitExceeded = 8226,
DsSizelimitExceeded = 8227,
DsAdminLimitExceeded = 8228,
DsCompareFalse = 8229,
DsCompareTrue = 8230,
DsAuthMethodNotSupported = 8231,
DsStrongAuthRequired = 8232,
DsInappropriateAuth = 8233,
DsAuthUnknown = 8234,
DsReferral = 8235,
DsUnavailableCritExtension = 8236,
DsConfidentialityRequired = 8237,
DsInappropriateMatching = 8238,
DsConstraintViolation = 8239,
DsNoSuchObject = 8240,
DsAliasProblem = 8241,
DsInvalidDnSyntax = 8242,
DsIsLeaf = 8243,
DsAliasDerefProblem = 8244,
DsUnwillingToPerform = 8245,
DsLoopDetect = 8246,
DsNamingViolation = 8247,
DsObjectResultsTooLarge = 8248,
DsAffectsMultipleDsas = 8249,
DsServerDown = 8250,
DsLocalError = 8251,
DsEncodingError = 8252,
DsDecodingError = 8253,
DsFilterUnknown = 8254,
DsParamError = 8255,
DsNotSupported = 8256,
DsNoResultsReturned = 8257,
DsControlNotFound = 8258,
DsClientLoop = 8259,
DsReferralLimitExceeded = 8260,
DsSortControlMissing = 8261,
DsOffsetRangeError = 8262,
DsRidmgrDisabled = 8263,
DsRootMustBeNc = 8301,
DsAddReplicaInhibited = 8302,
DsAttNotDefInSchema = 8303,
DsMaxObjSizeExceeded = 8304,
DsObjStringNameExists = 8305,
DsNoRdnDefinedInSchema = 8306,
DsRdnDoesntMatchSchema = 8307,
DsNoRequestedAttsFound = 8308,
DsUserBufferToSmall = 8309,
DsAttIsNotOnObj = 8310,
DsIllegalModOperation = 8311,
DsObjTooLarge = 8312,
DsBadInstanceType = 8313,
DsMasterdsaRequired = 8314,
DsObjectClassRequired = 8315,
DsMissingRequiredAtt = 8316,
DsAttNotDefForClass = 8317,
DsAttAlreadyExists = 8318,
DsCantAddAttValues = 8320,
DsSingleValueConstraint = 8321,
DsRangeConstraint = 8322,
DsAttValAlreadyExists = 8323,
DsCantRemMissingAtt = 8324,
DsCantRemMissingAttVal = 8325,
DsRootCantBeSubref = 8326,
DsNoChaining = 8327,
DsNoChainedEval = 8328,
DsNoParentObject = 8329,
DsParentIsAnAlias = 8330,
DsCantMixMasterAndReps = 8331,
DsChildrenExist = 8332,
DsObjNotFound = 8333,
DsAliasedObjMissing = 8334,
DsBadNameSyntax = 8335,
DsAliasPointsToAlias = 8336,
DsCantDerefAlias = 8337,
DsOutOfScope = 8338,
DsObjectBeingRemoved = 8339,
DsCantDeleteDsaObj = 8340,
DsGenericError = 8341,
DsDsaMustBeIntMaster = 8342,
DsClassNotDsa = 8343,
DsInsuffAccessRights = 8344,
DsIllegalSuperior = 8345,
DsAttributeOwnedBySam = 8346,
DsNameTooManyParts = 8347,
DsNameTooLong = 8348,
DsNameValueTooLong = 8349,
DsNameUnparseable = 8350,
DsNameTypeUnknown = 8351,
DsNotAnObject = 8352,
DsSecDescTooShort = 8353,
DsSecDescInvalid = 8354,
DsNoDeletedName = 8355,
DsSubrefMustHaveParent = 8356,
DsNcnameMustBeNc = 8357,
DsCantAddSystemOnly = 8358,
DsClassMustBeConcrete = 8359,
DsInvalidDmd = 8360,
DsObjGuidExists = 8361,
DsNotOnBacklink = 8362,
DsNoCrossrefForNc = 8363,
DsShuttingDown = 8364,
DsUnknownOperation = 8365,
DsInvalidRoleOwner = 8366,
DsCouldntContactFsmo = 8367,
DsCrossNcDnRename = 8368,
DsCantModSystemOnly = 8369,
DsReplicatorOnly = 8370,
DsObjClassNotDefined = 8371,
DsObjClassNotSubclass = 8372,
DsNameReferenceInvalid = 8373,
DsCrossRefExists = 8374,
DsCantDelMasterCrossref = 8375,
DsSubtreeNotifyNotNcHead = 8376,
DsNotifyFilterTooComplex = 8377,
DsDupRdn = 8378,
DsDupOid = 8379,
DsDupMapiId = 8380,
DsDupSchemaIdGuid = 8381,
DsDupLdapDisplayName = 8382,
DsSemanticAttTest = 8383,
DsSyntaxMismatch = 8384,
DsExistsInMustHave = 8385,
DsExistsInMayHave = 8386,
DsNonexistentMayHave = 8387,
DsNonexistentMustHave = 8388,
DsAuxClsTestFail = 8389,
DsNonexistentPossSup = 8390,
DsSubClsTestFail = 8391,
DsBadRdnAttIdSyntax = 8392,
DsExistsInAuxCls = 8393,
DsExistsInSubCls = 8394,
DsExistsInPossSup = 8395,
DsRecalcschemaFailed = 8396,
DsTreeDeleteNotFinished = 8397,
DsCantDelete = 8398,
DsAttSchemaReqId = 8399,
DsBadAttSchemaSyntax = 8400,
DsCantCacheAtt = 8401,
DsCantCacheClass = 8402,
DsCantRemoveAttCache = 8403,
DsCantRemoveClassCache = 8404,
DsCantRetrieveDn = 8405,
DsMissingSupref = 8406,
DsCantRetrieveInstance = 8407,
DsCodeInconsistency = 8408,
DsDatabaseError = 8409,
DsGovernsidMissing = 8410,
DsMissingExpectedAtt = 8411,
DsNcnameMissingCrRef = 8412,
DsSecurityCheckingError = 8413,
DsSchemaNotLoaded = 8414,
DsSchemaAllocFailed = 8415,
DsAttSchemaReqSyntax = 8416,
DsGcverifyError = 8417,
DsDraSchemaMismatch = 8418,
DsCantFindDsaObj = 8419,
DsCantFindExpectedNc = 8420,
DsCantFindNcInCache = 8421,
DsCantRetrieveChild = 8422,
DsSecurityIllegalModify = 8423,
DsCantReplaceHiddenRec = 8424,
DsBadHierarchyFile = 8425,
DsBuildHierarchyTableFailed = 8426,
DsConfigParamMissing = 8427,
DsCountingAbIndicesFailed = 8428,
DsHierarchyTableMallocFailed = 8429,
DsInternalFailure = 8430,
DsUnknownError = 8431,
DsRootRequiresClassTop = 8432,
DsRefusingFsmoRoles = 8433,
DsMissingFsmoSettings = 8434,
DsUnableToSurrenderRoles = 8435,
DsDraGeneric = 8436,
DsDraInvalidParameter = 8437,
DsDraBusy = 8438,
DsDraBadDn = 8439,
DsDraBadNc = 8440,
DsDraDnExists = 8441,
DsDraInternalError = 8442,
DsDraInconsistentDit = 8443,
DsDraConnectionFailed = 8444,
DsDraBadInstanceType = 8445,
DsDraOutOfMem = 8446,
DsDraMailProblem = 8447,
DsDraRefAlreadyExists = 8448,
DsDraRefNotFound = 8449,
DsDraObjIsRepSource = 8450,
DsDraDbError = 8451,
DsDraNoReplica = 8452,
DsDraAccessDenied = 8453,
DsDraNotSupported = 8454,
DsDraRpcCancelled = 8455,
DsDraSourceDisabled = 8456,
DsDraSinkDisabled = 8457,
DsDraNameCollision = 8458,
DsDraSourceReinstalled = 8459,
DsDraMissingParent = 8460,
DsDraPreempted = 8461,
DsDraAbandonSync = 8462,
DsDraShutdown = 8463,
DsDraIncompatiblePartialSet = 8464,
DsDraSourceIsPartialReplica = 8465,
DsDraExtnConnectionFailed = 8466,
DsInstallSchemaMismatch = 8467,
DsDupLinkId = 8468,
DsNameErrorResolving = 8469,
DsNameErrorNotFound = 8470,
DsNameErrorNotUnique = 8471,
DsNameErrorNoMapping = 8472,
DsNameErrorDomainOnly = 8473,
DsNameErrorNoSyntacticalMapping = 8474,
DsConstructedAttMod = 8475,
DsWrongOmObjClass = 8476,
DsDraReplPending = 8477,
DsDsRequired = 8478,
DsInvalidLdapDisplayName = 8479,
DsNonBaseSearch = 8480,
DsCantRetrieveAtts = 8481,
DsBacklinkWithoutLink = 8482,
DsEpochMismatch = 8483,
DsSrcNameMismatch = 8484,
DsSrcAndDstNcIdentical = 8485,
DsDstNcMismatch = 8486,
DsNotAuthoritiveForDstNc = 8487,
DsSrcGuidMismatch = 8488,
DsCantMoveDeletedObject = 8489,
DsPdcOperationInProgress = 8490,
DsCrossDomainCleanupReqd = 8491,
DsIllegalXdomMoveOperation = 8492,
DsCantWithAcctGroupMembershps = 8493,
DsNcMustHaveNcParent = 8494,
DsCrImpossibleToValidate = 8495,
DsDstDomainNotNative = 8496,
DsMissingInfrastructureContainer = 8497,
DsCantMoveAccountGroup = 8498,
DsCantMoveResourceGroup = 8499,
DsInvalidSearchFlag = 8500,
DsNoTreeDeleteAboveNc = 8501,
DsCouldntLockTreeForDelete = 8502,
DsCouldntIdentifyObjectsForTreeDelete = 8503,
DsSamInitFailure = 8504,
DsSensitiveGroupViolation = 8505,
DsCantModPrimarygroupid = 8506,
DsIllegalBaseSchemaMod = 8507,
DsNonsafeSchemaChange = 8508,
DsSchemaUpdateDisallowed = 8509,
DsCantCreateUnderSchema = 8510,
DsInstallNoSrcSchVersion = 8511,
DsInstallNoSchVersionInInifile = 8512,
DsInvalidGroupType = 8513,
DsNoNestGlobalgroupInMixeddomain = 8514,
DsNoNestLocalgroupInMixeddomain = 8515,
DsGlobalCantHaveLocalMember = 8516,
DsGlobalCantHaveUniversalMember = 8517,
DsUniversalCantHaveLocalMember = 8518,
DsGlobalCantHaveCrossdomainMember = 8519,
DsLocalCantHaveCrossdomainLocalMember = 8520,
DsHavePrimaryMembers = 8521,
DsStringSdConversionFailed = 8522,
DsNamingMasterGc = 8523,
DsDnsLookupFailure = 8524,
DsCouldntUpdateSpns = 8525,
DsCantRetrieveSd = 8526,
DsKeyNotUnique = 8527,
DsWrongLinkedAttSyntax = 8528,
DsSamNeedBootkeyPassword = <PASSWORD>,
DsSamNeedBootkeyFloppy = 8530,
DsCantStart = 8531,
DsInitFailure = 8532,
DsNoPktPrivacyOnConnection = 8533,
DsSourceDomainInForest = 8534,
DsDestinationDomainNotInForest = 8535,
DsDestinationAuditingNotEnabled = 8536,
DsCantFindDcForSrcDomain = 8537,
DsSrcObjNotGroupOrUser = 8538,
DsSrcSidExistsInForest = 8539,
DsSrcAndDstObjectClassMismatch = 8540,
SamInitFailure = 8541,
DsDraSchemaInfoShip = 8542,
DsDraSchemaConflict = 8543,
DsDraEarlierSchemaConflict = 8544,
DsDraObjNcMismatch = 8545,
DsNcStillHasDsas = 8546,
DsGcRequired = 8547,
DsLocalMemberOfLocalOnly = 8548,
DsNoFpoInUniversalGroups = 8549,
DsCantAddToGc = 8550,
DsNoCheckpointWithPdc = 8551,
DsSourceAuditingNotEnabled = 8552,
DsCantCreateInNondomainNc = 8553,
DsInvalidNameForSpn = 8554,
DsFilterUsesContructedAttrs = 8555,
DsUnicodepwdNotInQuotes = 8556,
DsMachineAccountQuotaExceeded = 8557,
DsMustBeRunOnDstDc = 8558,
DsSrcDcMustBeSp4OrGreater = 8559,
DsCantTreeDeleteCriticalObj = 8560,
DsInitFailureConsole = 8561,
DsSamInitFailureConsole = 8562,
DsForestVersionTooHigh = 8563,
DsDomainVersionTooHigh = 8564,
DsForestVersionTooLow = 8565,
DsDomainVersionTooLow = 8566,
DsIncompatibleVersion = 8567,
DsLowDsaVersion = 8568,
DsNoBehaviorVersionInMixeddomain = 8569,
DsNotSupportedSortOrder = 8570,
DsNameNotUnique = 8571,
DsMachineAccountCreatedPrent4 = 8572,
DsOutOfVersionStore = 8573,
DsIncompatibleControlsUsed = 8574,
DsNoRefDomain = 8575,
DsReservedLinkId = 8576,
DsLinkIdNotAvailable = 8577,
DsAgCantHaveUniversalMember = 8578,
DsModifydnDisallowedByInstanceType = 8579,
DsNoObjectMoveInSchemaNc = 8580,
DsModifydnDisallowedByFlag = 8581,
DsModifydnWrongGrandparent = 8582,
DsNameErrorTrustReferral = 8583,
NotSupportedOnStandardServer = 8584,
DsCantAccessRemotePartOfAd = 8585,
DsCrImpossibleToValidateV2 = 8586,
DsThreadLimitExceeded = 8587,
DsNotClosest = 8588,
DsCantDeriveSpnWithoutServerRef = 8589,
DsSingleUserModeFailed = 8590,
DsNtdscriptSyntaxError = 8591,
DsNtdscriptProcessError = 8592,
DsDifferentReplEpochs = 8593,
DsDrsExtensionsChanged = 8594,
DsReplicaSetChangeNotAllowedOnDisabledCr = 8595,
DsNoMsdsIntid = 8596,
DsDupMsdsIntid = 8597,
DsExistsInRdnattid = 8598,
DsAuthorizationFailed = 8599,
DsInvalidScript = 8600,
DsRemoteCrossrefOpFailed = 8601,
DsCrossRefBusy = 8602,
DsCantDeriveSpnForDeletedDomain = 8603,
DsCantDemoteWithWriteableNc = 8604,
DsDuplicateIdFound = 8605,
DsInsufficientAttrToCreateObject = 8606,
DsGroupConversionError = 8607,
DsCantMoveAppBasicGroup = 8608,
DsCantMoveAppQueryGroup = 8609,
DsRoleNotVerified = 8610,
DsWkoContainerCannotBeSpecial = 8611,
DsDomainRenameInProgress = 8612,
DsExistingAdChildNc = 8613,
DsReplLifetimeExceeded = 8614,
DsDisallowedInSystemContainer = 8615,
DsLdapSendQueueFull = 8616,
DsDraOutScheduleWindow = 8617,
DsPolicyNotKnown = 8618,
NoSiteSettingsObject = 8619,
NoSecrets = 8620,
NoWritableDcFound = 8621,
DsNoServerObject = 8622,
DsNoNtdsaObject = 8623,
DsNonAsqSearch = 8624,
DsAuditFailure = 8625,
DsInvalidSearchFlagSubtree = 8626,
DsInvalidSearchFlagTuple = 8627,
DsHierarchyTableTooDeep = 8628,
DsDraCorruptUtdVector = 8629,
DsDraSecretsDenied = 8630,
DsReservedMapiId = 8631,
DsMapiIdNotAvailable = 8632,
DsDraMissingKrbtgtSecret = 8633,
DsDomainNameExistsInForest = 8634,
DsFlatNameExistsInForest = 8635,
InvalidUserPrincipalName = 8636,
DsOidMappedGroupCantHaveMembers = 8637,
DsOidNotFound = 8638,
DsDraRecycledTarget = 8639,
DsDisallowedNcRedirect = 8640,
DsHighAdldsFfl = 8641,
DsHighDsaVersion = 8642,
DsLowAdldsFfl = 8643,
DomainSidSameAsLocalWorkstation = 8644,
DsUndeleteSamValidationFailed = 8645,
IncorrectAccountType = 8646,
DsSpnValueNotUniqueInForest = 8647,
DsUpnValueNotUniqueInForest = 8648,
DsMissingForestTrust = 8649,
DsValueKeyNotUnique = 8650,
IpsecQmPolicyExists = 13000,
IpsecQmPolicyNotFound = 13001,
IpsecQmPolicyInUse = 13002,
IpsecMmPolicyExists = 13003,
IpsecMmPolicyNotFound = 13004,
IpsecMmPolicyInUse = 13005,
IpsecMmFilterExists = 13006,
IpsecMmFilterNotFound = 13007,
IpsecTransportFilterExists = 13008,
IpsecTransportFilterNotFound = 13009,
IpsecMmAuthExists = 13010,
IpsecMmAuthNotFound = 13011,
IpsecMmAuthInUse = 13012,
IpsecDefaultMmPolicyNotFound = 13013,
IpsecDefaultMmAuthNotFound = 13014,
IpsecDefaultQmPolicyNotFound = 13015,
IpsecTunnelFilterExists = 13016,
IpsecTunnelFilterNotFound = 13017,
IpsecMmFilterPendingDeletion = 13018,
IpsecTransportFilterPendingDeletion = 13019,
IpsecTunnelFilterPendingDeletion = 13020,
IpsecMmPolicyPendingDeletion = 13021,
IpsecMmAuthPendingDeletion = 13022,
IpsecQmPolicyPendingDeletion = 13023,
IpsecIkeNegStatusBegin = 13800,
IpsecIkeAuthFail = 13801,
IpsecIkeAttribFail = 13802,
IpsecIkeNegotiationPending = 13803,
IpsecIkeGeneralProcessingError = 13804,
IpsecIkeTimedOut = 13805,
IpsecIkeNoCert = 13806,
IpsecIkeSaDeleted = 13807,
IpsecIkeSaReaped = 13808,
IpsecIkeMmAcquireDrop = 13809,
IpsecIkeQmAcquireDrop = 13810,
IpsecIkeQueueDropMm = 13811,
IpsecIkeQueueDropNoMm = 13812,
IpsecIkeDropNoResponse = 13813,
IpsecIkeMmDelayDrop = 13814,
IpsecIkeQmDelayDrop = 13815,
IpsecIkeError = 13816,
IpsecIkeCrlFailed = 13817,
IpsecIkeInvalidKeyUsage = 13818,
IpsecIkeInvalidCertType = 13819,
IpsecIkeNoPrivateKey = 13820,
IpsecIkeSimultaneousRekey = 13821,
IpsecIkeDhFail = 13822,
IpsecIkeCriticalPayloadNotRecognized = 13823,
IpsecIkeInvalidHeader = 13824,
IpsecIkeNoPolicy = 13825,
IpsecIkeInvalidSignature = 13826,
IpsecIkeKerberosError = 13827,
IpsecIkeNoPublicKey = 13828,
IpsecIkeProcessErr = 13829,
IpsecIkeProcessErrSa = 13830,
IpsecIkeProcessErrProp = 13831,
IpsecIkeProcessErrTrans = 13832,
IpsecIkeProcessErrKe = 13833,
IpsecIkeProcessErrId = 13834,
IpsecIkeProcessErrCert = 13835,
IpsecIkeProcessErrCertReq = 13836,
IpsecIkeProcessErrHash = 13837,
IpsecIkeProcessErrSig = 13838,
IpsecIkeProcessErrNonce = 13839,
IpsecIkeProcessErrNotify = 13840,
IpsecIkeProcessErrDelete = 13841,
IpsecIkeProcessErrVendor = 13842,
IpsecIkeInvalidPayload = 13843,
IpsecIkeLoadSoftSa = 13844,
IpsecIkeSoftSaTornDown = 13845,
IpsecIkeInvalidCookie = 13846,
IpsecIkeNoPeerCert = 13847,
IpsecIkePeerCrlFailed = 13848,
IpsecIkePolicyChange = 13849,
IpsecIkeNoMmPolicy = 13850,
IpsecIkeNotcbpriv = 13851,
IpsecIkeSecloadfail = 13852,
IpsecIkeFailsspinit = 13853,
IpsecIkeFailqueryssp = 13854,
IpsecIkeSrvacqfail = 13855,
IpsecIkeSrvquerycred = 13856,
IpsecIkeGetspifail = 13857,
IpsecIkeInvalidFilter = 13858,
IpsecIkeOutOfMemory = 13859,
IpsecIkeAddUpdateKeyFailed = 13860,
IpsecIkeInvalidPolicy = 13861,
IpsecIkeUnknownDoi = 13862,
IpsecIkeInvalidSituation = 13863,
IpsecIkeDhFailure = 13864,
IpsecIkeInvalidGroup = 13865,
IpsecIkeEncrypt = 13866,
IpsecIkeDecrypt = 13867,
IpsecIkePolicyMatch = 13868,
IpsecIkeUnsupportedId = 13869,
IpsecIkeInvalidHash = 13870,
IpsecIkeInvalidHashAlg = 13871,
IpsecIkeInvalidHashSize = 13872,
IpsecIkeInvalidEncryptAlg = 13873,
IpsecIkeInvalidAuthAlg = 13874,
IpsecIkeInvalidSig = 13875,
IpsecIkeLoadFailed = 13876,
IpsecIkeRpcDelete = 13877,
IpsecIkeBenignReinit = 13878,
IpsecIkeInvalidResponderLifetimeNotify = 13879,
IpsecIkeInvalidMajorVersion = 13880,
IpsecIkeInvalidCertKeylen = 13881,
IpsecIkeMmLimit = 13882,
IpsecIkeNegotiationDisabled = 13883,
IpsecIkeQmLimit = 13884,
IpsecIkeMmExpired = 13885,
IpsecIkePeerMmAssumedInvalid = 13886,
IpsecIkeCertChainPolicyMismatch = 13887,
IpsecIkeUnexpectedMessageId = 13888,
IpsecIkeInvalidAuthPayload = 13889,
IpsecIkeDosCookieSent = 13890,
IpsecIkeShuttingDown = 13891,
IpsecIkeCgaAuthFailed = 13892,
IpsecIkeProcessErrNatoa = 13893,
IpsecIkeInvalidMmForQm = 13894,
IpsecIkeQmExpired = 13895,
IpsecIkeTooManyFilters = 13896,
IpsecIkeNegStatusEnd = 13897,
IpsecIkeKillDummyNapTunnel = 13898,
IpsecIkeInnerIpAssignmentFailure = 13899,
IpsecIkeRequireCpPayloadMissing = 13900,
IpsecKeyModuleImpersonationNegotiationPending = 13901,
IpsecIkeCoexistenceSuppress = 13902,
IpsecIkeRatelimitDrop = 13903,
IpsecIkePeerDoesntSupportMobike = 13904,
IpsecIkeAuthorizationFailure = 13905,
IpsecIkeStrongCredAuthorizationFailure = 13906,
IpsecIkeAuthorizationFailureWithOptionalRetry = 13907,
IpsecIkeStrongCredAuthorizationAndCertmapFailure = 13908,
IpsecIkeNegStatusExtendedEnd = 13909,
IpsecBadSpi = 13910,
IpsecSaLifetimeExpired = 13911,
IpsecWrongSa = 13912,
IpsecReplayCheckFailed = 13913,
IpsecInvalidPacket = 13914,
IpsecIntegrityCheckFailed = 13915,
IpsecClearTextDrop = 13916,
IpsecAuthFirewallDrop = 13917,
IpsecThrottleDrop = 13918,
IpsecDospBlock = 13925,
IpsecDospReceivedMulticast = 13926,
IpsecDospInvalidPacket = 13927,
IpsecDospStateLookupFailed = 13928,
IpsecDospMaxEntries = 13929,
IpsecDospKeymodNotAllowed = 13930,
IpsecDospNotInstalled = 13931,
IpsecDospMaxPerIpRatelimitQueues = 13932,
SxsSectionNotFound = 14000,
SxsCantGenActctx = 14001,
SxsInvalidActctxdataFormat = 14002,
SxsAssemblyNotFound = 14003,
SxsManifestFormatError = 14004,
SxsManifestParseError = 14005,
SxsActivationContextDisabled = 14006,
SxsKeyNotFound = 14007,
SxsVersionConflict = 14008,
SxsWrongSectionType = 14009,
SxsThreadQueriesDisabled = 14010,
SxsProcessDefaultAlreadySet = 14011,
SxsUnknownEncodingGroup = 14012,
SxsUnknownEncoding = 14013,
SxsInvalidXmlNamespaceUri = 14014,
SxsRootManifestDependencyNotInstalled = 14015,
SxsLeafManifestDependencyNotInstalled = 14016,
SxsInvalidAssemblyIdentityAttribute = 14017,
SxsManifestMissingRequiredDefaultNamespace = 14018,
SxsManifestInvalidRequiredDefaultNamespace = 14019,
SxsPrivateManifestCrossPathWithReparsePoint = 14020,
SxsDuplicateDllName = 14021,
SxsDuplicateWindowclassName = 14022,
SxsDuplicateClsid = 14023,
SxsDuplicateIid = 14024,
SxsDuplicateTlbid = 14025,
SxsDuplicateProgid = 14026,
SxsDuplicateAssemblyName = 14027,
SxsFileHashMismatch = 14028,
SxsPolicyParseError = 14029,
SxsXmlEMissingquote = 14030,
SxsXmlECommentsyntax = 14031,
SxsXmlEBadstartnamechar = 14032,
SxsXmlEBadnamechar = 14033,
SxsXmlEBadcharinstring = 14034,
SxsXmlEXmldeclsyntax = 14035,
SxsXmlEBadchardata = 14036,
SxsXmlEMissingwhitespace = 14037,
SxsXmlEExpectingtagend = 14038,
SxsXmlEMissingsemicolon = 14039,
SxsXmlEUnbalancedparen = 14040,
SxsXmlEInternalerror = 14041,
SxsXmlEUnexpectedWhitespace = 14042,
SxsXmlEIncompleteEncoding = 14043,
SxsXmlEMissingParen = 14044,
SxsXmlEExpectingclosequote = 14045,
SxsXmlEMultipleColons = 14046,
SxsXmlEInvalidDecimal = 14047,
SxsXmlEInvalidHexidecimal = 14048,
SxsXmlEInvalidUnicode = 14049,
SxsXmlEWhitespaceorquestionmark = 14050,
SxsXmlEUnexpectedendtag = 14051,
SxsXmlEUnclosedtag = 14052,
SxsXmlEDuplicateattribute = 14053,
SxsXmlEMultipleroots = 14054,
SxsXmlEInvalidatrootlevel = 14055,
SxsXmlEBadxmldecl = 14056,
SxsXmlEMissingroot = 14057,
SxsXmlEUnexpectedeof = 14058,
SxsXmlEBadperefinsubset = 14059,
SxsXmlEUnclosedstarttag = 14060,
SxsXmlEUnclosedendtag = 14061,
SxsXmlEUnclosedstring = 14062,
SxsXmlEUnclosedcomment = 14063,
SxsXmlEUncloseddecl = 14064,
SxsXmlEUnclosedcdata = 14065,
SxsXmlEReservednamespace = 14066,
SxsXmlEInvalidencoding = 14067,
SxsXmlEInvalidswitch = 14068,
SxsXmlEBadxmlcase = 14069,
SxsXmlEInvalidStandalone = 14070,
SxsXmlEUnexpectedStandalone = 14071,
SxsXmlEInvalidVersion = 14072,
SxsXmlEMissingequals = 14073,
SxsProtectionRecoveryFailed = 14074,
SxsProtectionPublicKeyTooShort = 14075,
SxsProtectionCatalogNotValid = 14076,
SxsUntranslatableHresult = 14077,
SxsProtectionCatalogFileMissing = 14078,
SxsMissingAssemblyIdentityAttribute = 14079,
SxsInvalidAssemblyIdentityAttributeName = 14080,
SxsAssemblyMissing = 14081,
SxsCorruptActivationStack = 14082,
SxsCorruption = 14083,
SxsEarlyDeactivation = 14084,
SxsInvalidDeactivation = 14085,
SxsMultipleDeactivation = 14086,
SxsProcessTerminationRequested = 14087,
SxsReleaseActivationContext = 14088,
SxsSystemDefaultActivationContextEmpty = 14089,
SxsInvalidIdentityAttributeValue = 14090,
SxsInvalidIdentityAttributeName = 14091,
SxsIdentityDuplicateAttribute = 14092,
SxsIdentityParseError = 14093,
MalformedSubstitutionString = 14094,
SxsIncorrectPublicKeyToken = 14095,
UnmappedSubstitutionString = 14096,
SxsAssemblyNotLocked = 14097,
SxsComponentStoreCorrupt = 14098,
AdvancedInstallerFailed = 14099,
XmlEncodingMismatch = 14100,
SxsManifestIdentitySameButContentsDifferent = 14101,
SxsIdentitiesDifferent = 14102,
SxsAssemblyIsNotADeployment = 14103,
SxsFileNotPartOfAssembly = 14104,
SxsManifestTooBig = 14105,
SxsSettingNotRegistered = 14106,
SxsTransactionClosureIncomplete = 14107,
SmiPrimitiveInstallerFailed = 14108,
GenericCommandFailed = 14109,
SxsFileHashMissing = 14110,
EvtInvalidChannelPath = 15000,
EvtInvalidQuery = 15001,
EvtPublisherMetadataNotFound = 15002,
EvtEventTemplateNotFound = 15003,
EvtInvalidPublisherName = 15004,
EvtInvalidEventData = 15005,
EvtChannelNotFound = 15007,
EvtMalformedXmlText = 15008,
EvtSubscriptionToDirectChannel = 15009,
EvtConfigurationError = 15010,
EvtQueryResultStale = 15011,
EvtQueryResultInvalidPosition = 15012,
EvtNonValidatingMsxml = 15013,
EvtFilterAlreadyscoped = 15014,
EvtFilterNoteltset = 15015,
EvtFilterInvarg = 15016,
EvtFilterInvtest = 15017,
EvtFilterInvtype = 15018,
EvtFilterParseerr = 15019,
EvtFilterUnsupportedop = 15020,
EvtFilterUnexpectedtoken = 15021,
EvtInvalidOperationOverEnabledDirectChannel = 15022,
EvtInvalidChannelPropertyValue = 15023,
EvtInvalidPublisherPropertyValue = 15024,
EvtChannelCannotActivate = 15025,
EvtFilterTooComplex = 15026,
EvtMessageNotFound = 15027,
EvtMessageIdNotFound = 15028,
EvtUnresolvedValueInsert = 15029,
EvtUnresolvedParameterInsert = 15030,
EvtMaxInsertsReached = 15031,
EvtEventDefinitionNotFound = 15032,
EvtMessageLocaleNotFound = 15033,
EvtVersionTooOld = 15034,
EvtVersionTooNew = 15035,
EvtCannotOpenChannelOfQuery = 15036,
EvtPublisherDisabled = 15037,
EvtFilterOutOfRange = 15038,
EcSubscriptionCannotActivate = 15080,
EcLogDisabled = 15081,
EcCircularForwarding = 15082,
EcCredstoreFull = 15083,
EcCredNotFound = 15084,
EcNoActiveChannel = 15085,
MuiFileNotFound = 15100,
MuiInvalidFile = 15101,
MuiInvalidRcConfig = 15102,
MuiInvalidLocaleName = 15103,
MuiInvalidUltimatefallbackName = 15104,
MuiFileNotLoaded = 15105,
ResourceEnumUserStop = 15106,
MuiIntlsettingsUilangNotInstalled = 15107,
MuiIntlsettingsInvalidLocaleName = 15108,
MrmRuntimeNoDefaultOrNeutralResource = 15110,
MrmInvalidPriconfig = 15111,
MrmInvalidFileType = 15112,
MrmUnknownQualifier = 15113,
MrmInvalidQualifierValue = 15114,
MrmNoCandidate = 15115,
MrmNoMatchOrDefaultCandidate = 15116,
MrmResourceTypeMismatch = 15117,
MrmDuplicateMapName = 15118,
MrmDuplicateEntry = 15119,
MrmInvalidResourceIdentifier = 15120,
MrmFilepathTooLong = 15121,
MrmUnsupportedDirectoryType = 15122,
MrmInvalidPriFile = 15126,
MrmNamedResourceNotFound = 15127,
MrmMapNotFound = 15135,
MrmUnsupportedProfileType = 15136,
MrmInvalidQualifierOperator = 15137,
MrmIndeterminateQualifierValue = 15138,
MrmAutomergeEnabled = 15139,
MrmTooManyResources = 15140,
MrmUnsupportedFileTypeForMerge = 15141,
MrmUnsupportedFileTypeForLoadUnloadPriFile = 15142,
MrmNoCurrentViewOnThread = 15143,
DifferentProfileResourceManagerExist = 15144,
OperationNotAllowedFromSystemComponent = 15145,
MrmDirectRefToNonDefaultResource = 15146,
MrmGenerationCountMismatch = 15147,
McaInvalidCapabilitiesString = 15200,
McaInvalidVcpVersion = 15201,
McaMonitorViolatesMccsSpecification = 15202,
McaMccsVersionMismatch = 15203,
McaUnsupportedMccsVersion = 15204,
McaInternalError = 15205,
McaInvalidTechnologyTypeReturned = 15206,
McaUnsupportedColorTemperature = 15207,
AmbiguousSystemDevice = 15250,
SystemDeviceNotFound = 15299,
HashNotSupported = 15300,
HashNotPresent = 15301,
SecondaryIcProviderNotRegistered = 15321,
GpioClientInformationInvalid = 15322,
GpioVersionNotSupported = 15323,
GpioInvalidRegistrationPacket = 15324,
GpioOperationDenied = 15325,
GpioIncompatibleConnectMode = 15326,
GpioInterruptAlreadyUnmasked = 15327,
CannotSwitchRunlevel = 15400,
InvalidRunlevelSetting = 15401,
RunlevelSwitchTimeout = 15402,
RunlevelSwitchAgentTimeout = 15403,
RunlevelSwitchInProgress = 15404,
ServicesFailedAutostart = 15405,
ComTaskStopPending = 15501,
InstallOpenPackageFailed = 15600,
InstallPackageNotFound = 15601,
InstallInvalidPackage = 15602,
InstallResolveDependencyFailed = 15603,
InstallOutOfDiskSpace = 15604,
InstallNetworkFailure = 15605,
InstallRegistrationFailure = 15606,
InstallDeregistrationFailure = 15607,
InstallCancel = 15608,
InstallFailed = 15609,
RemoveFailed = 15610,
PackageAlreadyExists = 15611,
NeedsRemediation = 15612,
InstallPrerequisiteFailed = 15613,
PackageRepositoryCorrupted = 15614,
InstallPolicyFailure = 15615,
PackageUpdating = 15616,
DeploymentBlockedByPolicy = 15617,
PackagesInUse = 15618,
RecoveryFileCorrupt = 15619,
InvalidStagedSignature = 15620,
DeletingExistingApplicationdataStoreFailed = 15621,
InstallPackageDowngrade = 15622,
SystemNeedsRemediation = 15623,
AppxIntegrityFailureClrNgen = 15624,
ResiliencyFileCorrupt = 15625,
InstallFirewallServiceNotRunning = 15626,
PackageMoveFailed = 15627,
InstallVolumeNotEmpty = 15628,
InstallVolumeOffline = 15629,
InstallVolumeCorrupt = 15630,
NeedsRegistration = 15631,
InstallWrongProcessorArchitecture = 15632,
DevSideloadLimitExceeded = 15633,
StateLoadStoreFailed = 15800,
StateGetVersionFailed = 15801,
StateSetVersionFailed = 15802,
StateStructuredResetFailed = 15803,
StateOpenContainerFailed = 15804,
StateCreateContainerFailed = 15805,
StateDeleteContainerFailed = 15806,
StateReadSettingFailed = 15807,
StateWriteSettingFailed = 15808,
StateDeleteSettingFailed = 15809,
StateQuerySettingFailed = 15810,
StateReadCompositeSettingFailed = 15811,
StateWriteCompositeSettingFailed = 15812,
StateEnumerateContainerFailed = 15813,
StateEnumerateSettingsFailed = 15814,
StateCompositeSettingValueSizeLimitExceeded = 15815,
StateSettingValueSizeLimitExceeded = 15816,
StateSettingNameSizeLimitExceeded = 15817,
StateContainerNameSizeLimitExceeded = 15818,
ApiUnavailable = 15841
}
}<file_sep>/src-csharp6/Native/Gdi32.cs
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
// ReSharper disable UnassignedReadonlyField
// ReSharper disable InconsistentNaming
#pragma warning disable 169
namespace Example.Native
{
public static class Gdi32
{
public abstract class GdiObjectSafeHandle : SafeHandle
{
protected GdiObjectSafeHandle() : base(IntPtr.Zero, true)
{
}
public override bool IsInvalid => handle == IntPtr.Zero;
protected override bool ReleaseHandle() => DeleteObject(handle);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
}
public sealed class BitmapSafeHandle : GdiObjectSafeHandle
{
private BitmapSafeHandle()
{
}
public unsafe Bitmap AsBitmap()
{
BITMAP info;
if (GetObject(this, sizeof(BITMAP), out info) != sizeof(BITMAP))
{
if (IsInvalid) throw new ObjectDisposedException(nameof(BitmapSafeHandle));
throw new Win32Exception("GetObject failed.");
}
if (info.bmBits == IntPtr.Zero) throw new InvalidOperationException("Cannot access image data directly without first making a copy.");
return info.bmHeight > 0
? new Bitmap(info.bmWidth, info.bmHeight, -info.bmWidthBytes, GetPixelFormat(info.bmBitsPixel), info.bmBits + (info.bmHeight - 1) * info.bmWidthBytes)
: new Bitmap(info.bmWidth, -info.bmHeight, info.bmWidthBytes, GetPixelFormat(info.bmBitsPixel), info.bmBits);
}
public Bitmap CopyAndFree()
{
using (this) return new Bitmap(AsBitmap());
}
private static PixelFormat GetPixelFormat(ushort numBitsPerPixel)
{
switch (numBitsPerPixel)
{
case 32:
return PixelFormat.Format32bppArgb;
case 24:
return PixelFormat.Format24bppRgb;
default:
throw new NotImplementedException();
}
}
}
[DllImport("gdi32.dll")]
public static extern int GetObject(BitmapSafeHandle hBitmap, int cbBuffer, out BITMAP lpBitmap);
public struct BITMAP
{
private readonly int bmType;
public readonly int bmWidth;
public readonly int bmHeight;
public readonly int bmWidthBytes;
private readonly ushort bmPlanes;
public readonly ushort bmBitsPixel;
public readonly IntPtr bmBits;
}
}
}
<file_sep>/src/Native/HResult.cs
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Example.Native
{
[DebuggerDisplay("{ToString(),nq}")]
public struct HResult : IEquatable<HResult>
{
public static readonly HResult Ok = (HResult)0;
public static readonly HResult False = (HResult)1;
private readonly uint value;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private HResult(uint value)
{
this.value = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator HResult(int value) => new HResult(unchecked((uint)value));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator HResult(uint value) => new HResult(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator int(HResult hresult) => unchecked((int)hresult.value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator uint(HResult value) => value.value;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(HResult left, HResult right) => left.value == right.value;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(HResult left, HResult right) => left.value != right.value;
public WinErrorCode Code
{
get { return unchecked((WinErrorCode)value); }
}
public bool IsError
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return (value & 0x80000000) != 0; }
}
public HResultFacility Facility
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return unchecked((HResultFacility)((value >> 16) & 0x7FF)); }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString()
{
return $"0x{value:X8}";
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Exception CreateException() => new Win32Exception((int)Code);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Exception CreateException(string message) => new Win32Exception((int)Code, message);
[DebuggerNonUserCode]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ThrowIfError()
{
if (IsError) throw CreateException();
}
[DebuggerNonUserCode]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ThrowIfError(string message)
{
if (IsError) throw CreateException(message);
}
public bool Equals(HResult other) => value == other.value;
public override bool Equals(object obj) => obj is HResult && Equals((HResult)obj);
public override int GetHashCode() => (int)value;
}
}
<file_sep>/src-csharp6/Native/POINT.cs
using System.Diagnostics;
using System.Drawing;
namespace Example.Native
{
[DebuggerDisplay("{ToString(),nq}")]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
public override string ToString()
{
return X + ", " + Y;
}
public static implicit operator Point(POINT point)
{
return new Point(point.X, point.Y);
}
public static implicit operator POINT(Point point)
{
return new POINT(point.X, point.Y);
}
}
}
<file_sep>/src/Native/Shell32.cs
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
// ReSharper disable InconsistentNaming
#pragma warning disable 649
namespace Example.Native
{
public static class Shell32
{
public const short CF_UNICODETEXT = 13;
public static class FOLDERID
{
public static readonly Guid ControlPanelFolder = new Guid("82A74AEB-AEB4-465C-A014-D097EE346D63");
public static readonly Guid PrintersFolder = new Guid("76FC4E2D-D6AD-4519-A663-37BD56068185");
}
public static class PKEY
{
public static readonly PROPERTYKEY Devices_FriendlyName = new PROPERTYKEY(new Guid("656A3BB3-ECC<KEY>"), 12288);
public static readonly PROPERTYKEY Devices_CategoryIds = new PROPERTYKEY(new Guid("78C34FC8-104A-4ACA-9EA4-524D52996E57"), 90);
public static readonly PROPERTYKEY Devices_Status1 = new PROPERTYKEY(new Guid("78C34FC8-104A-4ACA-9EA4-524D52996E57"), 81);
public static readonly PROPERTYKEY Devices_Status2 = new PROPERTYKEY(new Guid("78C34FC8-104A-4ACA-9EA4-524D52996E57"), 82);
}
public class CoTaskMemSafeHandle : SafeHandle
{
protected CoTaskMemSafeHandle() : base(IntPtr.Zero, true)
{
}
public override bool IsInvalid => handle == IntPtr.Zero;
protected override bool ReleaseHandle()
{
Marshal.FreeCoTaskMem(handle);
return true;
}
}
public sealed class ItemIdListSafeHandle : CoTaskMemSafeHandle
{
private ItemIdListSafeHandle()
{
}
}
public sealed class CoTaskStringSafeHandle : CoTaskMemSafeHandle
{
private CoTaskStringSafeHandle()
{
}
public static CoTaskStringSafeHandle FromPointer(IntPtr pointer)
{
var r = new CoTaskStringSafeHandle();
r.SetHandle(pointer);
return r;
}
public string ReadAndFree()
{
using (this)
return Marshal.PtrToStringUni(handle);
}
}
[DllImport("shell32.dll")]
public static extern HResult SHGetKnownFolderIDList([In, MarshalAs(UnmanagedType.LPStruct)] Guid rfid, KF_FLAG dwFlags, IntPtr hToken, out ItemIdListSafeHandle ppidl);
[Flags]
public enum KF_FLAG : uint
{
DEFAULT = 0x00000000,
SIMPLE_IDLIST = 0x00000100,
NOT_PARENT_RELATIVE = 0x00000200,
DEFAULT_PATH = 0x00000400,
INIT = 0x00000800,
NO_ALIAS = 0x00001000,
DONT_UNEXPAND = 0x00002000,
DONT_VERIFY = 0x00004000,
CREATE = 0x00008000,
NO_APPCONTAINER_REDIRECTION = 0x00010000,
FORCE_APPCONTAINER_REDIRECTION = 0x00020000,
ALIAS_ONLY = 0x80000000
}
[DllImport("shell32.dll")]
public static extern HResult SHBindToObject(IntPtr psf, ItemIdListSafeHandle pidl, IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 3)] out object ppv);
[DllImport("shell32.dll")]
public static extern ItemIdListSafeHandle ILCombine(ItemIdListSafeHandle pIDLParent, ItemIdListSafeHandle pIDLChild);
[DllImport("shell32.dll")]
public static extern HResult SHCreateItemFromIDList(ItemIdListSafeHandle pidl, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 1)] out object ppv);
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
public interface IShellItem
{
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 2)]
object BindToHandler(IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid rbhid, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
IShellItem GetParent();
IntPtr GetDisplayName(SIGDN sigdnName);
SFGAO GetAttributes(SFGAO sfgaoMask);
int Compare(IShellItem psi, SICHINTF hint);
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7e9fb0d3-919f-4307-ab2e-9b1860310c93")]
public interface IShellItem2
{
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 2)]
object BindToHandler(IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid rbhid, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
IShellItem GetParent();
CoTaskStringSafeHandle GetDisplayName(SIGDN sigdnName);
SFGAO GetAttributes(SFGAO sfgaoMask);
int Compare(IShellItem psi, SICHINTF hint);
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 1)]
object GetPropertyStore(GPS flags, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 2)]
object GetPropertyStoreWithCreateObject(GPS flags, object punkCreateObject, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 3)]
object GetPropertyStoreForKeys([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] PROPERTYKEY[] rgKeys, uint cKeys, GPS flags, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 1)]
object GetPropertyDescriptionList([In] ref PROPERTYKEY keyType, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
void Update(IBindCtx pbc);
[PreserveSig]
HResult GetProperty([In] ref PROPERTYKEY key, PropVariantSafeHandle ppropvar);
[PreserveSig]
HResult GetCLSID([In] ref PROPERTYKEY key, out Guid pclsid);
[PreserveSig]
HResult GetFileTime([In] ref PROPERTYKEY key, out FILETIME pft);
[PreserveSig]
HResult GetInt32([In] ref PROPERTYKEY key, out int pi);
[PreserveSig]
HResult GetString([In] ref PROPERTYKEY key, out CoTaskStringSafeHandle ppsz);
[PreserveSig]
HResult GetUInt32([In] ref PROPERTYKEY key, out uint pui);
[PreserveSig]
HResult GetUInt64([In] ref PROPERTYKEY key, out ulong pull);
[PreserveSig]
HResult GetBool([In] ref PROPERTYKEY key, out bool pf);
}
public sealed class PropVariantSafeHandle : CoTaskMemSafeHandle
{
public PropVariantSafeHandle()
{
SetHandle(Marshal.AllocCoTaskMem(8 + (IntPtr.Size * 2)));
}
public override bool IsInvalid => handle == IntPtr.Zero;
protected override bool ReleaseHandle()
{
FreePropVariantArray(1, handle);
return base.ReleaseHandle();
}
[DllImport("ole32.dll")]
private static extern HResult FreePropVariantArray(uint cVariants, IntPtr rgvars);
[DllImport("propsys.dll")]
private static extern HResult PropVariantToStringVectorAlloc(PropVariantSafeHandle propvar, out CoTaskMemSafeHandle pprgsz, out uint pcElem);
public unsafe VarEnum VarType => *(VarEnum*)handle;
private unsafe struct CALPWSTR
{
public readonly uint cElems;
public readonly char** pElems;
}
public unsafe string[] ToStringVector()
{
if (IsInvalid) throw new InvalidOperationException("The handle is invalid.");
if (VarType == (VarEnum.VT_VECTOR | VarEnum.VT_LPWSTR))
{
var vector = (CALPWSTR*)(handle + 8);
var cElems = vector->cElems;
if (cElems == 0) return Array.Empty<string>();
var r = new string[cElems];
var currentElementPointer = *vector->pElems;
for (var i = 0; i < r.Length; i++)
{
r[i] = new string(currentElementPointer);
currentElementPointer++;
}
return r;
}
else if (PropVariantToStringVectorAlloc(this, out var buffer, out var cElems).Code != WinErrorCode.InvalidParameter)
{
using (buffer)
{
if (cElems == 0) return Array.Empty<string>();
var mustRelease = true;
buffer.DangerousAddRef(ref mustRelease);
try
{
var r = new string[cElems];
var currentElementPointer = (IntPtr*)buffer.DangerousGetHandle();
for (var i = 0; i < r.Length; i++)
{
r[i] = CoTaskStringSafeHandle.FromPointer(*currentElementPointer).ReadAndFree();
currentElementPointer++;
}
return r;
}
finally
{
if (mustRelease) buffer.DangerousRelease();
}
}
}
throw new NotImplementedException(VarType.ToString());
}
}
public struct PROPERTYKEY
{
public readonly Guid fmtid;
public readonly uint pid;
public PROPERTYKEY(Guid fmtid, uint pid)
{
this.fmtid = fmtid;
this.pid = pid;
}
}
public enum GPS
{
DEFAULT = 0x00000000,
HANDLERPROPERTIESONLY = 0x00000001,
READWRITE = 0x00000002,
TEMPORARY = 0x00000004,
FASTPROPERTIESONLY = 0x00000008,
OPENSLOWITEM = 0x00000010,
DELAYCREATION = 0x00000020,
BESTEFFORT = 0x00000040,
NO_OPLOCK = 0x00000080,
PREFERQUERYPROPERTIES = 0x00000100,
EXTRINSICPROPERTIES = 0x00000200,
EXTRINSICPROPERTIESONLY = 0x00000400,
VOLATILEPROPERTIES = 0x00000800,
VOLATILEPROPERTIESONLY = 0x00001000
}
[Flags]
public enum SIGDN : uint
{
NORMALDISPLAY = 0x00000000,
PARENTRELATIVEPARSING = 0x80018001,
DESKTOPABSOLUTEPARSING = 0x80028000,
PARENTRELATIVEEDITING = 0x80031001,
DESKTOPABSOLUTEEDITING = 0x8004c000,
FILESYSPATH = 0x80058000,
URL = 0x80068000,
PARENTRELATIVEFORADDRESSBAR = 0x8007c001,
PARENTRELATIVE = 0x80080001,
PARENTRELATIVEFORUI = 0x80094001
}
[Flags]
public enum SICHINTF : uint
{
SICHINT_DISPLAY = 0x00000000,
SICHINT_ALLFIELDS = 0x80000000,
SICHINT_CANONICAL = 0x10000000,
SICHINT_TEST_FILESYSPATH_IF_NOT_EQUAL = 0x20000000
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("bcc18b79-ba16-442f-80c4-8a59c30c463b")]
public interface IShellItemImageFactory
{
Gdi32.BitmapSafeHandle GetImage(POINT size, SIIGBF flags);
}
[Flags]
public enum SIIGBF
{
SIIGBF_RESIZETOFIT = 0x00000000,
SIIGBF_BIGGERSIZEOK = 0x00000001,
SIIGBF_MEMORYONLY = 0x00000002,
SIIGBF_ICONONLY = 0x00000004,
SIIGBF_THUMBNAILONLY = 0x00000008,
SIIGBF_INCACHEONLY = 0x00000010,
SIIGBF_CROPTOSQUARE = 0x00000020,
SIIGBF_WIDETHUMBNAILS = 0x00000040,
SIIGBF_ICONBACKGROUND = 0x00000080,
SIIGBF_SCALEUP = 0x00000100
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214E6-0000-0000-C000-000000000046")]
public interface IShellFolder
{
void ParseDisplayName(IntPtr hwnd, IBindCtx pbc, string pszDisplayName, IntPtr pchEaten, out ItemIdListSafeHandle ppidl, IntPtr pdwAttributes);
IEnumIDList EnumObjects(IntPtr hwnd, SHCONTF grfFlags);
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 2)]
object BindToObject(ItemIdListSafeHandle pidl, IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 2)]
object BindToStorage(ItemIdListSafeHandle pidl, IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
[PreserveSig]
HResult CompareIDs(IntPtr lParam, ItemIdListSafeHandle pidl1, ItemIdListSafeHandle pidl2);
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 1)]
object CreateViewObject(IntPtr hwndOwner, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
void GetAttributesOf(uint cidl, SafeHandleArray apidl, [In, Out] ref SFGAO rgfInOut);
[return: MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 3)]
object GetUIObjectOf(IntPtr hwndOwner, uint cidl, SafeHandleArray apidl, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, IntPtr rgfReserved);
IntPtr GetDisplayNameOf(ItemIdListSafeHandle pidl, SHGDN uFlags);
IntPtr SetNameOf(IntPtr hwnd, ItemIdListSafeHandle pidl, [MarshalAs(UnmanagedType.LPWStr)] string pszName, SHGDN uFlags);
}
[Flags]
public enum SHCONTF
{
CHECKING_FOR_CHILDREN = 0x0010,
FOLDERS = 0x0020,
NONFOLDERS = 0x0040,
INCLUDEHIDDEN = 0x0080,
INIT_ON_FIRST_NEXT = 0x0100,
NETPRINTERSRCH = 0x0200,
SHAREABLE = 0x0400,
STORAGE = 0x0800,
NAVIGATION_ENUM = 0x1000,
FASTITEMS = 0x2000,
FLATLIST = 0x4000,
ENABLE_ASYNC = 0x8000
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F2-0000-0000-C000-000000000046")]
public interface IEnumIDList
{
[PreserveSig]
HResult Next(uint celt, out ItemIdListSafeHandle rgelt, out uint pceltFetched);
[PreserveSig]
HResult Skip(uint celt);
void Reset();
IEnumIDList Clone();
}
[Flags]
public enum SFGAO : uint
{
CANCOPY = 0x1,
CANMOVE = 0x2,
CANLINK = 0x4,
STORAGE = 0x00000008,
CANRENAME = 0x00000010,
CANDELETE = 0x00000020,
HASPROPSHEET = 0x00000040,
DROPTARGET = 0x00000100,
CAPABILITYMASK = 0x00000177,
ENCRYPTED = 0x00002000,
ISSLOW = 0x00004000,
GHOSTED = 0x00008000,
LINK = 0x00010000,
SHARE = 0x00020000,
READONLY = 0x00040000,
HIDDEN = 0x00080000,
DISPLAYATTRMASK = 0x000FC000,
FILESYSANCESTOR = 0x10000000,
FOLDER = 0x20000000,
FILESYSTEM = 0x40000000,
HASSUBFOLDER = 0x80000000,
CONTENTSMASK = 0x80000000,
VALIDATE = 0x01000000,
REMOVABLE = 0x02000000,
COMPRESSED = 0x04000000,
BROWSABLE = 0x08000000,
NONENUMERATED = 0x00100000,
NEWCONTENT = 0x00200000,
CANMONIKER = 0x00400000,
HASSTORAGE = 0x00400000,
STREAM = 0x00400000,
STORAGEANCESTOR = 0x00800000,
STORAGECAPMASK = 0x70C50008,
PKEYSFGAOMASK = 0x81044000
}
[Flags]
public enum SHGDN
{
SHGDN_NORMAL = 0x0000,
SHGDN_INFOLDER = 0x0001,
SHGDN_FOREDITING = 0x1000,
SHGDN_FORADDRESSBAR = 0x4000,
SHGDN_FORPARSING = 0x8000
}
}
}
<file_sep>/src-csharp6/PrinterInfo.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Example.Native;
using static Example.Native.Shell32;
namespace Example
{
public sealed class PrinterInfo
{
public string IdName { get; }
public string DisplayName { get; }
public Bitmap Image { get; }
private PrinterInfo(string idName, string displayName, Bitmap image)
{
IdName = idName;
DisplayName = displayName;
Image = image;
}
public static IReadOnlyList<PrinterInfo> GetInstalledPrinterNamesAndImages(Size imageSize)
{
var r = new List<PrinterInfo>();
using (var folderIdList = CreateDevicesAndPrintersIDL())
{
var folder = GetShellFolder(folderIdList);
var enumerator = folder.EnumObjects(IntPtr.Zero, SHCONTF.NONFOLDERS);
for (;;)
{
// If you request more than are left, actualCount is 0, so we'll do one at a time.
ItemIdListSafeHandle relativeIdList;
uint actualCount;
var next = enumerator.Next(1, out relativeIdList, out actualCount);
next.ThrowIfError();
if (next == HResult.False || actualCount != 1) break; // printerChild is junk
using (relativeIdList)
using (var absoluteIdList = ILCombine(folderIdList, relativeIdList))
{
var shellItem = GetShellItem(absoluteIdList);
var idName = GetPrinterFriendlyNameIfPrinter(shellItem);
if (idName != null)
r.Add(new PrinterInfo(idName, GetDisplayName(shellItem), GetImage(shellItem, imageSize)));
}
}
}
return r;
}
private static ItemIdListSafeHandle CreateDevicesAndPrintersIDL()
{
ItemIdListSafeHandle controlPanelIdList;
SHGetKnownFolderIDList(FOLDERID.ControlPanelFolder, KF_FLAG.DEFAULT, IntPtr.Zero, out controlPanelIdList).ThrowIfError();
using (controlPanelIdList)
{
ItemIdListSafeHandle childDevicesAndPriversIdList;
GetShellFolder(controlPanelIdList).ParseDisplayName(IntPtr.Zero, null, "::{A8A91A66-3A7D-4424-8D24-04E180695C7A}", IntPtr.Zero, out childDevicesAndPriversIdList, IntPtr.Zero);
using (childDevicesAndPriversIdList)
return ILCombine(controlPanelIdList, childDevicesAndPriversIdList);
}
}
private static string GetPrinterFriendlyNameIfPrinter(IShellItem2 shellItem)
{
// Devices_PrimaryCategory returns "Printers" for printers and faxes on Windows 10 but "Printers and faxes" on Windows 7.
using (var categoryIds = new PropVariantSafeHandle())
{
shellItem.GetProperty(PKEY.Devices_CategoryIds, categoryIds).ThrowIfError();
if (!categoryIds.ToStringVector().Any(id => id.StartsWith("PrintFax", StringComparison.OrdinalIgnoreCase)))
return null;
}
// The canonical or "friendly name" needed to match the devmode
// https://blogs.msdn.microsoft.com/asklar/2009/10/21/getting-the-printer-friendly-name-from-the-device-center-shell-folder/
// PKEY_Devices_InterfacePaths doesn't seem to ever be found, but PKEY_Devices_FriendlyName works so...
CoTaskStringSafeHandle friendlyName;
shellItem.GetString(PKEY.Devices_FriendlyName, out friendlyName).ThrowIfError();
return friendlyName.ReadAndFree();
}
private static string GetDisplayName(IShellItem2 shellItem)
{
return shellItem.GetDisplayName(SIGDN.NORMALDISPLAY).ReadAndFree();
}
private static Bitmap GetImage(IShellItem2 shellItem, Size imageSize)
{
return ((IShellItemImageFactory)shellItem).GetImage(new POINT(imageSize.Width, imageSize.Height), SIIGBF.SIIGBF_BIGGERSIZEOK)
.CopyAndFree(); // Bitmap.FromHbitmap is useless with alpha, so make a copy
}
private static IShellFolder GetShellFolder(ItemIdListSafeHandle itemIdList)
{
object objShellFolder;
SHBindToObject(IntPtr.Zero, itemIdList, null, typeof(IShellFolder).GUID, out objShellFolder).ThrowIfError();
return (IShellFolder)objShellFolder;
}
private static IShellItem2 GetShellItem(ItemIdListSafeHandle itemIdList)
{
object objShellItem;
SHCreateItemFromIDList(itemIdList, typeof(IShellItem2).GUID, out objShellItem).ThrowIfError();
return (IShellItem2)objShellItem;
}
}
}
<file_sep>/src/ExampleForm.cs
using System.Windows.Forms;
namespace Example
{
public partial class ExampleForm : Form
{
public ExampleForm()
{
InitializeComponent();
foreach (var printerInfo in PrinterInfo.GetInstalledPrinterNamesAndImages(imageList1.ImageSize))
{
imageList1.Images.Add(printerInfo.Image);
listView1.Items.Add(new ListViewItem
{
Text = printerInfo.DisplayName,
ImageIndex = imageList1.Images.Count - 1,
Tag = printerInfo
});
}
}
}
}
<file_sep>/Readme.md
See [https://stackoverflow.com/questions/47274577/list-only-devices-shown-in-devices-and-printers-panel](https://stackoverflow.com/questions/47274577/list-only-devices-shown-in-devices-and-printers-panel).
| bd67a16deb49c00d5b7a437205ba47c38993238b | [
"Markdown",
"C#"
] | 9 | C# | jnm2/example-devices-and-printers | 24c621e2059c175cbf3397ea6a1e936059015e81 | 1acc9c240831ca8137abfb502d9e840af07964d3 |
refs/heads/master | <file_sep>package com.joshideepak.business;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.assertEquals;
//Run with Parameterized class
@RunWith(Parameterized.class)
public class LearningParameterizedTests {
Sum sum = new Sum();
//instance variable to get hold of parameters defined in method with @Parameter annotation
private Object[] input;
private Object expectedOutput;
//Constructor
public LearningParameterizedTests(Object[] input, Object expectedOutput) {
this.input = input;
this.expectedOutput = expectedOutput;
}
//Method with @Parameter annotation
@Parameterized.Parameters
public static Collection getParameters(){
Object[] input1 = {1,3};
Object[] input2 = {20,-10};
Object[][] arr = {
{input1,4},
{input2,10}
};
return Arrays.asList(arr);
}
@Test
public void testSumWithParameters(){
/*assertEquals(4, sum.sum(1,3));
assertEquals(10, sum.sum(20,-10));*/
int actual = sum.sum((Integer)input[0], (Integer)input[1]);
int expected = (Integer)expectedOutput;
assertEquals(expected,actual);
}
}
| 138fbf822bfd312d291435b4a65011d716372f28 | [
"Java"
] | 1 | Java | joshide/mockitocouse | adebd07faf62216253c6069b3ccb034aa8ed7ff7 | c8fbaa13e3d3e7a3f3cd447f388e80e0d3ca63a0 |
refs/heads/master | <repo_name>gibber-cc/gibberwocky.reference<file_sep>/script.js
/*
The MIT License (MIT)
Copyright (c) <2013> <<NAME>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
if ( typeof Object.create !== 'function' ) {
Object.create = function( obj ) {
function F() {}
F.prototype = obj;
return new F();
};
}
(function( $, window, document, undefined ) {
"use strict";
var Anchorific = {
init: function( options, elem ) {
var self = this;
self.elem = elem;
self.$elem = $( elem );
self.opt = $.extend( {}, this.opt, options );
self.headers = self.$elem.find( 'h1, h2, h3' );
// Fix bug #1
if ( self.headers.length !== 0 ) {
self.first = parseInt( self.headers.prop( 'nodeName' ).substring( 1 ), null );
}
if ( self.opt.spy ) {
self.spy();
}
if ( self.opt.top ) {
self.back();
}
},
opt: {
speed: 200, // speed of sliding back to top
top: '.top', // back to top button or link class
spy: true, // scroll spy
spyOffset: !0 // specify heading offset for spy scrolling
},
back: function() {
var self = this;
$( self.opt.top ).on( 'click', function( e ) {
e.preventDefault();
$( 'body, html' ).animate({
'scrollTop': 0
}, self.opt.speed );
});
},
top: function( that ) {
var self = this, top = self.opt.top, back;
if ( top !== false ) {
back = ( $( that ).scrollTop() > 200 ) ? $( top ).fadeIn() : $( top ).fadeOut();
}
},
spy: function() {
var self = this, prevAhref, currAhref, current, list, top, prevList;
$( window ).scroll( function( e ) {
// show links back to top
self.top( this );
// get all the header on top of the viewport
current = self.headers.map( function( e ) {
if ( $( this ).offset().top !==0 && ( $( this ).offset().top - $( window ).scrollTop() ) < self.opt.spyOffset ) {
return this;
}
});
// get only the latest header on the viewport
current = $( current ).last() || self.headers [0];
if ( current && current.length ) {
// get all li tag that contains href of # ( all the parents )
list = $( '#root-item li:has(a[href="#' + current.attr( 'id' ) + '"])' );
currAhref = $(list).find( 'a[href="#' + current.attr( 'id' ) + '"]' );
if (list.length !==0) {
if (prevList !== undefined) {
prevList.removeClass( 'active' );
}
list.addClass( 'active' );
prevList = list;
}
if (currAhref.length !==0) {
if (prevAhref !== undefined) {
prevAhref.removeClass( 'current' );
}
currAhref.addClass( 'current' );
prevAhref = currAhref;
}
}
});
}
};
$.fn.anchorific = function( options ) {
return this.each(function() {
if ( ! $.data( this, 'anchorific' ) ) {
var anchor = Object.create( Anchorific );
anchor.init( options, this );
$.data( this, 'anchorific', anchor );
}
});
};
})( jQuery, window, document );
// Flatdoc script
(function($) {
var $window = $(window);
var $document = $(document);
$document.on('flatdoc:ready', function() {
console.log( 'ANCHORIFIC?' )
$('.content').anchorific() ;
});
/*
* Sidebar stick.
*/
$(function() {
var $sidebar = $('.menubar');
var $header = $('.header');
$window
.on('resize.sidestick', function() {
$sidebar.removeClass('fixed');
$window.trigger('scroll.sidestick');
})
.on('scroll.sidestick', function() {
var scrollY = $window.scrollTop();
var elTop = $header.offset().top+$header.height();
$sidebar.toggleClass('fixed', (scrollY >= elTop));
})
.trigger('resize.sidestick');
});
/*
* Title card.
*/
$(function() {
var $card = $('.title-card');
if (!$card.length) return;
var $header = $('.header');
var headerHeight = $header.length ? $header.outerHeight() : 0;
$window
.on('resize.title-card', function() {
var windowWidth = $window.width();
if (windowWidth < 480) {
$card.css('height', '');
} else {
var height = $window.height();
$card.css('height', height - headerHeight);
}
})
.trigger('resize.title-card');
});
})(jQuery);
<file_sep>/docs.md
There are three different flavors of gibberwocky, with each targeting a different application. Although there are minor
application-specific differences between these versions the majority of the applications work fairly similarly.
The primary difference is the targets for sequencing. In gibberwocky.Live we primarily sequence `tracks`; in
gibberwocky.Max we primarily sequence `namespaces`; and in gibberwocky.MIDI we primarily sequence `channels`.
These differences aside, the API / syntax for sequencing and modulation is basically identical, with just a few different
keywords. There are also many common objects that are used identically across all three systems.
In this reference, we start by documenting the objects that are unique to each system, and then document ones
that are shared. Note that for almost every object in gibberwocky, each method can be *sequenced* by attaching a call
to `.seq()` to it. This is covered in the sequencing tutorials included in each envrionment.
#Gibberwocky.Live
In gibberwocky.live, the Live set is primarily manipulated through the global `tracks` and `returns` array, as well as the `master` object. Each track and return (as well as the master) has an array of `devices` that can be controlled; in turn each device has individual parameters that can be sequenced and modulated.
### Device
Devices are stored in the `devices` property of each individual track. They primarily represent softsynths and audio effects. In addition to a few convenience methods, devices in gibberwocky provide programmatic access to all of their parameters, so that they can all be sequecned and modulated.
```javascript
// toggle an effect on/off every measure
tracks[0].devices[1].toggle.seq( 1, 1 )
// turn the third device in the track's device chain off
tracks[0].devices[2].off()
// set value of parameter named Volume on device
tracks[0].devices[0].Volume( .5 )
```
#### Properties
* _parameters_: Object. Read-only. An array of all the parameters on a device. It is important to note that all parameters are also exposed on the device by name, which is an easier way to access them e.g. `tracks[0].devices[0][ 'Filter Cutoff' ]`. In practice the `parameters` array is not typically used.
#### Methods
* _on_: Turn the device on.
* _off_: Turn the device off.
* _toggle_: Toggle the on / off state of the device.
* _galumph_: Randomly pick a parameter of the device and assign a random number to it.
### Master
Provides access to the master track through the global `master` object and any effect devices placed in its device chain.
#### Properties
* _devices_: Array. Read-only. An array of all the devices in the track's device chain, *with the exception of the gibberwocky plugin itself*. See the [Device description](#Gibberwocky.Live-Device) for more information.
#### Methods
* _on_: Turn the device on.
* _volume_: Float. Set the volume of the track.
* _pan_: Float. Set the panning of the track. 0 = left, .5 = center, 1 = right.
* _start_: Starts any sequences running on the track that may have been previously halted.
* _stop_: Stops all sequences currently running on the track.
### Return
The global `returns` array provides access to the return objects, which are tracks that instrument tracks can route audio to using their `sends`.
#### Properties
* _sends_: Array. Read-only. An array of all the sends available for the retrun. For example, to ramp the value of send #1 over the course of two beats:
```javascript
returns[ 0 ].sends[ 1 ]( beats( 2 ) )
```
* _devices_: Array. Read-only. An array of all the devices in the return's device chain, *with the exception of the gibberwocky plugin itself*. See the [Device description](#Gibberwocky.Live-Device) for more information.
#### Methods
* _volume_: Float. Set the volume of the track.
* _pan_: Float. Set the panning of the track. 0 = left, .5 = center, 1 = right.
* _mute_: Integer. A value of `0` mutes the track, while `1` unmutes it.
* _solo_: Integer. A value of `1` solos the track, while `0` unsolos it. Note that soloing a track will *not* unsolo other tracks that have been previously soloed; you must do this manually.
* _start_: Starts any sequences running on the track that may have been previously halted.
* _stop_: Stops all sequences currently running on the track.
* _select_: Select the track in Live's GUI window and focus it.
### Track
All instrument tracks in a Live set are stored in the global `tracks` array. To access an individual track, you can either
use an array index or use the track's name. For example, assuming your first track was named `1-Impulse 606` you could access
it using `tracks[0]` or `tracks['1-Impulse 606']`.
Track objects in gibberwocky accept a variety of messages for triggering notes on any instrument on a track. They also provide access
to every control on every device, enabling you to set values and/or modulate them. However, in order to control an instrument or device
on a track, the track in question *must have a gibberwocky.midi plugin as the first device in the track's device chain*.
See tutorials #1, #2, and #5 for more information.
```javascript
// send notes to track 1
tracks[0].note.seq( 0, 1/4 )
// set the value of send #2 on track 2
tracks[1].sends[ 1 ]( .5 )
// modulate the Transpose property of an Impulse device on track 1
tracks[0].devices['Impulse 606']['Global Transpose']( lfo( .2 ) )
```
#### Properties
* _sends_: Array. Read-only. An array of all the sends available for the track. For example, to ramp the value of send #1 over the course of two beats:
```javascript
tracks[0].sends[0]( beats( 2 ) )
```
* _devices_: Array. Read-only. An array of all the devices in the track's device chain, *with the exception of the gibberwocky plugin itself*. See the [Device description](#Gibberwocky.Live-Device) for more information.
#### Methods
* _note_: Integer or String. Play a note using gibberwocky's built-in theory system. See the harmony tutorial for more information. Strings take the form of note name + octave, such as `c4` or `eb2`.
* _midinote_: Integer. Triggers a note using MIDI note numbers.
* _chord_: String or Array. Play a chord using gibberwocky's built-in theory system; see the harmony tutorial for more information. Strings take the form of note name + octave + quality + extension, for example `c4maj7` or `bb3dim9`. Alternatively an array of scale indices can be passed.
* _midichord_: Array. Trigger a list of MIDI note values simultaneously.
* _duration_: Integer (ms). Set the length of subsequent notes and chords that are played on this track in milliseconds.
* _velocity_: Integer {0,127}. Set the MIDI velocity value of subsequent cnotes and chords that are played on this track.
* _volume_: Float. Set the volume of the track.
* _pan_: Float. Set the panning of the track. 0 = left, .5 = center, 1 = right.
* _mute_: Integer. A value of `0` mutes the track, while `1` unmutes it.
* _solo_: Integer. A value of `1` solos the track, while `0` unsolos it. Note that soloing a track will *not* unsolo other tracks that have been previously soloed; you must do this manually.
* _start_: Starts any sequences running on the track that may have been previously halted.
* _stop_: Stops all sequences currently running on the track.
* _select_: Select the track in Live's GUI window and focus it.
#Gibberwocky.Max
Two global arrays and one constructor are the primary ways of interacting with gibberwocky.max. To use gibberwocky.max, you must first instantitate the gibberwocky.max object inside of your Max patch. This object has a single inlet, which is used to open the gibberwocky live-coding interface, and a number of outlets. The first outlet ouputs messages sent from objects created using the [Namespace](#gibberwocky.max-namespace) constructor. The remaining outlets output gen~ graphs and are accessed via the global `signals` array. Any Max object in a patch that containing a gibberwocky object and has a scripting name assinged to it can be accessed through the global `params` array.Finally, all Max for Live devices in a patch can be accessed via the global `devices` array.
The combination of these four entry points provides a great deal of flexibility when integrating gibberwocky with your Max patch. You can create complex routing schemes and send messages as needed, you can create complex signal graphs using gen~ expressions, and you can easily target any object with a scripting name and send it messages.
### Devices
There is a global `devices` array that provides access to all the Max for Live devices in any patcher containing a gibberwocky object. Note messages can be addressed directly to these devices without requiring any patching; individual properties of these devices can also be easily messaged.
```javascript
// The examples below assume that an instance of Analgue Drums is present in a Max
// patch, along with a gibberwocky object.
// quarter-note kick drums
devices['Analogue Drums'].midinote.seq( 36, 1/4 )
// sequence the 'kick-sweep' parameter of an analogue drums instance
devices['Analogue drums']['kick-sweep'].seq( [0, 16, 32, 64, 128], 1 )
```
### Namespace
The `namespace` constructor lets you create a messages that will be outputted from the first outlet of the gibberwocky.max object, with a prefix of your choice. For example, given:
```javascript
foo = namespace('foo')
foo.bar.seq( [0,1], 1 )
foo.baz.seq( -1, 1/2 )
```
... the following messages would be alternately sent out the first outlet of the gibberwocky Max object:
```
foo bar 0
foo baz -1
foo baz -1
foo bar 1
foo baz -1
foo baz -1
foo bar 0
...etc.
```
In effect, the sole argument to the `namespace` constructor determines the first word in the message it sends to Max, while the next property access adds another word to the message. `namespace('foo').bar( 1000 )` would send the message 'foo bar 1000' immediately.
In addition to using your own words for namespace routing, each namespace has several methods that are used to output MIDI noteon / noteoff messages.
#### Methods
* _note_: Integer or String. Play a note using gibberwocky's built-in theory system. See the harmony tutorial for more information. Strings take the form of note name + octave, such as `c4` or `eb2`.
* _midinote_: Integer. Triggers a note using MIDI note numbers.
* _chord_: String or Array. Play a chord using gibberwocky's built-in theory system; see the harmony tutorial for more information. Strings take the form of note name + octave + quality + extension, for example `c4maj7` or `bb3dim9`. Alternatively an array of scale indices can be passed.
* _midichord_: Array. Trigger a list of MIDI note values simultaneously.
* _duration_: Integer (ms). Set the length of subsequent notes and chords that are played on this track in milliseconds.
* _velocity_: Integer {0,127}. Set the MIDI velocity value of subsequent cnotes and chords that are played on this track.
### Signals
There is a global `signals` array that provides access to all the outlets in the gibberwocky.max object except for the first one (which is used for messaging). As the name suggests, these outlets are all used to output audio signals created using gen~ graphs, as opposed to irregular messages. gen~ graphs can also be sequenced; see the gen~ modulation tutorial for more information.
```javascript
// send a sine oscillator out the second outlet
signals[0]( cycle( .5 ) )
// send a sawtooth to the third outlet and sequence
// its frequency
mysin = phasor( 2 )
signals[1]( mysin )
mysin[0].seq( [.5,2,4,8], 1 )
```
### Params
Any object can be 'named' in Max/MSP by selecting it, opening up its info panel, and providing it with a scripting name. In addition, `receive` objects are named automatically when instantiated. gibberwocky provides a dictionary of these named parameters and `receive` objects, enabling easy messaging to them. For example, the gibberwocky.max help patch includes knobs with the scripting names 'White_Queen' and 'Red_Queen'. We can sequence messages to them as follows:
```javascript
params['White_Queen'].seq( [0,1,2,3], 1/4 )
params['Red_Queen'].seq( 1, Euclid(5,8) )
```
#Gibberwocky.MIDI
Programming in gibberwocky.midi is primarily done by sequencing MIDI `channel` objects, which are accessible through a global `channels` array.
### Channel
Each `channel` object represents a MIDI channel on the MIDI port selected for output (selection is made in gibberwocky's sidebar, under the MIDI tab).
```javascript
// play midinote 60 every quarter note
channels[0].midinote.seq( 60, 1/4 )
// change the velocity every measure
channels[0].velocity.seq( Rndi(0,127), 1 )
// sequence changes to CC 0
channels[0].cc0.seq( [0,32,64,127], 1/2 )
// assign a modulation graph to CC 1
channels[0].cc1( lfo( 4 ) )
```
#### Methods
* _note_: Integer or String. Play a note using gibberwocky's built-in theory system. See the harmony tutorial for more information. Strings take the form of note name + octave, such as `c4` or `eb2`.
* _midinote_: Integer. Triggers a note using MIDI note numbers, where 60 represents middle C.
* _chord_: String or Array. Play a chord using gibberwocky's built-in theory system; see the harmony tutorial for more information. Strings take the form of note name + octave + quality + extension, for example `c4maj7` or `bb3dim9`. Alternatively an array of scale indices can be passed.
* _midichord_: Array. Trigger a list of MIDI note values simultaneously.
* _duration_: Integer (ms). Set the length of subsequent notes and chords that are played on this channel in milliseconds.
* _velocity_: Integer {0,127}. Set the MIDI velocity value of subsequent notes and chords that are played on this channel.
* _start_: Starts any sequences running on the channel that may have been previously halted.
* _stop_: Stops all sequences currently running on the channel.
### Clock
Unlike the other gibberwocky systems, gibberwocky.midi can either be controlled by an external clock source or by its own internal clock. The global `Clock` object
represents this internal clock. It has a single property, `bpm`, that can be set to determine the tempo used by gibberwocky.
```javascript
channels[0].midinote.seq( 60, 1/4 )
Clock.bpm = 240 // change from 120 (default) to 240 bpm
Clock.bpm = 60 // change to 60 bpm
```
# Common Objects
###Arp
The Arp object is an arpeggiator providing a variety of controls. See the Arpeggio tutorial for detailed information.
Example:
```javascript
// 1,4,6, and 7th scale degrees,
// traveling up and down over 2 octaves
a = Arp( [0,3,5,6], 2, 'updown' )
// Live: play arpeggio on track 0 with 1/16th notes
tracks[0].note.seq( a, 1/16 )
// Max: play arpeggio through namespace 'foo' with 1/32 notes
namespace( 'foo' ).note.seq( a, 1/32 )
// c-diminished-7 chord in the third octave,
// traveling up over 4 octaves
a2 = Arp( 'c3dim7', 4, 'up' )
// MIDI: play argpeggio on MIDI channel 1 using Euclidean Rhythm
channels[0].note.seq( a2, Euclid( 5,8,1/16 ) )
```
#### Constructor
* _values_ : Array. The base values outputted by the sequencer. These values will be duplicated and transposed over a provided `octaves` argument.
* _octaves_ : Literal. The number of octaves to play the Arpeggio over.
* _pattern_ : String. The playback pattern used by the Arpeggiator.
#### Properties
* _pattern_ : String. Default value is 'up'. Controls the direction of notes. Possible values are 'up', 'down', 'updown' and 'updown2'. For 'updown2', the top and bottom notes of the arpeggio won't be repeated as it changes directions.
* _octaves_ : Number. Default is 1. The number of octaves that the arpeggio will span.
* _notes_: A Gibber Pattern object that holds all the notes the arpeggiator sequences, as determined by the chord passed to it, the `mult` property and the arpeggiation `pattern` used.
#### Methods
The Arp object uses a [Pattern](#common-objects-pattern) object as a mixin; this means that you can call most methods for
pattern manipulation (such as reverse, shuffle, rotate, transpose etc.) on an object created by the Arp
constructor. See [Pattern](#common-objects-pattern) for more information.
###Euclid
The Euclid constructor creates a Pattern object that outputs [Euclidean Rhythms](http://archive.bridgesmathart.org/2005/bridges2005-47.pdf).
The algorithm for these rhythms specifies that a certain number of pulses will occur over a certain number of time slots. For example, the
specification {5,8} will result in `x.xx.xx.` where an `x` represents a pulse and a `.` represents a rest. See the Euclidean tutorial for more
inforamation.
Example:
```javascript
// Live: play midinote 60 on track 0 with Euclidean rhythm
tracks[0].midinote.seq( 60, Euclid( 3,9 ) )
// Max: play notes through namespace 'foo' with Euclidean rhythm
namespace( 'foo' ).note.seq( [0,7], Euclid(5,12,1/8) )
p = Euclid(5,16)
// MIDI: play midinote 60 on MIDI channel 1 using Euclidean rhythm
channels[0].note.seq( 60, p )
// rotate Euclidean rhythm one position to the right each measure
p.rotate.seq( 1,1 )
```
#### Constructor
* _pulses_ : Int. The number of pulses (aka 'hits' or 'notes') in the generated pattern.
* _slots_ : Int. The number of slots in the pattern. If no third argument is passed, this also determines the duration
of each slot. For example, `Euclid(3,8)` means three pulses spread over eight slots, with each slot lasting an eighth note in duration.
* _slotDuration_ : Optional. Float. When passed to the constructor, this value determines the duration of each slot. For example,
`Euclid(3,8,1/16)` means that there will be three pulses distributed among eight slots, with each slot lasting a 1/16th note in duration.
#### Methods
The Euclid object uses a [Pattern](#common-objects-pattern) object as a mixin; this means that you can call most methods for
pattern manipulation (such as reverse, rotate etc.) on an object created by the Euclid.
constructor. See [Pattern](#common-objects-pattern) for more information.
###Pattern
Patterns are functions that output values from an internal list that is typically passed as an argument when the pattern is first created. These lists can be manipulated in various ways, influencing the output of the patterns. Alternatively, `filters` placed on the pattern (each filter is simply a function expected to return an array of values) can also change the output of the pattern dynamically, without affecting its underlying list.
Whenever you sequence any method or property in Gibber, Pattern(s) are created behind the scenes to handle sequencer output. All methods of the pattern object can be additionally sequenced; you can also sequence the `start`, `end`, and `stepSize` properties.
Example:
```javascript
// two patterns are created when notes are sequenced.
// The `values` pattern determines the output,
// while the `timings` pattern determines timing.
// In gibberwocky.MIDI:
channels[0].note.seq( [0,1,2,3], [1/4,1/8], 0 )
channels[0].note[0].values.reverse()
// a.note.values now equals [3,2,1,0]
channels[0].note[0].values.scale( 2 )
// a.note.values now equals [6,4,2,0]
// You can also pass Patterns directly to sequencing calls
// In gibberwocky.Max:
p = Pattern( 4,5,6,7 )
namespace('bar').note.seq( p, 1/4 )
// rotate the pattern -> 5,6,7,4 -> 6,7,4,5 -> 7,4,5,6 etc.
p.rotate.seq( 1,1 )
```
The gibberwocky Pattern tutorial has more information and examples of the Pattern object in use.
#### Constructor
* _values_ : ...arg list. The Pattern constructor takes a flexible number of arguments; each argument is added to an internal
list of possible output values for the pattern.
#### Properties
* _start_ : Int. The first index of the underlying list that will be used for output. For examples, if a pattern has values `[0,1,2]` and the `start` property is 1 then the pattern will output 1,2,1,2,1,2,1,2... skipping the 0-index item in the list.
* _end_ : Int. The last index of the underlying list that will be used for output. For examples, if a pattern has values `[0,1,2]` and the `end` property is 1 then the pattern will output 0,1,0,1,0,1... skipping the 2-index item in the list.
* _phase_ : Int. This is the next index in the underlying list that the pattern will output.
* _values_ : Array. The underlying list used by the pattern to determine output.
* _original_ : Array. A copy of the original values used to instantiate the pattern. These values can be used to restore the pattern to its original state after any transformations have been made using the `pattern.reset()` method.
* _storage_ : Array. The current permutation of a pattern can be stored at any time with a call to the `pattern.store()` method. Every stored pattern is placed in the `pattern.storage` array. The `pattern.switch` method can be used to switch between stored permutations.
* _stepSize_ : Float. Default 1. The amount that the phase is increased / decreased by each time the pattern outputs. For example, a `pattern.stepSize` of -1 means that the pattern will play in reverse. A `stepSize` of .5 means that each value in the list will be repeated before advancing to the next index.
* _integersOnly_ : Boolean. Default false. In certain cases (for example, scale degrees) we can ensure that any transformations applied to the pattern only result in integer values by setting this property to be true. For example, if a pattern has the original values of [2,3,4,5] and `pattern.scale(.5)` is applied, the values would normally then become [1,1.5,2,2.5]. By setting the value of `pattern.integersOnly` to be true, the values instead become [1,2,2,3] as the floats are rounded up.
#### Methods
* _reverse_: Reverse the current ordering of the pattern's `values` array.
* _range_( Array, or Int,Int ): Set both the start and end properties with a single method call. `pattern.range` can be called in two forms. In the first, both the start and the end values are passed as separate arguments. In the second, a single array is passed containing the start and the end values. This allows the range to be easily sequenced with calls to Rndi, for example: `pattern.range.seq( Rndi( 0,5,2 ), 1/2 )`. Note that if the value for start is lower than the value for end, this method will automatically switch the values.
* _set_( Array or list of values): Replace the current `pattern.values` array with new members.
* _repeat_( List of values ): Repeat certain values (not indices) in an array a certain number of times. When passing arguments, the even numbered arguments are the values you want to have repeated, while the odd values represent how many times each one should be played. For example, given the pattern [0,2,4] and the line `pattern.repeat( 0,2,4,2)` the pattern output would be 0,0,2,4,4 through one cycle (both 0 and 4 repeated ). This is particularly useful to line up odd time values; for example, if a pattern has 1/6 notes you can specify a repeat of 3 to make sure it lines up with a 1/2 note grid.
* _reset_: Return values to their original state at pattern creation.
* _store_: Push the current permutation of the pattern to the `pattern.storage` array.
* _switch_( Int ): Switch the values outputted by the pattern to a stored index in the `pattern.storage` array
* _transpose_ ( Number ): Add argument to all numerical values in the pattern. If a pattern consists of an array of chords, each member of each chord will be modified. For example [[0,2,4], [1,3,5]] transposed by 1 becomes [[1,3,5], [2,4,6]]
* _scale_ ( Number ): Multiply all numerical values in the pattern by argument. If a pattern consists of an array of chords, each member of each chord will be modified. For example [[0,2,4], [1,3,5]] scaled by 2 becomes [[0,4,8], [2,6,10]]
* _shuffle_: Randomize the order of values found in the `pattern.values` array.
* _flip_: Change the positions of pattern members so that the position of the highest member becomes the position of the lowest member, the position of the second highest becomes the position of the second lowest etc.
* _invert_: Similar to the technique from serialist compositions. Assume that the zero-index member of the pattern is our axis. Flip all other pattern members to the other side of the access. Thus, a member that is two higher than the zero-index member now becomes two lower.
* _rotate_( Int ): Shift the positions of all pattern members by the argument. For example, a pattern of `[0,1,2,3]` that is rotated by 1 becomes `[3,0,1,2]`.
###Scale
The `Scale` object is a global singleton that lets you control musical harmony in gibberwocky. By default, notes created using the `note` and `chord` methods in
gibberwocky use C minor, starting in the fourth octave, as their basis for generating notes. So, for example, a call to xxx.note( 0 ) will generate note `c4` while
a call to xxx.note(2) will generate `eb4`. The `Scale` object has `root` and `mode` functions that can be sequenced over time. You can also easily define your own modes; see the gibberwocky harmony tutorial for more information.
```javascript
// MIDI sequence:
channels[0].note( [0,1,2,3,4,5,6,7], 1/8 )
Scale.root.seq( ['c4','eb4'], 2 )
Scale.mode.seq( ['aeolian', 'lydian', 'locrian'], 2 )
```
#### Methods
* _root_: String. Change the base note for the current scale. The argument is the note name followed by an octave; for example: `c4`, `fb2`, or `g#1`.
* _mode_: String. Set the mode of the global scale. Possible values include: `major, minor, ionian, dorian, phrygian, lydian, mixolydian, aeolian, locrian, chromatic, wholeHalf, halfWhole`.
###Score
The Score object lets you define a timeline of events to be executed. Each event is a function that is called; these functions can play individual notes, create and start sequences playing, and even create other Score objects and start them. In addition to a list of events, time values are provided that tell the Score object how long to wait until it triggers its next event. These events and timestamps are listed in alternating order and passed to the Score constructor.
See the gibberwocky Score tutorial for more information.
```javascript
// MIDI score:
myscore = Score([
0, ()=> channels[0].midinote( 60 ),
1, ()=> channels[0].midinote( 72 ),
1, ()=> channels[0].midinote( 48 ),
1, ()=> channels[0].midinote.seq( [48,60,72], 1/8 ),
])
myscore.start()
```
#### Constructor
* _score_ : Array. The `Score` constructor accepts a single argument, an array storing timestamps associated with events. Each event is a function, while each timestamp provides an amount of time to wait before launching an event, relative to the last event that was played. In the above example, events are triggered on subsequent measures. The special value `Score.wait` can be passed as a timestamp to tell the score to stop playback until the `.next()` method is called on the score object.
#### Properties
* _wait_: Number. Read-only. A special value that can be included in scores to stop playback until the `.next()` method is called.
#### Methods
* _start_: If score playback is stopped, start it.
* _stop_: If the score is running, stop it.
* _next_: This method stops scores that have been halted after receiving a `Score.wait` message in their timeline.
* _combine_: ... argument list of Score objects. This method lets you combine multiple scores together. For example, if you use different scores to arrange different parts of a song, the combine method can be used to put them together in the end.
```javascript
verse = Score([ 1, channels[0].midinote.seq( 60, 1/8 ) ] )
chorus = Score([ 1, channels[0].midinote.seq( 72, 1/8 ) ] )
bridge = Score([ 1, channels[0].midinote.seq( 48, 1/8 ) ] )
song = Score.combine( verse, chorus, verse, chorus, bridge, chorus )
song.start()
```
###Seq
The Seq object is a standalone sequencer that can schedule calls to methods and properties on a target object. Alternatively, it can be used to quickly sequence repeated calls to an anonymous function. Scheduling occurs at audio-rate and may be modulated by audio sources.
Sequencers can work in one of two ways. In the first, anonymous functions can easily be scheduled to execute repeatedly. To create a `Seq` that accomplishes this, simply pass the constructor two values: the function to be executing and an array of time values to use for scheduling. In the second mode, four values are expected: a `values` array or literal, a `timings` array or literal, a `key` specifying the method to be sequenced, and the `target` object that owns the method.
```javascript
// MIDI: sequence four notes with alternating rhythms
a = Seq( [0,1,2,3], [1/4,1/2], 'note', channels[0] ).start()
// Live: sequence four notes with alternating rhythms
b = Seq( [0,1,2,3], [1/4,1/2], 'note', tracks[0] ).start()
// Max: sequence four notes with alternating rhythms
c = Seq( [0,1,2,3], [1/4,1/2], 'note', namespace('foo') ).start()
// ALL: sequence anonymous function that repeats every two measures
let count = 0
d = Seq( ()=> { Gibber.log( count++ ) }, 2 ).start()
```
#### Constructor
The Seq object has an overloaded constructor that accepts either four or two values. The two value option is only
for scheduling the repeated execution of functions.
* _values_ : Array, Literal, or Function. The value(s) outputted by the sequencer. This can either be an array of values, a single literal,
or a function that will be executed to provide a value... such functions should always return a valid value. Returning a value of `null` means
that the sequencer will not generate output for a particular execution.
* _timings_ : Array, Literal, or Function. The scheduling for the sequencer. This can either be an array of values, a single literal,
or a function that will be executed to provide a value.
* _key_ : String. The method or property that the sequencer will use on the `target` object.
* _target_ : Object. This determines the object that the sequencer will either execute a method on or set a property value on, depending on
the value of `key`.
* _values_ : Array or Function. Function(s) that will be called by the sequencer.
* _timings_ : Array, Literal, or Function. The scheduling for the sequencer. This can either be an array of values, a single literal,
or a function that will be executed to provide a value.
#### Properties
* _values_: Array, Function, or Number. The values used by the sequencer. This is a Gibber [Pattern][pattern] object.
* _timings_: Array, Function, or Number. The scheduling used by the sequencer. This is a Gibber [Pattern][pattern] object.
* _key_: String. The name of the method the sequencer calls on the `target` object.
* _target_ : Object. When the Seq object has a target, it can be used to change properties and call methods on that `target` object.
#### Methods
* _delay_: Delay the start of the sequencer by an argument value. For example, to start a pattern with a quarter note offset:
```javascript
a = Seq( ()=> Gibber.log('hi'), 1/2 )
.delay( 1/4 )
.start()
```
* _start_: If the sequencer is stopped, start it.
* _stop_: If the sequencer is running, stop it.
* _clear_: Stops sequencer and (hopefully) removes associated annotations.
###Steps
`Steps` creates a group of `Sequencer` objects; each sequencer is responsible for outputting a different MIDI note, with different velocities and rhythms as well. The `values` pattern of each sequencer in a `Steps` object can either be manipulated individually or they can all be manipulated as a group.
```javascript
// target = tracks[0] /* gibberwoky.live */
// target = devices[ 'drums' ] /* gibberwocky.max */
target = channels[0] /* gibberwocky.midi */
s = Steps({
36:'ffff', // quarter notes at max velocity, midinote 36
38:'.c.c', // alternating quarter notes, midinote 38
40:'9.69.69.', // eighth notes, midinote 40
42:'b9b3f', // fifth notes, midinote 42
}, target )
// rotate midinote 38 only by 1 position each measure
s[38].rotate.seq( 1,1 )
// reverse all patterns every 4 measures
s.reverse.seq( 1,4 )
```
The string argument for each MIDI note value accomplishes two tasks:
1. It defines the `timings` pattern for each sequence by counting the number of elements in the string. For example, given a string of 8 values, the `timings` pattern value will be an 1/8th note.
2. It defines a velocity for each note using hexadecimal notation, where `1` represents the lowest velocity and `f` represents the highest. A value of `.` means no note is played for that pattern position.
In the example code given above, the sequencer created for MIDI note 36 would be equivalent to:
```js
target.midinote.seq( 36, 1/4 )
target.velocity.seq( 127, 1/4 )
```
#### Methods
Note that all the methods below can be applied to any `Steps` object or to an individual sequence in a `Steps` objects.
* _reset_: Return all patterns to their original values, prior to any transformations.
* _reverse_: Reverse all the `values` patterns held by sequencers belonging to the `Steps` object.
* _rotate_: Rotate all the `values` patterns held by sequencers belonging to the `Steps` object by a given amount
* _shuffle_: Randomize the order of all values in each pattern.
# Common Functions
### rndi
Returns a single random integer.
#### Arguments
* _min_ : Integer, default = 0. The lower bound of the range of random numbers that can be generated.
* _max_ : Integer, default = 1. The upper bound of the range of random numbers that can be generated.
### rndf
Returns a single random floating point number.
#### Arguments
* _min_ : Float, default = 0. The lower bound of the range of random numbers that can be generated.
* _max_ : Float, default = 1. The upper bound of the range of random numbers that can be generated.
### Rndi
Returns a function that, when executed, returns a random integer within a set of bounds. This is useful
for sequencing, so that every time the function is called a new random value is generated.
#### Arguments
* _min_ : Integer, default = 0. The lower bound of the range of random numbers that can be generated.
* _max_ : Integer, default = 1. The upper bound of the range of random numbers that can be generated.
* _size_: Integer, default = 1. The number of random integers to generate. If `size` is set to more than one the generated function will return an array.
### Rndf
Returns a function that, when executed, returns a random float within a set of bounds. This is useful
for sequencing, so that every time the function is called a new random value is generated.
#### Arguments
* _min_ : Float, default = 0. The lower bound of the range of random numbers that can be generated.
* _max_ : Float, default = 1. The upper bound of the range of random numbers that can be generated.
* _size_: Float, default = 1. The number of random integers to generate. If `size` is set to more than one the generated function will return an array.
### log
Logs a message to the console in the gibberwocky sidebar, in addition to the developer's console of the browser.
#### Arguments
* _text_ : String or Number. The text that should be printed to gibberwocky's console.
# Modulation
## Arithmetic
### add
**args** *ugens* or *numbers*
```js
// midi
channels[0].cc0( add( .5, mul( cycle(.25), .5 ) ) )
// live
tracks[0].devices[0]['Volume']( add( .5, mul( cycle(.25), .5 ) ) )
// max
signals[0]( add( .5, mul( cycle(.25), .5 ) )
```
### sub
**args** *ugens* or *numbers*
```js
// midi
channels[0].cc0( sub( .5, mul( cycle(.25), .5 ) ) )
// live
tracks[0].devices[0]['Volume']( sub( .5, mul( cycle(.25), .5 ) ) )
// max
signals[0]( sub( .5, mul( cycle(.25), .5 ) )
```
### mul
**a,b** *ugen* or *number* Ugens or numbers to be multiplied.
Multiples two number or ugens together.
```js
// midi
channels[0].cc0( sub( .5, mul( cycle(.25), .5 ) ) )
// live
tracks[0].devices[0]['Volume']( sub( .5, mul( cycle(.25), .5 ) ) )
// max
signals[0]( sub( .5, mul( cycle(.25), .5 ) )
```
### div
**a,b** *ugen* or *number* Ugens or numbers.
Divides ugen or number *a* by ugen or number *b*.
```js
// midi
channels[0].cc0( sub( .5, div( cycle(.25), 2 ) ) )
// live
tracks[0].devices[0]['Volume']( sub( .5, div( cycle(.25), 2 ) ) )
// max
signals[0]( sub( .5, div( cycle(.25), 2 ) )
```
### mod
**a,b** *ugen* or *number* Ugens or numbers.
Divides ugen or number *a* by ugen or number *b* and returns the remainder.
```js
// midi
channels[0].cc0( mod( beats(2), lfo( .5 ) ) )
// live
tracks[0].devices[0]['Volume']( mod( beats(2), lfo( .5 ) ) )
// max
signals[0]( mod( beats(2), lfo( .5 ) ) )
```
## Buffer
### cycle
**frequency** *ugen* or *number* Ugen or number.
Outputs a sine wave via wavetable lookup / interpolation.
```javascript
// midi
channels[0].cc0( cycle(4 )
// live
tracks[0].devices[0]['Volume']( cycle(4) )
// max
signals[0]( cycle(4) )
```
### data
**dataArray** *Array* A pre-defined array of numbers to use.
**dataLength** *integer* The length of a new underlying array to be created.
Data objects serve as containers for storing numbers; these numbers can be read using calls to `peek()` and the data object can be written to using calls to `poke()`. The constructor can be called with two different argumensts. If a *dataArray* is passed as the first argument, this array becomes the data object's underlying data source. If a *dataLength* integer is passed, a Float32Array is created using the provided length.
```js
// create a sliding, interpolated frequency signal running between four values
d = data( [440,880,220,1320] )
p = peek( d, phasor(.1) )
c = cycle( p ) // feed sine osc frequency with signal
// midi
channels[0].cc0( c )
// live
tracks[0].devices[0]['Volume']( c )
// max
signals[0]( c )
```
### peek
**dataUgen** *data* A `data` ugen to read values from.
**index** *integer* The index to be read.
Peek reads from an input data object. It can index the data object using on of two *modes*.
```js
// create a sliding, interpolated frequency signal running between four values
d = data( [440,880,220,1320] )
p = peek( d, phasor(.1) )
c = cycle( p ) // feed sine osc frequency with signal
// midi
channels[0].cc0( c )
// live
tracks[0].devices[0]['Volume']( c )
// max
signals[0]( c )
```
## Envelopes
### t60
**a** *ugen* Number of samples to fade 1 by 60 dB.
`t60` provides a multiplier that, when applied to a signal every sample, fades it by 60db (at which point it is effectively inaudible). Although the example below shows `t60` in action, it would actually be much more efficient to calculate t60 once since the time used (88200) is static.
```javascript
lastsample = ssd(1)
// update fade with previous output * t60
// we could also use: Math.exp( -6.907755278921 / 88200 ) instead of t60( 88200 )
fade = mul( lastsample.out, t60( 88200 ) )
// record current value of fade
lastsample.in( fade )
play( mul( lastsample.out, cycle( 330 ) ) )
```
## Filter
### dcblock
**a** *ugen* Signal.
`dcblock()` remove DC offset from an input signal using a one-pole high-pass filter.
### slide
**a** *ugen* Signal.
**time** *integer* Length of slide in samples.
`slide()` is a logarithmically scaled low-pass filter to smooth discontinuities between values. It is especially useful to make continuous transitions from discrete events; for example, sliding from one note frequency to the next. The second argument to `slide` determines the length of transitions. A value of 100 means that a transition in a signal will take 100x longer than normal; a value of 1 causes the filter to have no effect.
## Integrator
### accum
**increment** *ugen* or *number* (default = 1) The amount to increase the accumulator's internal value by on each sample
**reset** *ugen* or *number* (default = 0) When `reset` has a value of 1, the accumulator will reset its internal value to 0.
`accum()` is used to increment a stored value between a provided range that defaults to {0,1}. If the accumulator values passes its maximum, it wraps. `accum()` is very similar to the `counter` ugen, but is slightly more efficient.
### counter
**increment** *ugen* or *number* (default = 1) The amount to increase the counter's internal value by on each sample
**min** *ugen* or *number* (default = 0) The minimum value of the accumulator
**max** *ugen* or *number* (default = 1) The maximum value of the accumulator
**reset** *ugen* or *number* (default = 0) When `reset` has a value of 1, the counter will reset its internal value to 0.
`counter()` is used to increment a stored value between a provided range that defaults to {0,1}. If the counter's interval value passes either range boundary, it is wrapped. `counter()` is very similar to the `accum` ugen, but is slightly less efficient.
## Logic
### not
**a** *ugen* or *number* Input signal
An input of 0 returns 1 while all other values return 0.
```javascript
y = x !== 0 ? 0 : 1
```
### bool
**a** *ugen* or *number* Input signal
Converts signals to either 0 or 1. If the input signal does not equal 0 then output is 1; if input == 0 then output 0. Roughly equivalent to the following pseudocode:
```javascript
y = x !== 0 ? 1 : 0
```
### and
**a** *ugen* or *number* Input signal
**b** *ugen* or *number* Input signal
Returns 1 if both inputs do not equal 0.
## Numeric
### round
**a** *ugen* or *number*
Rounds input up or down to nearest integer.
### floor
**a** *ugen* or *number*
Rounds input down to nearest integer by performing a bitwise or with 0.
### ceil
**a** *ugen* or *number*
Rounds input up to nearest integer.
### sign
**a** *ugen* or *number*
Returns 1 for positive input and -1 for negative input. Zero returns itself.
## Trigonometry
### sin
**a** *ugen* or *number*
Calculates the sine of the input (interepreted as radians).
### cos
**a** *ugen* or *number*
Calculates the cosine of the input (interpreted as radians).
### tan
**a** *ugen* or *number*
Calculates the tangent of the input (interpreted as radians).
### asin
**a** *ugen* or *number*
Calculates the arcsine of the input in radians using Javascript's `Math.asin()` function
### acos
**a** *ugen* or *number*
Calculates the arccosine of the input in radians.
### atan
**a** *ugen* or *number*
Calculates the arctangent of the input in radians.
## Comparison
### eq
**a** *ugen* or *number* Input signal
**b** *ugen* or *number* Input signal
Returns 1 if two inputs are equal, otherwise returns 0.
### max
**a,b** *ugen* or *number* Ugens or numbers.
Returns whichever value is greater.
### min
**a,b** *ugen* or *number* Ugens or numbers.
Returns whichever value is lesser.
### gt
**a,b** *ugen* or *number* Ugens or numbers.
Returns 1 if `a` is greater than `b`, otherwise returns 0
### lt
**a,b** *ugen* or *number* Ugens or numbers.
Returns 1 if `a` is less than `b`, otherwise returns 0
### gtp
**a,b** *ugen* or *number* Ugens or numbers.
Returns `a` if `a` is greater than `b`, otherwise returns 0
### ltp
**a,b** *ugen* or *number* Ugens or numbers.
Returns `a` if `a` is less than `b`, otherwise returns 0
## Miscellaneous
### fade
**length of fade** *number* The number of beats the fade should last
**start of fade** *number* The value the fade begins at
**end of fade** *number* The value the fade ends at.
The `fade` ugen is basically a ramp that travels from one value to another over a given number of beats. This ugen is unique to gibberwocky in that after the fade completes the ugen disconnects itself and replaces itself with its final value. For example, given the following:
```js
channels[0].cc0( fade( 32, 0, 127 ) )
```
1. The fade would begin with an initial value of 0
2. Over 32 beats the fade would rise to 127
3. After 32 beats the fade would remove itself, and effectively call `channels[0].cc0( 127 )`
### lfo
**frequency** *ugen* or *number* The frequency of the sine oscillator used in the lfo.
**amp** *ugen* or *number* The scalar applied to the lfo output.
**center** *ugen* or *number* The center value the lfo fluctuates around; alternatively named bias.
The `lfo` is a composite of `cycle`, `add`, and `mul` ugens. Unlike most other modulation sources, with the `lfo` ugen
you directly sequence the `frequency`, `amp`, and `center` properties instead of referring to them using index values.
```js
// gibberwocky.max
eleffoh = lfo( 2, 100, 200 )
devices['drums']['kick-tuning']( eleffoh )
eleffoh.frequency.seq( [.5,1,2,4,8], 1/2 )
```
###beats
**length** *number* The number of beats to ramp over.
`beats()` creates a upward ramp that cycles every `n` beats, where each beat is typically a quarter note. You can easily create a downward ramp by combining `beats` with `sub`:
```js
// gibberwocky.live
tracks[0].devices[0]['Global Transpose']( sub( 1, beats(4) ) )
```
## Range
### clamp
**a** *ugen* or *number* Input signal to clamp.
**min** *ugen* or *number* Signal or number that sets minimum of range to clamp input to.
**max** *ugen* or *number* Signal or number that sets maximum of range to clamp input to.
Clamp constricts an input `a` to a particular range. If input `a` exceeds the maximum, the maximum is returned. If input `b` is less than the minimum, the minimum is returned.
### fold
**a** *ugen* or *number* : Input signal to fold.
**min** *ugen* or *number* : Signal or number that sets minimum of range to fold input to.
**max** *ugen* or *number* : Signal or number that sets maximum of range to fold input to.
Fold constricts an input `a` to a particular range. Given a range of {0,1} and an input signal of {.8,.9,1,1.1,1.2}, fold will return {.8,.9,1,.9,.8}.
### wrap
**a** *ugen* or *number* : Input signal to fold.
**min** *ugen* or *number* : Signal or number that sets minimum of range to fold input to.
**max** *ugen* or *number* : Signal or number that sets maximum of range to fold input to.
Wrap constricts an input `a` to a particular range. Given a range of {0,1} and an input signal of {.8,.9,1,1.1,1.2}, fold will return {.8,.9,0,.1,.2}.
## Routing
### gate
**control** *ugen or number* Selects the output index that the input signal travels through.
**input** *integer* Signal that is passed through one of various outlets.
`gate()` routes signal from one of its outputs according to an input *control* signal, which defines an index for output. The various outputs are all stored in the `mygate.outputs` array. The code example to the right shows a signal alternating between left and right channels using the `gate` ugen.
### selector
**control** *ugen or number* Determines which input signal is passed to the ugen's output.
**...inputs** *ugens or numbers* After the `control` input, an arbitrary number of inputs can be passed to the selector constructor.
Selector is basically the same as `switch()` but allows you to have an arbitrary number of inputs to choose between.
### switch
**control** *ugen or number* When `control` === 1, output `a`; else output `b`.
**a** *ugen or number* Signal that is available to output.
**b** *ugen or number* Signal that is available to ouput.
A control input determines which of two additional inputs is passed to the output. Note that in the genish.js playground this is globally referred to as the `ternary` ugen, so as not to conflict with JavaScript's `switch` control structure.
## Waveforms
### cycle
**a** *ugen* or *number* Frequency.
Cycle creates a sine oscillator running at a provided frequency. The oscillator runs via an interpolated wavetable lookup.
### noise
Noise outputs a pseudo-random signal between {0,1}.
### phasor
**frequency** *ugen* or *number* Frequency.
A phasor accumulates phase, as determined by its frequency, and wraps between 0 and 1. This creates a sawtooth wave, but with a dc offset of 1 (no negative numbers). If a range of {-1,1} is needed you can use an `accum()` object with the increment `1/gen.samplerate * frequency` and the desired min/max properties.
### train
**frequency** *ugen* or *number* Frequency.
**pulsewidth** *ugen* or *number* (default .5) Pulsewidth. A pulsewidth of .5 means the oscillator will spend 50% of its time outputting 1 and 50% of its time outputting 0. A pulsewidth of .2 means the oscillator spends 20% of its time outputting 1 and 80% outputting 0.
`train()` creates a pulse train driven by an input frequency signal and input pulsewidth signal. The pulse train is created using the genish expression displayed at right.
```javascript
pulseTrain = lt( accum( div( inputFrequency, sampleRate ) ), inputPulsewidth )
```
<file_sep>/README.markdown
# gibberwocky.reference #
This repo contains the reference guide for [gibberwocky](http://gibberwocky.cc), a trio of live-coding environments targeting Ableton Live, Max/MSP/Jitter, and general MIDI output. The reference use [Flatdoc](http://ricostacruz.com/flatdoc/).
View the [docs.md](https://github.com/charlieroberts/gibberwocky.reference/blob/master/docs.md) file to browse the reference from within Github. | 0a9b3e37d2658966d336bca17a99be7267ce5754 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | gibber-cc/gibberwocky.reference | 537c4337cc515c9a9f593272550e918cc770ad6d | 3ab4d091476941159d6531ee1383ddcd6fea4228 |
refs/heads/master | <repo_name>Anthonyntilelli/map-state-to-props-lab-online-web-sp-000<file_sep>/src/components/Users.js
import React, { PureComponent } from 'react';
import { connect } from 'react-redux'
// add any needed imports here
class Users extends PureComponent {
render() {
return (
<div>
{this.props.usrNum}
<ul>
{this.props.usrs.map((usr, index) => <li>{usr.username}</li>)}
</ul>
</div>
)
}
}
export default connect((state) => { return {usrs: state.users, usrNum: state.users.length} })(Users) | e8160cbdae4b5d8960b214986e45fd93ade563cf | [
"JavaScript"
] | 1 | JavaScript | Anthonyntilelli/map-state-to-props-lab-online-web-sp-000 | 3f832ac92e6e5b5ce8c0910b4911252efc07d027 | 3327703f950533f731536166e050be203954cb00 |
refs/heads/master | <repo_name>Beatso/PackUpdater<file_sep>/server/src/index.ts
// imports
import AdmZip from 'adm-zip'
import { config } from 'dotenv'
import { Dropbox } from 'dropbox'
import express from 'express'
import { File, IncomingForm } from 'formidable'
import { existsSync } from 'fs'
import { v4 } from 'uuid'
// dotenv setup
config()
// dropbox setup
const dbx = new Dropbox({
accessToken: process.env.DROPBOXTOKEN,
})
// express setup
const app = express()
app.use(express.json()) // to support JSON-encoded bodies
app.get('/ping', (req, res) => res.send('pong'))
app.all('*', (req, res, next) => {
res.header('access-control-allow-origin', '*')
next()
})
// handle file update requests
app.post('/update_pack_with_file', (req, res, next) => {
const form = new IncomingForm()
form.parse(req, async (err, fields, files) => {
if (err) {
next(err)
return
}
const { path, name } = files.packFile as File
res.send(
await generateResponseFromFilePath(
path,
name,
Number(fields.newPackFormat)
)
)
})
})
// handle url update requests
app.post('/update_pack_with_url', async (req, res) => {
// ...
})
const generateResponseFromFilePath = async (
path: string,
name: string | null,
newPackFormat: number
) => {
try {
// check pack zip file exists
if (!existsSync(path))
return JSON.stringify({
success: false,
reason: 'Pack zip file did not exist.',
})
// check pack_format is valid
if (
isNaN(newPackFormat) || // must be a number
!Number.isInteger(newPackFormat) || // must be an integer
newPackFormat < 1 || // must be at least 1
newPackFormat > 99 // dont allow pack formats greater than 99
)
return JSON.stringify({
success: false,
reason: 'Provided pack_format was not a valid number.',
})
const zip = new AdmZip(path)
// check pack.mcmeta exists
if (
!zip
.getEntries()
.some(zipEntry => zipEntry.entryName === 'pack.mcmeta')
)
return JSON.stringify({
success: false,
reason: 'Pack had no pack.mcmeta. Make sure it was a valid resource or data pack and is zipped correctly.',
})
const oldPackMcmetaContents = zip.readAsText('pack.mcmeta')
// check pack.mcmeta is valid
try {
const oldContentsParsed = JSON.parse(oldPackMcmetaContents) // will throw an error if invalid json syntax
if (typeof oldContentsParsed?.pack?.pack_format !== 'number')
// throw error if not valid pack.mcmeta
throw 'not valid'
} catch {
return JSON.stringify({
success: false,
reason: 'pack.mcmeta was not valid.',
})
}
// update pack.mcmeta
let packMcmetaContentsParsed = JSON.parse(oldPackMcmetaContents)
packMcmetaContentsParsed.pack.pack_format = newPackFormat
const newPackMcmetaContents = Buffer.from(
JSON.stringify(packMcmetaContentsParsed, null, 2)
)
zip.updateFile('pack.mcmeta', newPackMcmetaContents)
// get new zip contents as buffer
const newZipContents = zip.toBuffer()
// upload zip to dropbox
const dropboxFilePath = `/${v4()}/updated-${name}`
await dbx.filesUpload({
path: dropboxFilePath,
contents: newZipContents,
})
// get direct download link
const shareLink = (
await dbx.filesGetTemporaryLink({ path: dropboxFilePath })
).result.link
// return direct download link
return JSON.stringify({
success: true,
download: shareLink,
})
} catch (error) {
// catch any other errors
console.error(error)
return JSON.stringify({
success: false,
reason: 'An unknown error occurred while trying to update your pack.',
})
}
}
// listen express server
const port = process.env.PORT || 3100
app.listen(port, () => console.log(`Server running on port ${port}`))
<file_sep>/README.md
# [Pack Updater](https://packupdater.netlify.app/)
A tool to update the pack_format of Minecraft resource packs and data packs
## Technologies Used
- [TypeScript](https://www.typescriptlang.org/) on the frontend and backend
- [React](https://reactjs.org/) with [create-react-app](https://create-react-app.dev/) to power the frontend
- [Node.js](https://nodejs.org/) to power the backend
- [Express](https://expressjs.com/) to manage the webserver
- [Bulma](https://bulma.io/) as a CSS framework on the site
- [Font Awesome](https://fontawesome.com/) for icons on the site
## Contributions
| Contribution | Accepted |
| ---------------------------- | -------- |
| Issues (bug reports) | ✅ |
| Issues (feature requests) | ✅ |
| Pull Requests (bug fixes) | ✅ |
| Pull Requests (new features) | ❌ |
## Running
Dependencies:
- [Node.js](https://nodejs.org/en/) v14 LTS
- [npm](https://docs.npmjs.com/)
### To run client development server
```sh
cd client
npm install
npm start
```
Open http://localhost:3000/ in a browser.
### To build client for production
```sh
cd client
npm install
npm run build
cd build
```
### To run server development
```sh
cd server
npm install
npm run watch
```
Will be served on http://localhost:3100/.
### To build server for production
```sh
cd server
npm install
npm run build
```
| 19a8d4ce0061c7e0bce3c51042358c5fc297b968 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | Beatso/PackUpdater | bf99bf1c7c9e08453a082ef3eab37b1c7b32c198 | f94a583366966ee83fd382a31a44829135aefc7b |
refs/heads/master | <file_sep>using System.Collections;
using UnityEngine;
public class GameManager : MonoBehaviour {
public static bool GameIsOver;
public Transform canvas;
void Start()
{
GameIsOver = false;
}
// Update is called once per frame
void Update () {
if (GameIsOver)
return;
if (PlayerStats.Lives <= 0)
{
EndGame();
}
}
void EndGame()
{
GameIsOver = true;
canvas.gameObject.SetActive(true);
Time.timeScale = 0;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExitMenu : MonoBehaviour {
public void OnMouseDown()
{
transform.localScale *= 0.9F;
Application.Quit();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Music : MonoBehaviour {
public AudioSource AudioSource;
public AudioClip AudioClip1;
public AudioClip AudioClip2;
void Start()
{
AudioSource.clip = AudioClip1;
AudioSource.Play();
}
void Update()
{
if (PlayerStats.Lives <= 0)
{
AudioSource.clip = AudioClip2;
AudioSource.Play();
}
}
}<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class WaveSpawner : MonoBehaviour {
public Transform capungPrefab;
public Transform kepikPrefab;
public Transform semutPrefab;
public Transform kelabangPrefab;
public Transform spawnPoint;
public float timeBetweenWaves = 8f;
private float countdown = 3f;
public Text waveCountdownText;
private int waveIndex = 0;
public int boss = 0;
public int x = 0;
void Update()
{
if (countdown <= 0f)
{
StartCoroutine(SpawnWave());
//SpawnWave();
countdown = timeBetweenWaves;
}
countdown -= Time.deltaTime;
countdown = Mathf.Clamp(countdown, 0f, Mathf.Infinity);
waveCountdownText.text = string.Format("{0:00.00}", countdown);
}
IEnumerator SpawnWave()
{
waveIndex++;
PlayerStats.Rounds++;
for (int i = 0; i < waveIndex; i++)
{
for (int j = 0; j < 2; j++)
{
SpawnKepik();
yield return new WaitForSeconds(0.3f);
}
}
for (int i = 0; i < waveIndex; i++)
{
SpawnCapung();
yield return new WaitForSeconds(0.5f);
}
if (waveIndex % 2 == 0)
{
x++;
for (int i = 0; i < x; i++)
{
SpawnSemut();
yield return new WaitForSeconds(0.7f);
}
}
if (waveIndex % 5 == 0)
{
boss++;
for (int i = 0; i < boss; i++) {
SpawnKelabang();
yield return new WaitForSeconds(1f);
}
}
}
void SpawnCapung()
{
Instantiate(capungPrefab);
}
void SpawnKepik()
{
Instantiate(kepikPrefab);
}
void SpawnSemut()
{
Instantiate(semutPrefab);
}
void SpawnKelabang()
{
Instantiate(kelabangPrefab);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QuitMenu : MonoBehaviour {
public void OnMouseDown()
{
transform.localScale *= 0.9F;
Application.LoadLevel(0);
Time.timeScale = 1;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class RestartMenu : MonoBehaviour {
public void OnMouseDown ()
{
transform.localScale *= 0.9F;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Time.timeScale = 1;
}
}
| 43bfd09f798236e3e6180827f362bc6dd5486712 | [
"C#"
] | 6 | C# | unitydstate/Insect_Defender | ec9c71d9a985caa6b8b09aa402012891fbabe511 | b8682b231f2a2ee09e605d2bc629d3dad3b83846 |
refs/heads/master | <file_sep>module Distribution
module Binomial
module GSL_
class << self
# Returns a `Proc`object that yields a random integer `k` <= `n`
# which is binomially distributed with mean np and variance np(1-p)
# This method only wraps GSL's binomial dist. generator
#
# @param n [Fixnum] the total number of trials
# @param prob [Float] probabilty of success in a single independant trial
# @param seed [Fixnum, nil] Value to initialize the generator with.
# The seed is always taken modulo 100000007. If omitted the value is
# remainder of `Random.new_seed` mod 100000007
#
# @return [Proc] a proc that generates a binomially distributed integer
# `k` <= `n` when called
def rng(n, prob, seed = nil)
# Method found at:
# SciRuby/rb-gsl/ext/gsl_native/randist.c#L1782
# and
# SciRuby/rb-gsl/ext/gsl_native/randist.c#L713
seed = Random.new_seed if seed.nil?
seed = seed.modulo 100_000_007
r = GSL::Rng.alloc(GSL::Rng::MT19937, seed)
# This is an undocumented function in rb-gsl
# see gsl_ran_binomial(3) in GSL manual and best guess using
# http://blackwinter.github.io/rb-gsl/rdoc/rng_rdoc.html
-> { r.binomial(prob, n) }
end
# Returns the probability mass function for a binomial variate
# having `k` successes out of `n` trials, with each success having
# probability `prob`.
#
# @param k [Fixnum, Bignum] number of successful trials
# @param n [Fixnum, Bignum] total number of trials
# @param prob [Float] probabilty of success in a single independant trial
#
# @return [Float] the probability mass for Binom(k, n, prob)
def pdf(k, n, prob)
GSL::Ran.binomial_pdf(k, prob, n)
end
# Returns the cumulative distribution function for a binomial variate
# having `k` successes out of `n` trials, with each success having
# probability `prob`.
#
# @param k [Fixnum, Bignum] number of successful trials
# @param n [Fixnum, Bignum] total number of trials
# @param prob [Float] probabilty of success in a single independant trial
#
# @return [Float] the probability mass for Binom(k, n, prob)
def cdf(k, n, prob)
GSL::Cdf.binomial_P(k, prob, n)
end
# Returns the inverse-CDF or the quantile given the probability `prob`,
# the total number of trials `n` and the number of successes `k`
# Note: Implementation taken from corresponding ruby code.
#
# @paran qn [Float] the cumulative function value to be inverted
# @param n [Fixnum, Bignum] total number of trials
# @param prob [Float] probabilty of success in a single independant trial
#
# @return [Fixnum, Bignum] the integer quantile `k` given cumulative value
# @raise RangeError if qn is from outside of the closed interval [0, 1]
def quantile(qn, n, prob)
fail RangeError, 'cdf value(qn) must be from [0, 1]. '\
"Cannot find quantile for qn=#{qn}" if qn > 1 || qn < 0
ac = 0
0.upto(n).each do |i|
ac += pdf(i, n, prob)
return i if qn <= ac
end
end
alias_method :p_value, :quantile
end
end
end
end
<file_sep>module Distribution
module Binomial
module Ruby_
class << self
# Returns a `Proc`object that yields a random integer `k` <= `n`
# which is binomially distributed with mean np and variance np(1-p)
# This method uses a variant of Luc Devroye's
# "Second Waiting Time Method" on page 522 of his text
# "Non-Uniform Random Variate Generation." for np < 1e-3
# For all other values it finds the sum of n IID bernoulli variates
#
# @param n [Fixnum] the total number of trials
# @param prob [Float] probabilty of success in a single independant trial
# @param seed [Fixnum, nil] Value to initialize the generator with.
# The seed is always taken modulo 100000007. If omitted the value is
# remainder of `Random.new_seed` mod 100000007
#
# @return [Proc] a proc that generates a binomially distributed integer
# `k` <= `n` when called
def rng(n, prob, seed = nil)
seed = Random.new_seed if seed.nil?
seed = seed.modulo 100_000_007
prng = Random.new(seed)
np = n * prob
k = 0
if np < 1e-3
# An efficient technique that works for small values of `n` * `prob`
# http://stackoverflow.com/q/23561551/
log_q = Math.log(1 - prob)
sum = 0
return -> {
while true
sum += Math.log(rand) / (n - k)
next k if sum < log_q
k += 1
end
}
else
# First principles algorithm
# Slow and a candidate for replacement
bernoulli_generator = lambda do |rng, p|
if rng.rand > p
0
else
1
end
end
# A binomial variate is the sum of n IID bernoulli trials
-> {
Array.new(n) {
bernoulli_generator.call(prng, prob)
}.reduce(:+)
}
end
end
# Returns the probability mass function for a binomial variate
# having `k` successes out of `n` trials, with each success having
# probability `prob`.
#
# @param k [Fixnum, Bignum] number of successful trials
# @param n [Fixnum, Bignum] total number of trials
# @param prob [Float] probabilty of success in a single independant trial
#
# @return [Float] the probability mass for Binom(k, n, prob)
def pdf(k, n, prob)
fail 'k > n' if k > n
Math.binomial_coefficient(n, k) * (prob**k) * (1 - prob)**(n - k)
end
alias_method :exact_pdf, :pdf
# TODO: Use exact_regularized_beta for
# small values and regularized_beta for bigger ones.
def cdf(k, n, prob)
# (0..x.floor).inject(0) {|ac,i| ac+pdf(i,n,pr)}
Math.regularized_beta(1 - prob, n - k, k + 1)
end
# Returns the exact CDF value by summing up all preceding values
#
# @param k [Fixnum, Bignum] number of successful trials
# @param n [Fixnum, Bignum] total number of trials
# @param prob [Float] probabilty of success in a single independant trial
def exact_cdf(k, n, prob)
out = (0..k).inject(0) { |ac, i| ac + pdf(i, n, prob) }
out = 1 if out > 1.0
out
end
# Returns the inverse-CDF or the quantile given the probability `prob`,
# the total number of trials `n` and the number of successes `k`
# Note: This is a candidate for future updates
#
# @paran qn [Float] the cumulative function value to be inverted
# @param n [Fixnum, Bignum] total number of trials
# @param prob [Float] probabilty of success in a single independant trial
#
# @return [Fixnum, Bignum] the integer quantile `k` given cumulative value
#
# @raise RangeError if qn is from outside of the closed interval [0, 1]
def quantile(qn, n, pr)
fail RangeError, 'cdf value(qn) must be from [0, 1]. '\
"Cannot find quantile for qn=#{qn}" if qn > 1 || qn < 0
ac = 0
(0..n).each do |i|
ac += pdf(i, n, pr)
return i if qn <= ac
end
end
alias_method :p_value, :quantile
end
end
end
end
| 39c023947d1de11b9d6e162382f036fffcc0c2dc | [
"Ruby"
] | 2 | Ruby | reactive-relations/distribution | 42cd0724d06ecc2e9f087c326c87c8262556b996 | 3ad04376baaf34dda8b65ab2c5451690a3b077a1 |
refs/heads/master | <repo_name>chuliam/SynchronizationForSZIIT<file_sep>/models/dbModel/newsInfo.go
package DbModel
import (
"time"
)
type NewsInfo struct{
NewsId int `gorm:"primary_key;AUTO_INCREMENT;column:NewsId"`
NewsTitle string `gorm:"type:text;column:NewsTitle"`
NewsOldLink string `gorm:"type:text;column:NewsOldLink"`
NewsLink string `gorm:"type:text;column:NewsLink"`
NewsPushDate string `gorm:"column:NewsPushDate"`
NewsType string `gorm:"column:NewsType"`
NewsContent string `gorm:"type:text;column:NewsContent"`
NewsSyncTime time.Time `gorm:"column:NewsSyncTime"`
}
func (NewsInfo) TableName() string {
return "NewsInfo"
}
<file_sep>/models/dbModel/logs.go
package DbModel
import "time"
type Logs struct {
LogId int `gorm:"primary_key;AUTO_INCREMENT;column:LogId"`
LogOperationalType string `gorm:"column:LogOperationalType"`
LogContent string `gorm:"type:text;column:LogContent"`
LogError string `gorm:"type:text;column:LogError"`
LogTime time.Time `gorm:"column:LogTime"`
}
func (Logs) TableName() string {
return "Logs"
}
<file_sep>/models/newsModel.go
package Models
type NewsModel struct{
Brief string `json:"Brief"`
Link string `json:"link"`
PushDate string `json:"pushDate"`
Title string `json:"title"`
Type string `json:"Type"`
}
<file_sep>/common/dbHelper.go
package Common
import "github.com/jinzhu/gorm"
import (
_ "github.com/go-sql-driver/mysql"
"SynchronizationForSZIIT/settings"
)
type DbHelper struct {
}
func (DbHelper)DbInit() (*gorm.DB) {
db, err := gorm.Open("mysql", settings.MysqlConn)
db.LogMode(settings.MysqlDbLogMode)//设置orm的日志模式
if err != nil {
return nil
}
return db
}
<file_sep>/app.go
package main
import (
"SynchronizationForSZIIT/common"
"SynchronizationForSZIIT/models"
"SynchronizationForSZIIT/models/dbModel"
"encoding/json"
"net/url"
"regexp"
"time"
"SynchronizationForSZIIT/settings"
"strconv"
)
func main() {
settings.LoadConfig()
println(settings.AppName+" started.")
ticker := time.NewTicker(time.Minute * time.Duration(settings.SyncTimes))
for _ = range ticker.C {
SyncNews()
}
}
func SyncNews() {
dh := Common.DbHelper{}
db := dh.DbInit()
db.AutoMigrate(&DbModel.Logs{}, &DbModel.NewsInfo{})
httpHelper := Common.HttpHelper{}
data, err := httpHelper.HttpGet(settings.NewsServerUri, nil)
if err != nil {
var l DbModel.Logs
l.LogOperationalType = "连接校内新闻服务器"
l.LogContent = "连接校内新闻服务器出错"
l.LogError = err.Error()
l.LogTime = time.Now()
db.Create(&l)
}
var news []Models.NewsModel
json.Unmarshal(data, &news)
var count int =0
if len(news) > 1 {
for _, j := range news {
var hasNI DbModel.NewsInfo
db.Where(DbModel.NewsInfo{NewsOldLink:j.Link, NewsPushDate:j.PushDate}).First(&hasNI)
if hasNI.NewsTitle == "" {
count++
realLink, _ := url.QueryUnescape(j.Link)
realLink = realLink[55:]
println(realLink)
newsContent, err := httpHelper.HttpGetDownload(realLink)
if err != nil {
var l DbModel.Logs
l.LogOperationalType = "连接校内新闻服务器"
l.LogContent = "连接校内新闻服务器获取内容出错"
l.LogError = err.Error()
l.LogTime = time.Now()
db.Create(&l)
}
pattern := `<div class="contentText" id="content">([\s\S]*?)</div>`
reg := regexp.MustCompile(pattern)
regContent := reg.FindAllString(newsContent, -1)
if len(regContent) < 1 {
var l DbModel.Logs
l.LogOperationalType = "正则匹配"
l.LogContent = "正则匹配新闻内容出错"
l.LogError = err.Error()
l.LogTime = time.Now()
db.Create(&l)
}
var ni DbModel.NewsInfo
ni.NewsContent = regContent[0]
ni.NewsLink = realLink
ni.NewsOldLink = j.Link
ni.NewsPushDate = j.PushDate
ni.NewsSyncTime = time.Now()
ni.NewsType = j.Type
ni.NewsTitle = j.Title
db.Create(&ni)
var l DbModel.Logs
l.LogOperationalType = "同步完成"
l.LogContent = "同步了【" + ni.NewsTitle + "】[" + strconv.Itoa(ni.NewsId) + "]"
l.LogError = ""
l.LogTime = time.Now()
db.Create(&l)
}
}
if count == 0 {
var l DbModel.Logs
l.LogOperationalType = "同步完成"
l.LogContent = "没有需要同步的通知"
l.LogError = "同步完成时间"+time.Now().String()
l.LogTime = time.Now()
db.Create(&l)
}
}
db.Close()
}
<file_sep>/settings/conf.go
package settings
import (
"github.com/Unknwon/goconfig"
"os"
)
const (
DEFAULT_SECTION = "APP"
MYSQL_SECTION = "MYSQL"
AppConfPath = "./conf/app.ini"
)
var (
Cfg *goconfig.ConfigFile
)
var (
AppName string
MysqlConn string
MysqlDbLogMode bool
NewsServerUri string
SyncTimes int
)
func LoadConfig() *goconfig.ConfigFile {
var err error
Cfg, err = goconfig.LoadConfigFile(AppConfPath)
if err != nil {
println("Fail to load configuration file: " + err.Error())
os.Exit(2)
}
AppName=Cfg.MustValue(DEFAULT_SECTION,"APP_NAME")
mysqlconn := Cfg.MustValue(MYSQL_SECTION, "DB_USER")
mysqlconn += ":" + Cfg.MustValue(MYSQL_SECTION, "DB_PWD")
mysqlconn += "@tcp(" + Cfg.MustValue(MYSQL_SECTION, "DB_HOST") + ":"+Cfg.MustValue(MYSQL_SECTION, "DB_PORT")+")/"
mysqlconn += Cfg.MustValue(MYSQL_SECTION, "DB_NAME") + "?charset="
mysqlconn += Cfg.MustValue(MYSQL_SECTION, "DB_CHARSET") + "&parseTime="
mysqlconn += Cfg.MustValue(MYSQL_SECTION, "DB_PARSETIME") + "&loc=" + Cfg.MustValue(MYSQL_SECTION, "DB_LOC")
MysqlDbLogMode = Cfg.MustBool(MYSQL_SECTION, "DB_LOG_MODE")
MysqlConn = mysqlconn
NewsServerUri=Cfg.MustValue(DEFAULT_SECTION,"NEWS_SERVER_URI")
SyncTimes=Cfg.MustInt(DEFAULT_SECTION,"SYNC_TIMES")
return Cfg
}
<file_sep>/README.md
Welcome to SynchronizationForSZIIT!
===================
Hey! I'm a tool, using the go language, used to synchronize the news of the Shenzhen Institute of Information Technology, and grab the news content to the specified database.
----------
How to use?
-------------
> 1, go get github.com/chuliam/SynchronizationForSZIIT
> 2, modify the app.in, replace the MySQL connection string into your connection string
> 3, the database with the name of the new connection string in MySQL
> 4, modify the app.go, set the need to synchronize the time, the initial set to 6 minutes
> 5, go build
> 6, run
----------
Pre condition
-------------------
>MySQL database
>Go environment
>vendor go tool
----------
<file_sep>/bin/linux_64/conf/app.ini
[APP]
APP_NAME=SynchronizationForSZIIT
NEWS_SERVER_URI=http://oa.sziit.edu.cn/seeyon/noticeServlet?loginName=test
SYNC_TIMES=1
[MYSQL]
DB_HOST=localhost
DB_NAME=SynchronizationForSZIIT
DB_USER=root
DB_PWD=
DB_PORT=3306
DB_CHARSET=utf8
DB_PARSETIME=true
DB_LOC=Local
DB_LOG_MODE=true
<file_sep>/common/httpHelper.go
package Common
import (
"io/ioutil"
"strconv"
"net/http"
"net/url"
"strings"
)
type HttpHelper struct {
}
func (HttpHelper)HttpGet(u string, m map[string]string) ([]byte, error) {
client := &http.Client{}
var postData = url.Values{}
for k, v := range m {
postData.Set(k, v)
}
queryString := postData.Encode()
inWord := strings.LastIndexAny(u, "?")
if inWord >= 0 {
if inWord == len(u) - 1 {
u += queryString
} else {
u += "&" + queryString
}
} else {
if queryString != "" {
u += "?" + queryString
}
}
request, err := http.NewRequest("GET", u, nil)
response, err := client.Do(request)
if err != nil {
return nil, err
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode!=200{
return []byte(strconv.Itoa(response.StatusCode)),nil
}
return contents, nil
}
}
func (HttpHelper)HttpGetDownload(u string) (string, error) {
client := &http.Client{}
request, err := http.NewRequest("GET", u, nil)
response, err := client.Do(request)
if err != nil {
return "", err
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
return string(contents), nil
}
} | 5a039dba0513b3f8c8b876cefebfc35e1d2075f2 | [
"Markdown",
"Go",
"INI"
] | 9 | Go | chuliam/SynchronizationForSZIIT | 30163790d4fa492aa4ebe900a288989ad1c7b6ba | f996cfb47826a4c02af46c7676c8f298e7f9252e |
refs/heads/master | <repo_name>Revature-1704-Java/reverse-string-quiz-JFenstermacher<file_sep>/src/main/java/quiz/ReverseString.java
package quiz;
public class ReverseString {
public String reverse(String input) {
if (input == null) return ""; //If null string, return empty one
StringBuilder sb = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--)
sb.append(input.charAt(i)); //Build the string in reverse
return sb.toString();
}
} | 694db79d368a082bf7f7501879e9a4932b673f89 | [
"Java"
] | 1 | Java | Revature-1704-Java/reverse-string-quiz-JFenstermacher | 20c1bcaa2bf1f89f7d3214255b314e227da1286d | 3230655f1ebec1039e13559e0cafae675ee96694 |
refs/heads/master | <repo_name>Serbroda/pong-port-2011<file_sep>/core/src/de/morphbit/pong/util/Utils.java
package de.morphbit.pong.util;
import java.util.Random;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import de.morphbit.pong.domain.Dimension;
public final class Utils {
private static GlyphLayout layout = new GlyphLayout();
private Utils() {
}
public static int random(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static float random(float min, float max) {
return (float)random((int)min, (int)max);
}
public static Dimension getFontBounds(BitmapFont font, String text) {
layout.setText(font, text);
return new Dimension(layout.width, layout.height);
}
public static Texture createRectImage(int width, int height, Color color) {
Pixmap ballPixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
ballPixmap.setColor(color);
ballPixmap.fill();
return new Texture(ballPixmap);
}
}
<file_sep>/core/src/de/morphbit/pong/manager/GameScreenManager.java
package de.morphbit.pong.manager;
import java.util.HashMap;
import de.morphbit.pong.PongGame;
import de.morphbit.pong.screen.AbstractScreen;
import de.morphbit.pong.screen.GameScreen;
import de.morphbit.pong.screen.LoadingScreen;
import de.morphbit.pong.screen.MenuScreen;
public class GameScreenManager {
public enum STATE {
MAIN_MENU,
PLAY,
SETTINGS;
}
private final PongGame game;
private HashMap<STATE, AbstractScreen> screens;
public GameScreenManager(PongGame game) {
this.game = game;
initScreens();
setScreen(STATE.PLAY);
}
private void initScreens() {
screens = new HashMap<STATE, AbstractScreen>();
screens.put(STATE.MAIN_MENU, new MenuScreen(game));
screens.put(STATE.PLAY, new GameScreen(game));
screens.put(STATE.SETTINGS, new LoadingScreen(game));
}
public void setScreen(STATE nextScreen) {
game.setScreen(screens.get(nextScreen));
}
public void dispose() {
for(AbstractScreen screen : screens.values()) {
if(screen != null) {
screen.dispose();
}
}
}
}
<file_sep>/core/src/de/morphbit/pong/domain/Powerup.java
package de.morphbit.pong.domain;
import java.util.Random;
import com.badlogic.gdx.graphics.Texture;
import de.morphbit.pong.util.Utils;
public class Powerup extends GameElement {
private static final long serialVersionUID = 1L;
private boolean shouldShow;
private boolean destroyed;
private float fieldWidth;
private float fieldHeight;
public Powerup(Texture texture, float fieldWidth, float fieldHeight) {
super(texture, 0, 0);
this.fieldWidth = fieldWidth;
this.fieldHeight = fieldHeight;
setShouldShow(false);
setRandomPosition();
}
public boolean isShouldShow() {
return shouldShow;
}
public void setShouldShow(boolean shouldShow) {
this.shouldShow = shouldShow;
}
public boolean isDestroyed() {
return destroyed;
}
public void setDestroyed(boolean destroy) {
this.destroyed = destroy;
if(destroy) {
setShouldShow(false);
}
}
public void calcShouldShow() {
if(!isDestroyed() && !isShouldShow()) {
Random rnd = new Random();
int rnd1 = rnd.nextInt(2147483647);
if(rnd1 < 2500000) {
this.shouldShow = true;
}
}
}
public void setRandomPosition() {
float effectiveXStart = 0 + 80;
float effectiveXEnd = this.fieldWidth - 80;
float effectiveYStart = 0 + 80;
float effectiveYEnd = this.fieldHeight - 80;
this.x = Utils.random(effectiveXStart, effectiveXEnd);
this.y = Utils.random(effectiveYStart, effectiveYEnd);
}
}
<file_sep>/core/src/de/morphbit/pong/accessor/TableAccessor.java
package de.morphbit.pong.accessor;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import aurelienribon.tweenengine.TweenAccessor;
public class TableAccessor implements TweenAccessor<Table> {
public static final int POS_XY = 1;
public static final int SCALE = 2;
public static final int COLOR = 3;
@Override
public int getValues(Table target, int tweenType, float[] returnValues) {
switch (tweenType) {
case POS_XY:
returnValues[0] = target.getX();
returnValues[1] = target.getY();
return 2;
case SCALE:
returnValues[0] = target.getScaleX();
return 1;
case COLOR:
returnValues[0] = target.getColor().r;
returnValues[1] = target.getColor().g;
returnValues[2] = target.getColor().b;
returnValues[3] = target.getColor().a;
return 4;
default:
assert false;
return -1;
}
}
@Override
public void setValues(Table target, int tweenType, float[] newValues) {
switch (tweenType) {
case POS_XY:
target.setPosition(newValues[0], newValues[1]);
break;
case SCALE:
target.setScale(newValues[0]);
break;
case COLOR:
Color c = target.getColor();
c.set(newValues[0], newValues[1], newValues[2], newValues[3]);
target.setColor(c);
break;
default:
assert false;
}
}
}
<file_sep>/ios/robovm.properties
app.version=1.0
app.id=de.morphbit.pong
app.mainclass=de.morphbit.pong.IOSLauncher
app.executable=IOSLauncher
app.build=1
app.name=pong-port
<file_sep>/core/src/de/morphbit/pong/domain/Player.java
package de.morphbit.pong.domain;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
public class Player extends Paddle {
private static final long serialVersionUID = 435953026373161762L;
public Player(Texture texture, float x, float y, float fieldHeight) {
super(texture, x, y, fieldHeight);
}
@Override
public void move() {
float mousePosToWorld = -(Gdx.input.getY() - fieldHeight + height / 2);
float mouseLerp = y + (mousePosToWorld - y) * .3f;
if (mouseLerp > (fieldHeight - height)) {
mouseLerp = fieldHeight - height;
} else if (mouseLerp < 0f) {
mouseLerp = 0f;
}
setY(mouseLerp);
}
}
| 3328a746fb34c727bf4f451219e7c0ac88a862cf | [
"Java",
"INI"
] | 6 | Java | Serbroda/pong-port-2011 | 8c09fb584230f933b4b06d46334c3adbea49ad2d | dc3ca17222f1ecee573a0771749b3cdf72206245 |
refs/heads/master | <repo_name>dpoarch/SafeOregon-Android<file_sep>/.gradle/2.4/taskArtifacts/cache.properties
#Fri Feb 19 13:22:40 IST 2016
<file_sep>/app/src/main/java/com/safeoregon/app/FormActivity.java
package com.safeoregon.app;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.etech.util.AppUtils;
import com.etech.util.AsyncTaskCompleteListener;
import com.etech.util.AutoCompleteAdapter;
import com.etech.util.Constant;
import com.etech.util.CustomAlertDialogue;
import com.etech.util.ETechAsyncTask;
import com.etech.util.JSONFileReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
public class FormActivity extends Activity implements AsyncTaskCompleteListener<String> {
private static final int REQUEST_CODE_VIDEO_TRIM = 1001;
ViewFlipper formFlipper;
TextView txtHeaderTitle;
AutoCompleteTextView autotxtSchoolName;
Button btnHeaderNext;
Button btnDate;
EditText editBullyperson;
EditText editPerson;
EditText editDescription;
EditText editName;
EditText editPhNo;
Spinner spIncident;
private Uri fileUri;
int currentDay;
int currentMonth;
int currentYear;
// VideoView videoPreview;
String value_stateID = null;
String value_schoolID = null;
String value_schoolName = null;
String value_incidentLocation = null;
int incidentValue = 0;
String value_incidentTime = "0001";
String value_description = null;
String value_reporterType = null;
String user_lang = "en";
ArrayList<String> schoolNameList = null;
ArrayList<String> schoolIDList = null;
ArrayList<String> schoolCityList = null;
ArrayList<String> incidentValueList = null;
ArrayList<String> reporterValueList = null;
ArrayList<String> stateIDList = null;
private Drawable x;
private boolean dateDialogflag = true;
JSONFileReader jsonFileReader;
String APP_NAME = "Sprigeo Sample";
String btn_diaOK = "Ok";
String btn_diaCancel = "Cancel";
private final int REQUEST_CAMERA = 101;
private final int SELECT_IMAGE_FILE = 102;
private final int SELECT_VIDEO_FILE = 103;
private final int VIDEO_CAPTURE = 104;
private final int CROP_PIC = 105;
/*
new Spinner added
*/
Spinner spIncidentAdult;
Spinner spSituation;
String[] incidentAdultList;
String[] situationList;
ArrayList<String> alistIncidentAdult;
ArrayList<String> alistSituationList;
String valueIncidentAdult = null;
String valueSituation = null;
EditText edtWho;
ImageView imgUpload;
Button btnUpload;
String strWhois;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
formFlipper = (ViewFlipper) findViewById(R.id.formFlipper);
btnHeaderNext = (Button) findViewById(R.id.btnHeaderNext);
txtHeaderTitle = (TextView) findViewById(R.id.header_title);
autotxtSchoolName = (AutoCompleteTextView) findViewById(R.id.autoschoolName);
btnDate = (Button) findViewById(R.id.btnDateTime);
editBullyperson = (EditText) findViewById(R.id.editTextBully);
editPerson = (EditText) findViewById(R.id.editTextPerson);
editDescription = (EditText) findViewById(R.id.editTextDescription);
editName = (EditText) findViewById(R.id.editTextName);
editPhNo = (EditText) findViewById(R.id.editTextPhNo);
edtWho = (EditText) findViewById(R.id.edtWho);
imgUpload = (ImageView) findViewById(R.id.imgUpload);
btnUpload = (Button) findViewById(R.id.btnUpload);
btnUpload.setOnClickListener(uploadClickListener);
Spinner spStateName = (Spinner) findViewById(R.id.spStateName);
Spinner spTime = (Spinner) findViewById(R.id.spTime);
Spinner spReporterType = (Spinner) findViewById(R.id.spReporterType);
spIncident = (Spinner) findViewById(R.id.spIncident);
spIncidentAdult = (Spinner) findViewById(R.id.spIncidentAdult);
incidentAdultList = getResources().getStringArray(R.array.incidentAdult);
alistIncidentAdult = new ArrayList<String>(Arrays.asList(incidentAdultList));
spSituation = (Spinner) findViewById(R.id.spSituation);
situationList = getResources().getStringArray(R.array.sutuationList);
alistSituationList = new ArrayList<String>(Arrays.asList(situationList));
// SharedPreferences user_pref = getSharedPreferences(Constant.USER_PREF, MODE_PRIVATE);
// user_lang = user_pref.getString(Constant.selLang, "en");
Log.i("USER LANGUAGE", user_lang);
jsonFileReader = new JSONFileReader(loadJSONFromAsset());
if (jsonFileReader.jsonObj == null) {
Log.d("StateList", "sonFileReader.jsonObj ");
jsonFileReader = new JSONFileReader(loadJSONFromAsset());
}
if (jsonFileReader.jsonObj != null) {
setLabelNames();
ArrayList<ArrayList<String>> stateList = jsonFileReader.getstateList();
Log.d("StateList", "List : " + stateList);
stateIDList = stateList.get(0);
ArrayAdapter<String> stateNameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stateList.get(1) /*Constant.stateNames*/);
stateNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spStateName.setPrompt(jsonFileReader.getLabelObj("LBL_SEL_STATE"));
spStateName.setAdapter(stateNameAdapter);
Constant.Time[0] = jsonFileReader.getLabelObj("LBL_SELECT");
ArrayAdapter<String> timeAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Constant.Time);
timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spTime.setPrompt(jsonFileReader.getLabelObj("LBL_SEL_TIME"));
spTime.setAdapter(timeAdapter);
ArrayAdapter<String> reporterAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, jsonFileReader.getReporterList());
reporterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spReporterType.setPrompt(jsonFileReader.getLabelObj("LBL_TYPE"));
spReporterType.setAdapter(reporterAdapter);
reporterValueList = jsonFileReader.getReporterListValue();
ArrayAdapter<String> incidentAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, jsonFileReader.getincidentList());
incidentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spIncident.setPrompt(jsonFileReader.getLabelObj("MSG_SELECT_INCIDENT"));
spIncident.setAdapter(incidentAdapter);
incidentValueList = jsonFileReader.getincidentListValue();
/*
new Spinner Adapter
*/
}
ArrayAdapter<String> incidentAdultAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, alistIncidentAdult);
incidentAdultAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spIncidentAdult.setPrompt(jsonFileReader.getLabelObj("LBL_TYPE"));
spIncidentAdult.setAdapter(incidentAdultAdapter);
ArrayAdapter<String> situationAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, alistSituationList);
situationAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spSituation.setPrompt(jsonFileReader.getLabelObj("LBL_TYPE"));
spSituation.setAdapter(situationAdapter);
spStateName.setOnItemSelectedListener(SpStateItemSelectListener);
spIncident.setOnItemSelectedListener(SpIncidentItemSelectListener);
spTime.setOnItemSelectedListener(SpTimeItemSelectListener);
spReporterType.setOnItemSelectedListener(SpReportTypeItemSelectListener);
/*
new Spiner onitemclick listeer
*/
spIncidentAdult.setOnItemSelectedListener(SpIncidentAdultItemSelectListener);
spSituation.setOnItemSelectedListener(SpSituationItemSelectListener);
Calendar calendar = Calendar.getInstance();
currentDay = calendar.get(Calendar.DATE);
currentMonth = calendar.get(Calendar.MONTH);
currentYear = calendar.get(Calendar.YEAR);
schoolNameList = new ArrayList<String>();
schoolCityList = new ArrayList<String>();
schoolIDList = new ArrayList<String>();
x = getResources().getDrawable(R.drawable.close);
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
autotxtSchoolName.addTextChangedListener(autoTxtwatcher);
autotxtSchoolName.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
value_schoolID = schoolIDList.get(position);
value_schoolName = schoolNameList.get(position);
AppUtils.hideSoftKeyboard(FormActivity.this);
}
});
autotxtSchoolName.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent event) {
if (autotxtSchoolName.getCompoundDrawables()[2] == null) {
return false;
}
if (event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
if (event.getX() > autotxtSchoolName.getWidth()
- autotxtSchoolName.getPaddingRight() - x.getIntrinsicWidth()) {
autotxtSchoolName.setText("");
autotxtSchoolName.setCompoundDrawables(null, null, null, null);
if (schoolNameList != null) {
schoolNameList.clear();
}
if (schoolCityList != null) {
schoolCityList.clear();
}
if (schoolIDList != null) {
schoolIDList.clear();
}
value_schoolID = null;
}
return false;
}
});
/*HashMap<String,Object>paramValues=new HashMap<String, Object>();
paramValues.put("token",Constant.token);
ETechAsyncTask task=new ETechAsyncTask(this,this,"IncidentList", paramValues,ETechAsyncTask.REQUEST_METHOD_POST);
task.execute(Constant.getIncidentLocationListURL);*/
}
View.OnClickListener uploadClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
};
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("sprigeo_en.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
public void setLabelNames() {
try {
// AppUtils.hideSoftKeyboard(FormActivity.this);
TextView LBL_LIVE = (TextView) findViewById(R.id.LBL_LIVE);
TextView LBL_SEL_SCHOOL = (TextView) findViewById(R.id.LBL_SEL_SCHOOL);
TextView LBL_WHERE_INCIDENT = (TextView) findViewById(R.id.LBL_WHERE_INCIDENT);
TextView LBL_WHEN_HAPPEN = (TextView) findViewById(R.id.LBL_WHEN_HAPPEN);
TextView LBL_TIME = (TextView) findViewById(R.id.LBL_TIME);
TextView LBL_BULLY = (TextView) findViewById(R.id.LBL_BULLY);
TextView LBL_BULLY_PERSON = (TextView) findViewById(R.id.LBL_BULLY_PERSON);
TextView LBL_WHAT_HAPPEN = (TextView) findViewById(R.id.LBL_WHAT_HAPPEN);
TextView LBL_WHO = (TextView) findViewById(R.id.LBL_WHO);
TextView LBL_NAME = (TextView) findViewById(R.id.LBL_NAME);
TextView LBL_PHONE = (TextView) findViewById(R.id.LBL_PHONE);
Button btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(clickListener);
Button btnBack = (Button) findViewById(R.id.btnBack);
if (jsonFileReader != null) {
APP_NAME = jsonFileReader.getLabelObj("APP_TITLE");
if (isTablet(this)) {
txtHeaderTitle.setText(APP_NAME);
} else {
String txtTitle = jsonFileReader.getLabelObj("TITLE_FORM1");
if (txtTitle != null) {
txtHeaderTitle.setText(txtTitle);
}
}
String txtLIVE = jsonFileReader.getLabelObj("LBL_LIVE");
if (txtLIVE != null) {
LBL_LIVE.setText(txtLIVE);
}
String txtSchool = jsonFileReader.getLabelObj("LBL_SEL_SCHOOL");
if (txtSchool != null) {
LBL_SEL_SCHOOL.setText(txtSchool);
}
String txtIncident = jsonFileReader.getLabelObj("LBL_WHERE_INCIDENT");
if (txtIncident != null) {
LBL_WHERE_INCIDENT.setText(txtIncident);
}
String txtWhenHappen = jsonFileReader.getLabelObj("LBL_WHEN_HAPPEN");
if (txtWhenHappen != null) {
LBL_WHEN_HAPPEN.setText(txtWhenHappen);
}
String txtTIME = jsonFileReader.getLabelObj("LBL_TIME");
if (txtTIME != null) {
LBL_TIME.setText(txtTIME);
}
String txtBULLY = jsonFileReader.getLabelObj("LBL_BULLY");
if (txtBULLY != null) {
LBL_BULLY.setText(txtBULLY);
}
String txtBULLYPERSON = jsonFileReader.getLabelObj("LBL_BULLY_PERSON");
if (txtBULLYPERSON != null) {
LBL_BULLY_PERSON.setText(txtBULLYPERSON);
}
String txtWHATHAPPEN = jsonFileReader.getLabelObj("LBL_WHAT_HAPPEN");
if (txtWHATHAPPEN != null) {
LBL_WHAT_HAPPEN.setText(txtWHATHAPPEN);
}
String txtWHO = jsonFileReader.getLabelObj("LBL_WHO");
if (txtWHO != null) {
LBL_WHO.setText(txtWHO);
}
String txtName = jsonFileReader.getLabelObj("LBL_NAME");
if (txtName != null) {
LBL_NAME.setText(txtName);
}
String txtPhone = jsonFileReader.getLabelObj("LBL_PHONE");
if (txtPhone != null) {
LBL_PHONE.setText(txtPhone);
}
String txtBtnSubmit = jsonFileReader.getLabelObj("BTN_SUBMIT");
if (txtBtnSubmit != null) {
btnSubmit.setText(txtBtnSubmit);
}
String txtBtnOk = jsonFileReader.getLabelObj("BTN_OK");
if (txtBtnOk != null) {
btn_diaOK = txtBtnOk;
}
String txtBtnCancel = jsonFileReader.getLabelObj("BTN_CANCEL");
if (txtBtnCancel != null) {
btn_diaCancel = txtBtnCancel;
}
String txtBtnBack = jsonFileReader.getLabelObj("BTN_BACK");
if (txtBtnBack != null) {
btnBack.setText(" " + txtBtnBack);
}
String txtBtnNext = jsonFileReader.getLabelObj("BTN_NEXT");
if (txtBtnNext != null) {
btnHeaderNext.setText(txtBtnNext);
}
}
} catch (Exception e) {
Log.e("FormActivity", "setLabelNames() " + e, e);
}
}
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
value_description = editDescription.getText().toString();
String validateMsg = validateValues(true);
if (validateMsg != null) {
CustomAlertDialogue.showAlert(FormActivity.this, APP_NAME, validateMsg, btn_diaOK, null, null, null);
}
else {
try {
HashMap<String, Object> submitparams = new HashMap<String, Object>();
submitparams.put("token", Constant.token);
// submitparams.put("stateId",URLEncoder.encode(value_stateID,"utf-8"));
submitparams.put("school", URLEncoder.encode(value_schoolName, "utf-8"));
if (value_schoolID != null && !"".equalsIgnoreCase(value_schoolID))
submitparams.put("schoolId", URLEncoder.encode(value_schoolID, "utf-8"));
else
submitparams.put("schoolId", "");
submitparams.put("incidentLocation", URLEncoder.encode(value_incidentLocation, "utf-8"));
submitparams.put("incidentDescription", URLEncoder.encode(value_description, "utf-8"));
submitparams.put("incidentDate", URLEncoder.encode(btnDate.getText().toString(), "utf-8"));
submitparams.put("incidentTime", URLEncoder.encode(value_incidentTime, "utf-8"));
submitparams.put("howManyTimes", URLEncoder.encode(valueSituation, "utf-8"));
submitparams.put("reportedToAdult", URLEncoder.encode(valueIncidentAdult, "utf-8"));
//submitparams.put("reportedToAdultName", URLEncoder.encode(strWhois, "utf-8"));
if (strWhois != null && !"".equalsIgnoreCase(strWhois))
submitparams.put("reportedToAdultName", URLEncoder.encode(strWhois, "utf-8"));
else
submitparams.put("reportedToAdultName", "");
submitparams.put("SentFromMobile", URLEncoder.encode("1", "utf-8"));
submitparams.put("bullyName", URLEncoder.encode(editBullyperson.getText().toString(), "utf-8"));
submitparams.put("victimName", URLEncoder.encode(editPerson.getText().toString(), "utf-8"));
submitparams.put("postedBy", URLEncoder.encode(value_reporterType, "utf-8"));
submitparams.put("postedByName", URLEncoder.encode(editName.getText().toString(), "utf-8"));
submitparams.put("postedByName", URLEncoder.encode(editName.getText().toString(), "utf-8"));
//get POST image
String imgresponse = "";
if(imgUpload.getDrawable() != null) {
Bitmap bitmap = ((BitmapDrawable) imgUpload.getDrawable()).getBitmap();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
byte[] byteArray = bytes.toByteArray();
String encodedImage = Base64.encodeToString(byteArray, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String currentDateandTime = sdf.format(new Date());
HashMap<String, Object> imageparams = new HashMap<String, Object>();
imageparams.put("image", URLEncoder.encode(encodedImage, "utf-8"));
imageparams.put("name", URLEncoder.encode("image" + currentDateandTime + ".jpg", "utf-8"));
ETechAsyncTask subMitImageTask = new ETechAsyncTask(FormActivity.this, FormActivity.this, "+", imageparams, ETechAsyncTask.REQUEST_METHOD_POST);
imgresponse = subMitImageTask.execute("http://safeoregon.com/test.php").get();
submitparams.put("imagename", URLEncoder.encode("image" + currentDateandTime + ".jpg", "utf-8"));
}
else{
submitparams.put("imagename", "");
}
// submitparams.put("postedByContactInfo",URLEncoder.encode(editPhNo.getText().toString(),"utf-8"));
/* if (strWhois != null && !"".equalsIgnoreCase(strWhois))
submitparams.put("reportedToAdultName", URLEncoder.encode(strWhois, "utf-8"));
else
submitparams.put("reportedToAdultName","");*/
Log.i("SubmitParams: ", submitparams.toString());
ETechAsyncTask subMitDataTask = new ETechAsyncTask(FormActivity.this, FormActivity.this, "SubmitData", submitparams, ETechAsyncTask.REQUEST_METHOD_POST);
subMitDataTask.execute(Constant.submitIncidentURL);
} catch (Exception e) {
Log.e("SubmitParams", "Error : " + e.getMessage());
}
}
}
};
String strText = "";
int delay = 1000;
TextWatcher autoTxtwatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence text, int start, int before, int count) {
autotxtSchoolName.setCompoundDrawables(null, null, autotxtSchoolName.getText()
.toString().equals("") ? null : x, null);
/* if(value_stateID==null || "".equalsIgnoreCase(value_stateID)){
String alertStateMsg = "Please Select a State.";
if(jsonFileReader != null){
String ALT_STATE = jsonFileReader.getLabelObj("ALT_STATE");
if(ALT_STATE != null) {alertStateMsg = ALT_STATE; }
}
CustomAlertDialogue.showAlert(FormActivity.this,null,alertStateMsg,btn_diaOK,null,null,null);
}
else{*/
strText = text.toString();
if (text.length() > 1) {
if (start != 0) {
handler.removeMessages(2);
handler.sendMessageDelayed(handler.obtainMessage(2), delay);
}
}
if (start != 0) {
if (schoolNameList != null) {
schoolNameList.clear();
}
if (schoolCityList != null) {
schoolCityList.clear();
}
if (schoolIDList != null) {
schoolIDList.clear();
}
}
// }
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("token", Constant.token);
ETechAsyncTask task = new ETechAsyncTask(FormActivity.this, FormActivity.this, "SchoolName", params, ETechAsyncTask.REQUEST_METHOD_POST);
task.execute("http://report.sprigeo.com/schoolLookup?stateid=" + Constant.STATE_ID + "&q=" + URLEncoder.encode(strText) + "&lan=" + user_lang);
}
};
OnItemSelectedListener SpStateItemSelectListener = new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
long arg3) {
value_stateID = stateIDList.get(position);/*Constant.stateID[position];*/
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
OnItemSelectedListener SpTimeItemSelectListener = new OnItemSelectedListener() {
@SuppressLint("LongLogTag")
@Override
public void onItemSelected(AdapterView<?> spinnerAdapter, View arg1, int position, long arg3) {
value_incidentTime = Constant.TimeID[position];
Log.i("Time Spinner Select Value:", value_incidentTime);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
OnItemSelectedListener SpIncidentItemSelectListener = new OnItemSelectedListener() {
@SuppressLint("LongLogTag")
@Override
public void onItemSelected(AdapterView<?> spinner, View arg1, int position, long arg3) {
incidentValue = position;
value_incidentLocation = incidentValueList.get(position);/*spinner.getItemAtPosition(position).toString()*/
;
Log.i("incidentLocation Spinner Select Value:", value_incidentLocation);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
OnItemSelectedListener SpReportTypeItemSelectListener = new OnItemSelectedListener() {
@SuppressLint("LongLogTag")
@Override
public void onItemSelected(AdapterView<?> spinnerAdapter, View arg1, int position, long arg3) {
value_reporterType = reporterValueList.get(position)/*spinnerAdapter.getItemAtPosition(position).toString()*/;
if (value_reporterType.equalsIgnoreCase(jsonFileReader.getLabelObj("LBL_SELECT"))) {
value_reporterType = "";
}
Log.i("ReporterType Spinner Select Value:", value_reporterType);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
OnItemSelectedListener SpIncidentAdultItemSelectListener = new OnItemSelectedListener() {
@SuppressLint("LongLogTag")
@Override
public void onItemSelected(AdapterView<?> spinnerAdapter, View arg1, int position, long arg3) {
valueIncidentAdult = alistIncidentAdult.get(position)/*spinnerAdapter.getItemAtPosition(position).toString()*/;
if (valueIncidentAdult != null && valueIncidentAdult.equalsIgnoreCase("Yes")) {
edtWho.setVisibility(View.VISIBLE);
//Toast.makeText(FormActivity.this, "Please Select any one", Toast.LENGTH_SHORT).show();
} else if (valueIncidentAdult.equalsIgnoreCase(jsonFileReader.getLabelObj("LBL_SELECT")) || valueIncidentAdult != null && (valueIncidentAdult.equalsIgnoreCase("No"))) {
edtWho.setVisibility(View.GONE);
edtWho.setText("");
}
Log.i("SpIncidentAdultItemSelectListener", "Incient Adult : " + valueIncidentAdult);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
OnItemSelectedListener SpSituationItemSelectListener = new OnItemSelectedListener() {
@SuppressLint("LongLogTag")
@Override
public void onItemSelected(AdapterView<?> spinnerAdapter, View arg1, int position, long arg3) {
valueSituation = alistSituationList.get(position)/*spinnerAdapter.getItemAtPosition(position).toString()*/;
/*if(valueSituation.equalsIgnoreCase(jsonFileReader.getLabelObj("LBL_SELECT"))){
valueSituation="";
//Toast.makeText(FormActivity.this, "Please Select any one", Toast.LENGTH_SHORT).show();
}
*/
Log.i("SpIncidentAdultItemSelectListener", "valueSituation : " + valueSituation);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
public void btnDateTimeClick(View v) {
dateDialogflag = true;
DatePickerDialog dialog = new DatePickerDialog(this, mDateSetListener, currentYear, currentMonth, currentDay);
//------->
//dialog.setTitle("Select Date");
dialog.show();
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if (dateDialogflag) {
dateDialogflag = false;
if (isDateAfter(view)) {
String msg = jsonFileReader.getLabelObj("MSG_PREVIOUS_DATE");
if (msg == null) {
msg = "Please Select Previous Date.";
}
CustomAlertDialogue.showAlert(FormActivity.this, APP_NAME, msg, btn_diaOK, btn_diaCancel, alertClick, null);
} else {
btnDate.setText((monthOfYear + 1) + "/" + dayOfMonth + "/" + year);
currentYear = year;
currentMonth = monthOfYear;
currentDay = dayOfMonth;
}
}
}
private boolean isDateAfter(DatePicker tempView) {
Calendar mCalendar = Calendar.getInstance();
Calendar tempCalendar = Calendar.getInstance();
tempCalendar.set(tempView.getYear(), tempView.getMonth(), tempView.getDayOfMonth(), 0, 0, 0);
if (tempCalendar.after(mCalendar))
return true;
else
return false;
}
};
OnClickListener alertClick = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
btnDateTimeClick(null);
}
};
public void btnHeaderNextClick(View v) {
String validateMsg = null;
if (formFlipper.getDisplayedChild() == 0)
validateMsg = validateValues(false);
else if (formFlipper.getDisplayedChild() == 1) {
value_description = editDescription.getText().toString();
validateMsg = validateValues(true);
} else if (formFlipper.getDisplayedChild() == 2) {
validateMsg = validate();
}
if (validateMsg != null) {
CustomAlertDialogue.showAlert(this, APP_NAME, validateMsg, btn_diaOK, null, null, null);
} else {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editDescription.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if (formFlipper.getDisplayedChild() == 2) {
btnHeaderNext.setVisibility(View.GONE);
}
formFlipper.showNext();
changeHeaderTitle();
}
}
private String validate() {
if (valueSituation != null && valueSituation.equalsIgnoreCase(jsonFileReader.getLabelObj("LBL_SELECT"))) {
return "Please Select another Situation.";
}
if (valueIncidentAdult != null && valueIncidentAdult.equalsIgnoreCase(jsonFileReader.getLabelObj("LBL_SELECT"))) {
// edtWho.setVisibility(View.GONE);
return "Please Select another Incident Adult.";
}
if (edtWho.getVisibility() == View.VISIBLE) {
strWhois = edtWho.getText().toString().trim();
if (strWhois == null || strWhois.trim().equalsIgnoreCase("")) {
return "Please Enter Value.";
}
}
return null;
}
private String validateValues(Boolean checkDescription) {
if (value_schoolName == null || value_schoolName.trim().length() <= 0) {
value_schoolName = autotxtSchoolName.getText().toString().trim();
}
if (value_schoolName == null || value_schoolName.trim().equalsIgnoreCase("")) {
/*if(jsonFileReader!= null){
String ALT_SCHOOL = jsonFileReader.getLabelObj("ALT_SCHOOL");
if(ALT_SCHOOL != null) { return ALT_SCHOOL; }
}*/
return "School name is Required.";
} else if (incidentValue == 0) {
if (jsonFileReader != null) {
String ALT_INCIDENT = jsonFileReader.getLabelObj("ALT_INCIDENT");
if (ALT_INCIDENT != null) {
return ALT_INCIDENT;
}
}
return "Incident is Required.";
} else if (checkDescription) {
if (value_description == null || "".equalsIgnoreCase(value_description)) {
if (jsonFileReader != null) {
String ALT_DESC = jsonFileReader.getLabelObj("ALT_DESC");
if (ALT_DESC != null) {
return ALT_DESC;
}
}
return "Description is Required.";
}
}
return null;
}
@Override
public void onTaskComplete(int statusCode, String result, String webserviceCb) {
if (statusCode == ETechAsyncTask.COMPLETED) {
if (webserviceCb.equalsIgnoreCase("SchoolName")) {
Log.i("Result", result);
try {
JSONArray schoolNames = new JSONArray(result);
for (int i = 0; i < schoolNames.length(); i++) {
JSONObject school = schoolNames.getJSONObject(i);
schoolNameList.add(school.getString("school"));
schoolCityList.add(school.getString("city"));
schoolIDList.add(school.getString("id"));
}
Log.i("schoolNameList", schoolNameList.toString());
Log.i("schoolCityList", schoolCityList.toString());
Log.i("schoolIDList", schoolIDList.toString());
ArrayAdapter<String> schoolListadapter = new AutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line, schoolNameList);
autotxtSchoolName.setAdapter(schoolListadapter);
autotxtSchoolName.showDropDown();
} catch (JSONException e) {
Log.e("JSONError:" + webserviceCb, " Error: " + e, e);
}
} else if (webserviceCb.equalsIgnoreCase("SubmitData")) {
Log.i("Submit Response: ", result);
String original_response="";
try {
String substr = "<BR>";
if(result.contains("<BR>")) {
String before = result.substring(0, result.indexOf(substr));
original_response = result.substring(result.indexOf(substr) + substr.length());
}
else
original_response=result;
// Log.d("TestStrinng","Before Data : "+before);
// Log.d("TestStrinng","After Data : "+original_response);
JSONArray response = new JSONArray(original_response);
String submitsuccess = response.getJSONObject(0).getString("success");
String message = response.getJSONObject(0).getString("message");
if (submitsuccess.equalsIgnoreCase("true")) {
String reportSubmitMsg = "Your Report has been sent. Thanks for using Sprigeo";
if (jsonFileReader != null) {
String ALT_MSG = jsonFileReader.getLabelObj("ALT_REPORT_SUBMT");
if (ALT_MSG != null) {
reportSubmitMsg = ALT_MSG;
}
}
CustomAlertDialogue.showAlert(this, APP_NAME, reportSubmitMsg, btn_diaOK, null, succesfulSubmitAlertClick, null);
} else {
CustomAlertDialogue.showAlert(this, APP_NAME, message, btn_diaOK, null, succesfulSubmitAlertClick, null);
}
} catch (JSONException e) {
CustomAlertDialogue.showAlert(this, "Error", "Error Occured.", btn_diaOK, null, null, null);
e.printStackTrace();
}
}
/*else if(webserviceCb.equalsIgnoreCase("IncidentList")){
try {
JSONArray response=new JSONArray(result);
incidentLocationList=new ArrayList<String>();
incidentLocationList.add("---Select---");
for(int i=0;i<response.length();i++){
incidentLocationList.add(response.getJSONObject(i).getString("location"));
}
if(incidentLocationList!=null){
ArrayAdapter<String> incidentLocationListadapter=new AutoCompleteAdapter(this,android.R.layout.simple_spinner_item,incidentLocationList);
incidentLocationListadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spIncident.setAdapter(incidentLocationListadapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
} else if (statusCode == ETechAsyncTask.ERROR_NETWORK) {
String msg = jsonFileReader.getLabelObj("ALT_NETWORK");
if (msg == null) {
msg = result;
}
CustomAlertDialogue.showAlert(this, APP_NAME, msg, btn_diaOK, null, null, null);
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Gallery Image", "Gallery Video", "Capture Video", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(FormActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/*intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);*/
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Gallery Image")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_IMAGE_FILE);
} else if (items[item].equals("Gallery Video")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
intent.setType("video/*");
startActivityForResult(
Intent.createChooser(intent, "Select Video"),
SELECT_VIDEO_FILE);
} else if (items[item].equals("Capture Video")) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
// start the video capture Intent
startActivityForResult(intent, VIDEO_CAPTURE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
// performCrop(data.getData());
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imgUpload.setVisibility(View.VISIBLE);
imgUpload.setImageBitmap(thumbnail);
} else if (requestCode == SELECT_IMAGE_FILE) {
Uri selectedImageUri = data.getData();
performCrop(selectedImageUri);
} else if (requestCode == SELECT_VIDEO_FILE || requestCode == VIDEO_CAPTURE) {
// get the returned data
try {
Uri selectedImageUri = data.getData();
// performCrop(selectedImageUri);
String video_path = getPath(selectedImageUri);
Intent intent = new Intent(FormActivity.this, VideoTrimActivity.class);
intent.putExtra("filepath", video_path);
startActivityForResult(intent, REQUEST_CODE_VIDEO_TRIM);
} catch (Exception e) {
e.printStackTrace();
}
} /*else if (requestCode == VIDEO_CAPTURE) {
*//* File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".mp4");
try {
destination.createNewFile();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*//*
Uri videoUri = data.getData();
String video_path = getPath(videoUri);
Bitmap bmThumbnail;
bmThumbnail = ThumbnailUtils.createVideoThumbnail(video_path,
MediaStore.Video.Thumbnails.MICRO_KIND);
imgUpload.setVisibility(View.VISIBLE);
imgUpload.setImageBitmap(bmThumbnail);
}*/ else if (requestCode == CROP_PIC) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
// ImageView picView = (ImageView) findViewById(R.id.picture);
imgUpload.setVisibility(View.VISIBLE);
imgUpload.setImageBitmap(thePic);
} else if (requestCode == REQUEST_CODE_VIDEO_TRIM) {
if (data.hasExtra("filepath")) {
String trimFilepath = data.getStringExtra("filepath");
// Toast.makeText(FormActivity.this, trimFilepath + "", Toast.LENGTH_LONG).show();
Bitmap bmThumbnail;
bmThumbnail = ThumbnailUtils.createVideoThumbnail(trimFilepath,
MediaStore.Video.Thumbnails.MICRO_KIND);
imgUpload.setVisibility(View.VISIBLE);
imgUpload.setImageBitmap(bmThumbnail);
}
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
private void performCrop(Uri picUri) {
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_PIC);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
@Override
public void onBackPressed() {
btnHeaderBackClick(null);
}
public void btnHeaderBackClick(View v) {
if (formFlipper.getDisplayedChild() == 0) {
finish();
} else {
formFlipper.showPrevious();
changeHeaderTitle();
if (formFlipper.getDisplayedChild() < 3) {
btnHeaderNext.setVisibility(View.VISIBLE);
}
}
}
public void changeHeaderTitle() {
if (formFlipper.getDisplayedChild() == 0) {
if (jsonFileReader != null) {
String titleForm1 = jsonFileReader.getLabelObj("TITLE_FORM1");
txtHeaderTitle.setText(titleForm1);
}
} else if (formFlipper.getDisplayedChild() == 1) {
if (jsonFileReader != null) {
String titleForm2 = jsonFileReader.getLabelObj("TITLE_FORM2");
txtHeaderTitle.setText(titleForm2);
}
} else if (formFlipper.getDisplayedChild() == 2) {
// if(jsonFileReader !=null){
String titleForm3 = jsonFileReader.getLabelObj("TITLE_FORM3");
txtHeaderTitle.setText("Form 3");
// }
} else if (formFlipper.getDisplayedChild() == 3) {
if (jsonFileReader != null) {
String titleForm3 = jsonFileReader.getLabelObj("TITLE_FORM3");
txtHeaderTitle.setText(titleForm3);
}
}
}
OnClickListener succesfulSubmitAlertClick = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(FormActivity.this, ThankYouActivity.class);
startActivity(intent);
finish();
}
};
}
<file_sep>/app/src/main/java/com/safeoregon/app/ThankYouActivity.java
package com.safeoregon.app;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.etech.util.Header;
public class ThankYouActivity extends HeaderActivity implements OnClickListener {
Button thankYou;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thankyou);
setHeader();
thankYou = (Button) findViewById(R.id.btnThank);
thankYou.setOnClickListener(this);
}
private void setHeader() {
try {
super.setTitle(getString(R.string.title_thank_u));
Header header = (Header) findViewById(R.id.header1);
header.setLeftBtnImage(R.drawable.ic_back_arrow);
header.hideRightBtn();
header.setLeftBtnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnThank:
this.finish();
break;
}
}
}
<file_sep>/app/src/main/java/com/safeoregon/app/MyTipsDetailActivity.java
package com.safeoregon.app;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.etech.bean.DbMyTips;
import com.etech.util.Header;
/**
* Created by etech8 on 11/2/16.
*/
public class MyTipsDetailActivity extends HeaderActivity {
TextView txtTipsNo;
TextView txtTipsDate;
DbMyTips myTips;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_detail);
setHeader();
init();
}
private void setHeader() {
try {
super.setTitle(getString(R.string.title_tips_detail));
Header header = (Header) findViewById(R.id.header1);
header.setLeftBtnImage(R.drawable.ic_back_arrow);
header.hideRightBtn();
header.setLeftBtnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void init()
{
Intent intent = getIntent();
myTips = (DbMyTips) intent.getSerializableExtra("myTips");
txtTipsNo = (TextView) findViewById(R.id.txtTipsNo);
txtTipsDate = (TextView) findViewById(R.id.txtTipsDate);
if(myTips!=null && myTips.getTips_number()!=null)
txtTipsNo.setText(myTips.getTips_number());
if(myTips!=null && myTips.getTips_date()!=null)
txtTipsDate.setText(myTips.getTips_date());
}
}
<file_sep>/app/src/main/java/com/safeoregon/app/MyTipsListActivity.java
package com.safeoregon.app;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.etech.bean.DbMyTips;
import com.etech.model.myTipsHelper;
import com.etech.util.ActionCallback;
import com.etech.util.Header;
import java.util.ArrayList;
/**
* Created by etech8 on 11/2/16.
*/
public class MyTipsListActivity extends HeaderActivity {
private ListView listTips;
Context context = MyTipsListActivity.this;
private ArrayList<DbMyTips> alistmyTips;
DbMyTips myTips;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_list);
setHeader();
alistmyTips = new ArrayList<DbMyTips>();
getTipsList();
}
private void setHeader() {
try {
super.setTitle(getString(R.string.title_tips_list));
Header header = (Header) findViewById(R.id.header1);
header.setLeftBtnImage(R.drawable.ic_back_arrow);
header.hideRightBtn();
header.setLeftBtnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void init()
{
listTips = (ListView) findViewById(R.id.listTips);
}
private void getTipsList()
{
try
{
myTipsHelper tipsHelper = new myTipsHelper(context);
tipsHelper.apiGetTipsList(tipsCallback);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private ActionCallback tipsCallback = new ActionCallback() {
@Override
public void onActionComplete(int statusCode, String callbackString,
Object res) {
if(alistmyTips!=null && alistmyTips.size()>0)
alistmyTips.clear();
init();
myTips = new DbMyTips();
myTips.setTips_id("1");
myTips.setTips_number("tips 1");
myTips.setTips_date("1-1-2015");
alistmyTips.add(myTips);
myTips = new DbMyTips();
myTips.setTips_id("2");
myTips.setTips_number("tips2");
myTips.setTips_date("02-02-2015");
alistmyTips.add(myTips);
myTips = new DbMyTips();
myTips.setTips_id("3");
myTips.setTips_number("tips 3");
myTips.setTips_date("3-02-2015");
alistmyTips.add(myTips);
myTips = new DbMyTips();
myTips.setTips_id("4");
myTips.setTips_number("tips 4");
myTips.setTips_date("4-02-2015");
alistmyTips.add(myTips);
MyTipsListAdapter tipsAdapter = new MyTipsListAdapter(context);
listTips.setAdapter(tipsAdapter);
}
};
class MyTipsListAdapter extends BaseAdapter {
Context context;
private LayoutInflater mLayoutInflater = null;
public MyTipsListAdapter(Context context) {
this.context = context;
mLayoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return alistmyTips.size();
}
@Override
public Object getItem(int position) {
try {
return alistmyTips.get(position);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
try {
if (view == null) {
holder = new ViewHolder();
//view = mLayoutInflater.inflate(R.layout., null);
view = mLayoutInflater.inflate(R.layout.common_tips_view, viewGroup, false);
holder.txtTipsNo = (TextView) view.findViewById(R.id.txtTipsNo);
holder.txtTipsDate = (TextView) view.findViewById(R.id.txtTipsDate);
holder.btnView = (Button) view.findViewById(R.id.btnView);
// the setTag is used to store the data within this view
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final DbMyTips myTips = alistmyTips.get(position);
holder.btnView.setTag(myTips.getTips_id());
holder.txtTipsNo.setText("" + myTips.getTips_number());
holder.txtTipsDate.setText("" + myTips.getTips_date());
holder.btnView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyTipsListActivity.this,MyTipsDetailActivity.class);
intent.putExtra("myTips",myTips);
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
private class ViewHolder {
private TextView txtTipsNo;
private TextView txtTipsDate;
private Button btnView;
}
}
}
<file_sep>/app/src/main/java/com/etech/util/Header.java
package com.etech.util;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.safeoregon.app.R;
public class Header extends RelativeLayout {
private final String tag = "Header";
private ImageButton btnRight = null;
private ImageButton btnLeft = null;
private TextView txtTitle = null;
private EditText fakeEdit = null;
private RelativeLayout headerView;
private String title = null;
private Activity activity = null;
public Header(Context context, AttributeSet attrs) {
super(context, attrs);
String infService = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li;
li = (LayoutInflater) getContext().getSystemService(infService);
li.inflate(R.layout.header, this, true);
btnLeft = (ImageButton) findViewById(R.id.btnLeft);
btnRight = (ImageButton) findViewById(R.id.btnRight);
txtTitle = (TextView) findViewById(R.id.txtTitle);
headerView = (RelativeLayout) findViewById(R.id.header);
}
public void init(Activity activity, String title) {
init(activity, title, null, null, false);
}
public void init(Activity activity, String title, String rightBtntitle, OnClickListener rightBtnClickListener, Boolean addMenu) {
this.activity = activity;
this.title = title;
if (title != null) {
txtTitle.setText(this.title);
}
btnLeft.setOnClickListener(leftBtnClickListener);
/* if(rightBtnClickListener != null) {
btnRight.setOnClickListener(rightBtnClickListener);
}
else {
btnRight.setVisibility(View.GONE);
}*/
/* if(addMenu){
menu=new SlidingMenu(activity, SlidingMenu.SLIDING_WINDOW);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
menu.setMenu(new MenuView(activity));
}
*/
}
OnClickListener leftBtnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
//if(menu!=null) {
// menu.toggle();
/*MenuView menuView = (MenuView) menu.getMenu();
menuView.showLinNewbieView();*/
//}
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(fakeEdit.getWindowToken(), 0);
//activity.finish();
}
};
public void hideLeftBtn() {
btnLeft.setVisibility(View.GONE);
}
public void setRightBtnImage(int rightBtnImage){
btnRight.setImageResource(rightBtnImage);
}
public void hideRightBtn(){
btnRight.setVisibility(View.GONE);
}
public void btnRighClickListener(OnClickListener onClickListener){
if(onClickListener!=null){
btnRight.setVisibility(View.VISIBLE);
btnRight.setOnClickListener(onClickListener);
}else{
btnRight.setVisibility(View.INVISIBLE);
}
}
public void setLeftBtnImage(int leftBtnImage) {
btnLeft.setImageResource(leftBtnImage);
}
public void setLeftBtnTitle(int leftBtnTitle) {
btnLeft.setImageResource(leftBtnTitle);
}
public void setLeftBtnClickListener(OnClickListener btnLeftClickListener) {
btnLeft.setOnClickListener(btnLeftClickListener);
}
public void setTitle(String title) {
txtTitle.setText(title);
}
public void setBackGroundColor(int resId) {
//AppUtils.setStatusbarColor(getContext(),resId);
headerView.setBackgroundResource(resId);
}
}
| 272c3492ec49a8b42e451292fddca2bed803380d | [
"Java",
"INI"
] | 6 | INI | dpoarch/SafeOregon-Android | 3d8940946cb753f5236dc0b205821a5f46a68861 | 53e1114c02ade0be2f8613863c0ce047c2f0f9f9 |
refs/heads/master | <file_sep>TwitalyseClient
===============
This is a Webinterface-Client for the Twitalyse-Service.<file_sep>/*
* Copyright (C) 2012 MacYser
*
* 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/>.
*/
package de.fhb.twitalyseclient.beans.components;
import de.fhb.twitalyseclient.beans.common.NaviActionListener;
import de.fhb.twitalyseclient.connection.RedisConnection;
import java.io.IOException;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PreDestroy;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.component.submenu.Submenu;
import org.primefaces.model.DefaultMenuModel;
import org.primefaces.model.MenuModel;
import redis.clients.jedis.Jedis;
/**
*
* @author MacYser
*/
@Named
@RequestScoped
public class NaviBean {
private MenuModel model;
private Jedis jedis;
/**
* Creates a new instance of NaviBean
*/
public NaviBean() {
jedis = new RedisConnection().getConnection();
}
@PreDestroy
private void preDestroy() {
jedis.disconnect();
}
private Set<String> getKeyOfDailyWords() {
return jedis.keys("words_*");
}
private Set<String> getKeyOfDailyWordsInEnviroment() {
return jedis.keys("coordswords_*");
}
private Set<String> getKeyOfDailyHashtags() {
return jedis.keys("hashtags_*");
}
private void buildMenuModel() {
model = new DefaultMenuModel();
String key;
//Global submenu
Submenu subAllStatistics = new Submenu();
subAllStatistics.setLabel("Global Statistics");
MenuItem item = new MenuItem();
item.setValue("All Words");
key = "words";
item.setAjax(false);
item.getAttributes().put("key", key);
item.addActionListener(new NaviActionListener());
subAllStatistics.getChildren().add(item);
item = new MenuItem();
item.setValue("All Words in Enviroment");
key = "coordswords";
item.setAjax(false);
item.getAttributes().put("key", key);
item.addActionListener(new NaviActionListener());
subAllStatistics.getChildren().add(item);
item = new MenuItem();
item.setValue("All Languages");
key = "languages";
item.setAjax(false);
item.getAttributes().put("key", key);
item.addActionListener(new NaviActionListener());
subAllStatistics.getChildren().add(item);
item = new MenuItem();
item.setValue("All Sources");
key = "sources";
item.setAjax(false);
item.getAttributes().put("key", key);
item.addActionListener(new NaviActionListener());
subAllStatistics.getChildren().add(item);
item = new MenuItem();
item.setValue("All Hashtags");
key = "hashtags";
item.setAjax(false);
item.getAttributes().put("key", key);
item.addActionListener(new NaviActionListener());
subAllStatistics.getChildren().add(item);
model.addSubmenu(subAllStatistics);
//Daily submenu
Submenu subDailyStatistics = new Submenu();
subDailyStatistics.setLabel("Daily Statistics");
String name;
for (String keyDaily : getKeyOfDailyWords()) {
name = "All Words of " + keyDaily.split("_")[1] + "." + keyDaily.split("_")[2] + "." + keyDaily.split("_")[3];
item = new MenuItem();
item.setAjax(false);
item.setValue(name);
item.getAttributes().put("key", keyDaily);
item.addActionListener(new NaviActionListener());
subDailyStatistics.getChildren().add(item);
}
for (String keyDaily : getKeyOfDailyWordsInEnviroment()) {
name = "All Words in Enviroment of " + keyDaily.split("_")[1] + "." + keyDaily.split("_")[2] + "." + keyDaily.split("_")[3];
item = new MenuItem();
item.setAjax(false);
item.setValue(name);
item.getAttributes().put("key", keyDaily);
item.addActionListener(new NaviActionListener());
subDailyStatistics.getChildren().add(item);
}
for (String keyDaily : getKeyOfDailyHashtags()) {
name = "All Hashtags of " + keyDaily.split("_")[1] + "." + keyDaily.split("_")[2] + "." + keyDaily.split("_")[3];
item = new MenuItem();
item.setAjax(false);
item.setValue(name);
item.getAttributes().put("key", keyDaily);
item.addActionListener(new NaviActionListener());
subDailyStatistics.getChildren().add(item);
}
model.addSubmenu(subDailyStatistics);
}
public MenuModel getModel() {
buildMenuModel();
return model;
}
}
<file_sep>/*
* Copyright (C) 2012 <NAME>
*
* 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/>.
*/
package de.fhb.twitalyseclient.beans.common;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;
import redis.clients.jedis.exceptions.JedisException;
/**
*
* @author <NAME>
*/
public abstract class LazyRedisDataModel<T> extends LazyDataModel<T> {
private final static Logger LOGGER = Logger.getLogger(LazyRedisDataModel.class.getName());
private Jedis jedis;
private String key;
public LazyRedisDataModel(Jedis jedis, String key) {
this.key = key;
this.jedis = jedis;
}
@Override
public List<T> load(int first, int pageSize, String sortField, SortOrder so, Map<String, String> map) {
Set<Tuple> words = null;
try {
LOGGER.log(Level.INFO, "START: {0}, END: {1}", new Object[]{first, first+(pageSize-1)});
words = jedis.zrevrangeWithScores(key, first, first+(pageSize-1));
} catch (JedisException e) {
LOGGER.log(Level.SEVERE, "JedisException{0}", e);
}
return fillList(words);
}
protected abstract List<T> fillList(Set<Tuple> returnedSet);
@Override
public void setRowIndex(final int rowIndex) {
if (rowIndex == -1 || getPageSize() == 0) {
super.setRowIndex(-1);
} else {
super.setRowIndex(rowIndex % getPageSize());
}
}
}
| 9a496281ac7b1dfce12d2b1e4664e7015c3958b3 | [
"Markdown",
"Java"
] | 3 | Markdown | Yserz/TwitalyseClient | aad071c8d743182da52f10c06963de3b52946c30 | d3624103abb23958803c581633f68d334196dbb2 |
refs/heads/main | <file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1:3306
-- Время создания: Июн 02 2021 г., 00:51
-- Версия сервера: 8.0.19
-- Версия PHP: 8.0.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `beauty_salon`
--
-- --------------------------------------------------------
--
-- Структура таблицы `clear_face`
--
CREATE TABLE `clear_face` (
`id` int NOT NULL,
`service` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `clear_face`
--
INSERT INTO `clear_face` (`id`, `service`, `price`) VALUES
(1, 'Алмазный пилинг ', '3 500 руб\r\n'),
(2, 'Ультрозвуковое очищение ', '3 500 руб\r\n'),
(3, 'Ультрозвуковое очищение в программе ', '1 500 руб\r\n'),
(4, 'Маска лифтинг ', '1 500 руб\r\n'),
(5, 'Электропорация ', '3 500 руб\r\n'),
(6, 'Комплексный уход ', '4 200 руб\r\n'),
(7, 'Комплексный уход с электропорацией ', '4 900 руб\r\n'),
(8, 'Программа Fluoroxygen+С, косметика Christina ', '3 700 руб\r\n'),
(9, 'Программа Silk, косметика Christina ', '3 900 руб\r\n'),
(10, 'Программа Wish, косметика Christina ', '3 900 руб\r\n'),
(11, 'Программа Forever young, косметика Christina ', '3 800 руб\r\n'),
(12, 'Программа Comodex, косметика Christina ', '3 500 руб\r\n'),
(13, 'Программа Muse, косметика Christina ', '3 900 руб\r\n'),
(14, 'Альгинатная маска, косметика Christina ', '1 000 руб\r\n'),
(15, 'Маска по типу кожи, косметика Christina ', '500 руб\r\n'),
(16, 'Глубокое очищение пор Le grand classique, косметика Yon-Ka ', '4 700 руб\r\n'),
(17, 'Глубокое увлажнение Hidralessence, косметика Yon-Ka ', '4 700 руб\r\n'),
(18, 'Восстановление структуры кожи Stimulastine, косметика Yon-Ka ', '5 200 руб\r\n'),
(19, 'Лифтинговый эффект Optimizer, косметика Yon-Ka ', '4 900 руб\r\n'),
(20, 'Увлажняющая маска, косметика Yon-Ka ', '700 руб\r\n'),
(21, 'Глиняная маска, 2 вида глины косметика, Yon-Ka ', '800 руб\r\n'),
(22, 'Механическое очищение ', '2 500 руб\r\n'),
(23, 'Комбинированное очищение ', '3 000 руб\r\n'),
(24, '<NAME>, Dermotime ', '3 500 руб\r\n'),
(25, 'Пилинг-уход, Dermotime ', '4 000 руб\r\n'),
(26, 'Молочный пилинг, Dermotime ', '2 500 руб\r\n'),
(27, 'Окси-пилинг с массажем лица, Dermotime ', '3 900 руб\r\n'),
(28, 'Ретиноловый крем пилинг усиливающий, Dermotime ', '1 200 руб\r\n');
-- --------------------------------------------------------
--
-- Структура таблицы `client`
--
CREATE TABLE `client` (
`id` int NOT NULL,
`name` varchar(255) NOT NULL,
`master` varchar(255) NOT NULL,
`telephone` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `client`
--
INSERT INTO `client` (`id`, `name`, `master`, `telephone`) VALUES
(1, '<NAME>', 'Кудеярова Анастасия Олеговна', '89996130111'),
(2, '<NAME>', 'Кудеярова Анастасия Олеговна', '89612220099');
-- --------------------------------------------------------
--
-- Структура таблицы `eyebrows_and_eyelashes`
--
CREATE TABLE `eyebrows_and_eyelashes` (
`id` int NOT NULL,
`service` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `eyebrows_and_eyelashes`
--
INSERT INTO `eyebrows_and_eyelashes` (`id`, `service`, `price`) VALUES
(1, 'Окрашивание бровей ', '800 руб\r\n'),
(2, 'Окрашивание бровей хной ', '1 500 руб\r\n'),
(3, 'Окрашивание ресниц ', '800 руб\r\n'),
(4, 'Коррекция бровей ', '800 руб\r\n'),
(5, 'Коррекция бровей воском ', '1 200 руб\r\n'),
(6, 'Форма бровей + окрашивание бровей и ресниц ', '1 200 руб\r\n');
-- --------------------------------------------------------
--
-- Структура таблицы `hairdressers_man`
--
CREATE TABLE `hairdressers_man` (
`id` int NOT NULL,
`service` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `hairdressers_man`
--
INSERT INTO `hairdressers_man` (`id`, `service`, `price`) VALUES
(1, 'Стрижка (цена зависит от выбранного специалиста) ', '1 900/2 500 руб\r\n'),
(2, 'Экспресс стрижка машинкой (30 мин) ', '800 руб\r\n'),
(3, 'Экспресс стрижка машинкой (60 мин) ', '1 200 руб\r\n'),
(4, 'Стрижка бороды и усов ', '800 руб\r\n'),
(5, 'Коррекция бороды и усов ', '600 руб\r\n'),
(6, 'Коррекция челки ', '500 руб\r\n'),
(7, 'Комуфляж седины (цена зависит от сложности процедуры) ', '1 800/3 000 руб\r\n'),
(8, 'Бритье головы ', '1 500 руб\r\n'),
(9, 'Массаж головы ', '500 руб\r\n');
-- --------------------------------------------------------
--
-- Структура таблицы `hairdressers_woman`
--
CREATE TABLE `hairdressers_woman` (
`id` int NOT NULL,
`service` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `hairdressers_woman`
--
INSERT INTO `hairdressers_woman` (`id`, `service`, `price`) VALUES
(1, 'Стрижка + укладка лёгкая по форме (короткие волосы) ', '2 500 руб\r\n'),
(2, 'Стрижка + укладка лёгкая по форме (длинные волосы) ', '3 200 руб\r\n'),
(3, 'Стрижка + укладка сложная коктейльная (короткие волосы) ', '3 000 руб\r\n'),
(4, 'Стрижка + укладка сложная коктейльная (длинные волосы) ', '3 500 руб\r\n'),
(5, 'Стрижка сложная + укладка лёгкая по форме (короткие волосы) ', '3 500 руб\r\n'),
(6, 'Стрижка сложная + укладка лёгкая по форме (длинные волосы) ', '3 800 руб\r\n'),
(7, 'Стрижка сложная + укладка сложная коктейльная (короткие волосы) ', '3 800 руб\r\n'),
(8, 'Стрижка сложная + укладка сложная коктейльная (длинные волосы) ', '4 200 руб\r\n'),
(9, 'Укладка лёгкая по форме (короткие волосы) ', '1 600 руб\r\n'),
(10, 'Укладка лёгкая по форме (длинные волосы) ', '2 000 руб\r\n'),
(11, 'Укладка коктейльная (короткие волосы) ', '3 000 руб\r\n'),
(12, 'Укладка коктейльная (длинные волосы) ', '3 500 руб\r\n'),
(13, 'Укладка вечерняя (короткие волосы) ', '3 500 руб\r\n'),
(14, 'Укладка вечерняя (длинные волосы) ', '4 000 руб\r\n'),
(15, 'Укладка вечерняя сложная ', '5 000 руб\r\n'),
(16, 'Cтрижка горячими ножницами ', '4 000 руб\r\n'),
(17, 'Cушка (короткие волосы) ', '700 руб\r\n'),
(18, 'Cушка (длинные волосы) ', '1 000 руб\r\n'),
(19, 'Коррекция длины ', '1 500 руб\r\n'),
(20, 'Стрижка челка ', '500 руб\r\n'),
(21, 'Массаж головы ', '500 руб\r\n'),
(22, 'Плетение простое без мытья (короткие волосы) ', '800 руб\r\n'),
(23, 'Плетение простое без мытья (длинные волосы) ', '1 000 руб\r\n'),
(24, 'Плетение простое с мытья (короткие волосы) ', '1 500 руб\r\n'),
(25, 'Плетение простое с мытья (длинные волосы) ', '2 000 руб\r\n'),
(26, 'Плетение сложное без мытья (короткие волосы) ', '1 800 руб\r\n'),
(27, 'Плетение сложное без мытья (длинные волосы) ', '2 000 руб\r\n'),
(28, 'Плетение сложное с мытья (короткие волосы) ', '2 500 руб\r\n'),
(29, 'Плетение сложное с мытья (длинные волосы) ', '3 000 руб\r\n'),
(30, 'Окрашивание, Wella ', '4 200/4 700/5 200 руб\r\n'),
(31, 'Тонирование, Wella ', '3 000/3 500/4 000 руб\r\n'),
(32, 'Мелирование, Wella ', '4 000/5 000/6 000 руб\r\n'),
(33, 'Декапирование, Wella ', '4 000 руб\r\n'),
(34, 'Блондирование, Wella ', '3 000/3 500/4 000 руб\r\n'),
(35, 'Частичное мелирование, Wella /1 прядь/ ', '500 руб\r\n'),
(36, 'Окрашивание шатуш, Wella ', '5 000 руб\r\n'),
(37, 'Уход Детокс, I.C.O.N ', '800/1 500 руб\r\n'),
(38, 'В процедуру Детокс ', '+ 500 руб\r\n'),
(39, 'Маска India 24K ', '1 500/2 000 руб\r\n'),
(40, 'Профессиональный уход за волосами, I.Plex ', '1700/2 200/3 200 руб\r\n'),
(41, 'Добавка в краситель I.Plex ', '1 000 руб\r\n');
-- --------------------------------------------------------
--
-- Структура таблицы `manicure`
--
CREATE TABLE `manicure` (
`id` int NOT NULL,
`service` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `manicure`
--
INSERT INTO `manicure` (`id`, `service`, `price`) VALUES
(1, 'Классический ', '1 000 руб\r\n'),
(2, 'Комбинированный ', '1 300 руб\r\n'),
(3, 'Аппаратный ', '1 500 руб\r\n'),
(4, 'Горячий ', '1 200 руб\r\n'),
(5, 'Экспресс-маникюр ', '800 руб\r\n'),
(6, 'Стиль/Форма/Блеск ', '500 руб\r\n'),
(7, 'Японский маникюр Masura ', '2 100 руб\r\n'),
(8, 'Массаж рук ', '400 руб\r\n');
-- --------------------------------------------------------
--
-- Структура таблицы `massage`
--
CREATE TABLE `massage` (
`id` int NOT NULL,
`service` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `massage`
--
INSERT INTO `massage` (`id`, `service`, `price`) VALUES
(1, 'Массаж 30 мин ', '1 600 руб\r\n'),
(2, 'Массаж 45 мин ', '2 000 руб\r\n'),
(3, 'Массаж 1 ч ', '2 500 руб\r\n'),
(4, 'Массаж 1,5 ч ', '3 500 руб\r\n'),
(5, 'Массаж лимфодренажный 1 ч ', '2 500 руб\r\n'),
(6, 'Массаж лимфодренажный 1,5 ч ', '3 500 руб\r\n'),
(7, 'Антицеллюлитный/Коррекционный массаж 45 мин ', '2 000 руб\r\n'),
(8, 'Антицеллюлитный/Коррекционный массаж 1 ч ', '2 500 руб\r\n'),
(9, 'Антицеллюлитный/Коррекционный массаж 1,5 ч ', '3 500 руб\r\n'),
(10, 'Пилинг манговый ', '2 000 руб\r\n'),
(11, 'Манговая программа для тела ', '5 000 руб\r\n'),
(12, 'Морской уход со спирулиной ', '5 500 руб\r\n');
-- --------------------------------------------------------
--
-- Структура таблицы `nail_extensions`
--
CREATE TABLE `nail_extensions` (
`id` int NOT NULL,
`service` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `nail_extensions`
--
INSERT INTO `nail_extensions` (`id`, `service`, `price`) VALUES
(1, 'Укрепление натуральных ногтей ', '2 300 руб\r\n'),
(2, 'Укрепление натуральных ногтей цветными гелями ', '2 600 руб\r\n'),
(3, 'Наращивание натуральных ногтей под лак ', '3 300 руб\r\n'),
(4, 'Коррекция натуральных ногтей под лак ', '2 700 руб\r\n'),
(5, 'Наращивание ногтей с постоянным цветом ', '3 800 руб\r\n'),
(6, 'Коррекция ногтей с постоянным цветом ', '2 700 руб\r\n'),
(7, 'Классический френч ', '4 000 руб\r\n'),
(8, 'Коррекция классического френча ', '3 000 руб\r\n'),
(9, 'Аквариумный дизайн ', '4 500 руб\r\n'),
(10, 'Коррекция ногтей с аквариумным дизайном ', '3 200 руб\r\n'),
(11, 'Наращивание 1 ногтя ', '360 руб\r\n'),
(12, 'Коррекция 1 ногтя ', '300 руб\r\n'),
(13, 'Снятие наращённых ногтей ', '900 руб\r\n'),
(14, 'Снятие 1 ногтя ', '100 руб\r\n'),
(15, 'Био-Коррекция натуральных ногтей под лак ', '2 200 руб\r\n'),
(16, 'Био-Коррекция ногтей с постоянным цветом ', '2 700 руб\r\n'),
(17, 'Био-Укрепление Френч ', '3 000 руб\r\n'),
(18, 'Био-Наращивание натуральных ногтей под лак ', '3 500 руб\r\n'),
(19, 'Снятие Био-геля ', '500 руб\r\n');
-- --------------------------------------------------------
--
-- Структура таблицы `pedicures`
--
CREATE TABLE `pedicures` (
`id` int NOT NULL,
`service` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `pedicures`
--
INSERT INTO `pedicures` (`id`, `service`, `price`) VALUES
(1, 'Классический ', '2 000 руб\r\n'),
(2, 'Комбинированный ', '2 100 руб\r\n'),
(3, 'Аппаратный ', '2 300 руб\r\n'),
(4, 'Экспресс-педикюр ', '1 500 руб\r\n'),
(5, 'Массаж ног ', '600 руб\r\n'),
(6, 'Удаление мозолей/натоптышей ', '250 руб\r\n'),
(7, 'Коррекция вросшего ногтя скобами PodoFix ', '3 000 руб\r\n'),
(8, 'Обработка вросшего ногтя ', '350 руб\r\n'),
(9, 'Полировка ногтей ', '500 руб\r\n');
-- --------------------------------------------------------
--
-- Структура таблицы `varnish_coating`
--
CREATE TABLE `varnish_coating` (
`id` int NOT NULL,
`service` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Дамп данных таблицы `varnish_coating`
--
INSERT INTO `varnish_coating` (`id`, `service`, `price`) VALUES
(1, 'Покрытие лаком Fedua/OPI ', '600 руб\r\n'),
(2, 'Покрытие френч Fedua/OPI ', '800 руб\r\n'),
(3, 'Снятие лака ', '100 руб\r\n'),
(4, 'Покрытие гель-лаком NeoNail/OPI, цвет ', '1 200 руб\r\n'),
(5, 'Покрытие гель-лаком NeoNail/OPI, френч ', '1 500 руб\r\n'),
(6, 'Покрытие гель-лаком NeoNail/OPI, перевёрнутый Френч ', '1 700 руб\r\n'),
(7, 'Снятие гель-лака NeoNail/OPI ', '500 руб\r\n'),
(8, 'Дизайн одного ногтя ', 'от 100 руб\r\n'),
(9, 'Укрепление натуральных ногтей NeoNail/OPI ', '2 300 руб\r\n'),
(10, 'Укрепление натуральных ногтей NeoNail/OPI цветными гелями ', '2 600 руб\r\n'),
(11, 'IBX System ', '1000 руб\r\n'),
(12, 'Лечебное покрытие Vitagel ', '1 000 руб\r\n'),
(13, 'Лечебное покрытие Duri ', '350 руб\r\n');
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `clear_face`
--
ALTER TABLE `clear_face`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `client`
--
ALTER TABLE `client`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `eyebrows_and_eyelashes`
--
ALTER TABLE `eyebrows_and_eyelashes`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `hairdressers_man`
--
ALTER TABLE `hairdressers_man`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `hairdressers_woman`
--
ALTER TABLE `hairdressers_woman`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `manicure`
--
ALTER TABLE `manicure`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `massage`
--
ALTER TABLE `massage`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `nail_extensions`
--
ALTER TABLE `nail_extensions`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `pedicures`
--
ALTER TABLE `pedicures`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `varnish_coating`
--
ALTER TABLE `varnish_coating`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `clear_face`
--
ALTER TABLE `clear_face`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=29;
--
-- AUTO_INCREMENT для таблицы `client`
--
ALTER TABLE `client`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT для таблицы `eyebrows_and_eyelashes`
--
ALTER TABLE `eyebrows_and_eyelashes`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT для таблицы `hairdressers_man`
--
ALTER TABLE `hairdressers_man`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT для таблицы `hairdressers_woman`
--
ALTER TABLE `hairdressers_woman`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=42;
--
-- AUTO_INCREMENT для таблицы `manicure`
--
ALTER TABLE `manicure`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT для таблицы `massage`
--
ALTER TABLE `massage`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT для таблицы `nail_extensions`
--
ALTER TABLE `nail_extensions`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
--
-- AUTO_INCREMENT для таблицы `pedicures`
--
ALTER TABLE `pedicures`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT для таблицы `varnish_coating`
--
ALTER TABLE `varnish_coating`
MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep># Pracktika2
# Назначение проекта
## <NAME>- это общественная, частная организация, которая оказывает услуги косметического характера для женщин и мужчин. В настоящее время актуальна электронная запись на услуги данного заведения. Также оно позволяет совершать следующие действия:
* поикс клиентов
* просмотр инфомации о клиентах
# Минимальные системные требования
* процессор - Intel Core 2 Duo E6600 or AMD Athlon 2 x2 250
* видеокарта - GeForce 8800GT or ATI Radeon x1300
* оперативная память - не менее 1 Гб
* место на накопителе - не менее 100 Мб
* операционная система - не старше Windows 7 SP1 64-bit
# Руководство пользователя
* Установка
* Перейти в репозиторий
* Нажать на кнопку "Clone or Download" и в выпадающем меню выбрать "Download ZIP"
* Найти в папке с загрузками скачанный архив с названием "praktika
* Распаковать архив
* В распакованной папке пройти по пути "...\Praktika\ bin\ Debug\
* В папке Debug найти файл "Praktika.exe
* Запустить данный файл
| d6b47bda804b4dbc7549690f03c6c688bbd1269c | [
"Markdown",
"SQL"
] | 2 | SQL | Mariy21/Pracktika2 | ad80b8478fbda0f30400007093daa3bbe622c783 | e2164a05451da5a368632412b318e2a36728d47b |
refs/heads/main | <file_sep><?php
class crud extends database
{
public function showData()
{
$sql ="SELECT * FROM tb_mahasiswa";
$stmt=$this->koneksi->prepare($sql);
$stmt->execute();
return $stmt;
}
public function insertData($nim, $nama)
{
try
{
$sql="INSERT INTO tb_mahasiswa(nim, nama_mahasiswa) VALUES (:nim, :nama_mahasiswa)";
$stmt=$this->koneksi->prepare($sql);
$stmt->bindParam(":nim",$nim);
$stmt->bindParam(":nama_mahasiswa", $nama);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function detailData($data)
{
# GET DATA
try
{
$sql ="SELECT id_mahasiswa, nim, nama_mahasiswa FROM tb_mahasiswa WHERE id_mahasiswa=:id_mahasiswa";
$stmt=$this->koneksi->prepare($sql);
$stmt->bindParam(":id_mahasiswa",$data);
$stmt->execute();
$stmt->bindColumn(1, $this->id_mahasiswa);
$stmt->bindColumn(2, $this->nim);
$stmt->bindColumn(3, $this->nama_mahasiswa);
$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount()==1):
return true;
else:
return false;
endif;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function detailData_duatest($data)
{
# Sample GET DATA by ID
try
{
$sql ="SELECT id_mahasiswa, nim, nama_mahasiswa FROM tb_mahasiswa WHERE id_mahasiswa=:id_mahasiswa";
$stmt=$this->koneksi->prepare($sql);
$stmt->execute(array(":id_mahasiswa"=>$data));
$this->row=$stmt->fetch(PDO::FETCH_ASSOC);
return $this->row;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function updateData($nim, $nama, $data)
{
try
{
$sql="UPDATE tb_mahasiswa SET nim=:nim, nama_mahasiswa=:nama_mahasiswa WHERE id_mahasiswa=:id_mahasiswa";
$stmt=$this->koneksi->prepare($sql);
$stmt->bindParam(":nim",$nim);
$stmt->bindParam(":nama_mahasiswa",$nama);
$stmt->bindParam(":id_mahasiswa",$data);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function delete ($data)
{
try{
$sql="DELETE FROM tb_mahasiswa WHERE id_mahasiswa=:id_mahasiswa";
$stmt=$this->koneksi->prepare($sql);
$stmt->execute(array("id_mahasiswa"=>$data));
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
}
?><file_sep><?php
class Database
{
private $host="localhost";
private $user="root";
private $pass="";
private $db="codexam";
protected $koneksi;
public function __construct()
{
try
{
$this->koneksi = new PDO("mysql:host=$this->host; dbname=$this->db",$this->user, $this->pass);
$this->koneksi->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $this->koneksi;
}
}
<file_sep><?php
require_once('db.php');
require_once('class.upload.php');
$obj = new upload;
$error = array();
if($_SERVER['REQUEST_METHOD']=='POST')
{
$obj->getImage2('image');
if(!$obj->fileExtension($obj->file_extension, $obj->file_valid)):
array_push($error, "Maaf ektensi file salah");
elseif($obj->fileSize($obj->file_size)):
array_push($error,"Maaf file terlalu besar");
endif;
/* With no rename new image
if(count($error)==0):
if(move_uploaded_file($obj->file_tmp, $obj->file_target)):
if($obj->insertImage($obj->file_name, $obj->image)):
echo "Gambar berhasil di upload";
else:
echo "Gambar gagal di upload";
endif;
else:
echo "Gagal mengunggah gambar";
endif;
endif;
*/
if(count($error)==0):
if(move_uploaded_file($obj->file_tmp,$obj->file_dir.$obj->file_item)):
if($obj->insertImage($obj->file_item, $obj->image)):
echo "Gambar berhasil di upload";
else:
echo "Gambar gagal di upload";
endif;
else:
echo "Gagal mengunggah gambar";
endif;
endif;
}
$obj->getError($error);
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" name="upload" value="upload">
</form>
<table class="table table-bordered">
<tr>
<th>NO</th>
<th>FOTO DB</th>
<th>FOTO BASE64</th>
</tr>
<?php
$data=$obj->imageFetch();
while($row=$data->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><img src="image/<?php echo $row['name']; ?>" width="100px"></td>
<td><img src="<?php echo $row['image']; ?>" width="100px"></td>
</tr>
<?php } $data->closeCursor();?>
</table>
</body>
</html>
<file_sep><?php
class Absensiswa extends Database
{
public function data_Absen($userid)
{
try
{
$sql = "SELECT * FROM absen_masuk WHERE userid=$userid";
$stmt = $this->koneksi->prepare($sql);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function cek_Absenmasuk($userid)
{
try
{
$sql = "SELECT * FROM absen_masuk WHERE tgl_masuk=CURRENT_DATE() AND userid=$userid";
$stmt = $this->koneksi->query($sql);
if($stmt->execute())
{
if($stmt->rowCount()==1)
{
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function cek_Absenkeluar($userid)
{
try
{
$sql = "SELECT * FROM absen_masuk WHERE tgl_keluar=CURRENT_DATE() AND userid=$userid";
$stmt = $this->koneksi->prepare($sql);
$stmt->execute();
if($stmt->rowCount()==1)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function get_idabsen($userid)
{
//mendapatkan id absen berdasarkan id user yang aktif
try
{
$sql = "SELECT id_absen FROM absen_masuk WHERE tgl_masuk=CURRENT_DATE() AND userid=$userid";
$stmt = $this->koneksi->prepare($sql);
$stmt->execute();
$stmt->bindColumn(1,$this->id_absen);
$stmt->fetch(PDO::FETCH_BOUND);
return $this->id_absen?$this->id_absen:''; //akan menghasilkan string kosong jika tidak ada
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function insert_Absenmasuk($userid, $tgl_masuk, $jam_masuk)
{
try
{
$sql = "INSERT INTO absen_masuk(userid, tgl_masuk, jam_masuk) VALUES(:userid,:tgl_masuk, :jam_masuk)";
$stmt = $this->koneksi->prepare($sql);
$stmt->bindParam(":userid",$userid);
$stmt->bindParam(":tgl_masuk",$tgl_masuk);
$stmt->bindParam(":jam_masuk",$jam_masuk);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function update_Absenkeluar($tgl_keluar, $jam_keluar, $id_absen)
{
try
{
$sql = "UPDATE absen_masuk SET tgl_keluar=:tgl_keluar, jam_keluar=:jam_keluar WHERE id_absen=:id_absen";
$stmt = $this->koneksi->prepare($sql);
$stmt->bindParam(":tgl_keluar",$tgl_keluar);
$stmt->bindParam(":jam_keluar",$jam_keluar);
$stmt->bindParam(":id_absen",$id_absen);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function __destruct()
{
return true;
}
}<file_sep>Baca tutorialnya di : https://www.root93.co.id/2021/09/tutorial-php-supaya-user-hanya-bisa-input-sekali.html
<file_sep><?php
require_once('database.php');
require_once('Absenclass.php');
$obj = new Absensiswa;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Absensi masuk siswa</title>
</head>
<body>
<?php
//pertama kita coba dapatkan dulu id absen berdasarkan data useridnya untuk proses update
//jika variabel bernilai kosong maka kita kembalikan ke index
if(empty($obj->get_idabsen(1)))
{
echo
'
<script>
window.alert("Anda harus melakukan absen masuk terlebih dahulu");
window.location.href="index.php";
</script>
';
}
else
{
//Selanjutnya kita cek dulu apakah dia sudah melakukan absen keluar sebelumnya
if($obj->cek_Absenkeluar(1))
{
//jika sudah absen sebelumnya arahkan ke index.php
echo
'
<script>
window.alert("Anda sudah absen keluar hari ini");
window.location.href="index.php";
</script>
';
}
else
{
//tapi jika belum, kita lakukan query ke id user untuk mendapatkan id absen berdasarkan tgl masuk
//jika dia belum melaukan absen masuk maka dia akan dikembalikan ke halaman utama
if($_SERVER['REQUEST_METHOD']=='POST')
{
//format tanggal akan dibuat seperti format di mysql
$tgl_keluar = date('Y-m-d');
$jam_keluar = date('H:i:s');
if($obj->update_Absenkeluar($tgl_keluar,$jam_keluar,$obj->id_absen))
{
echo
'
<script>
window.alert("Anda berhasil absen kelaur hari ini");
window.location.href="index.php";
</script>
';
}
else
{
echo
"
<script>
alert('Anda gagal absen hari ini');
</script>
";
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table style="border: 1px solid #ccc;" width="500px">
<tr>
<td colspan="2">Formulir Absen keluar</td>
</tr>
<tr>
<td>Siap untuk absen ?</td>
<td><input type="submit" name="absen" value="Klik Absen keluar"></td>
</tr>
</table>
</form>
<?php }}?>
</body>
</html><file_sep><?php
class db
{
private $host="localhost";
private $user="root";
private $pass="";
private $db="codexam";
protected $con;
public function __construct()
{
$this->con = new mysqli($this->host, $this->user, $this->pass, $this->db);
if($this->con==false)die('Tidak dapat terhubung ke database'.$this->con->connect_error());
return $this->con;
}
}
class main extends db
{
public function listFakultas()
{
$sql ="SELECT id_fakultas, nama_fakultas FROM fakultas";
$perintah=$this->con->query($sql);
return $perintah;
}
public function listProdi_selectAjax($data)
{
$sql="SELECT id_prodi, nama_prodi FROM prodi WHERE id_fakultas='$data'";
$result=$this->con->query($sql);
while($row=$result->fetch_assoc()):
$dataset[]=$row;
endwhile;
if(!empty($dataset))return $dataset;
}
}
?><file_sep><?php
class upload extends dbh
{
public function insertImage($name, $base)
{
try
{
$sql="INSERT INTO foto (name, image) VALUES(:name,:image)";
$stmt=$this->koneksi->prepare($sql);
$stmt->bindParam(":name",$name);
$stmt->bindParam(":image",$base);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function imageFetch()
{
try
{
$sql="SELECT * FROM foto";
$stmt=$this->koneksi->query($sql);
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function uploadBase64($data)
//method 1
{
$this->file_name=$_FILES[$data]['name'];
$this->file_tmp=$_FILES[$data]['tmp_name'];
$this->file_size=$_FILES[$data]['size'];
$this->file_extension=strtolower(pathinfo($this->file_name, PATHINFO_EXTENSION));
$this->file_valid=array('jpg','jpeg','png');
$this->file_dir="image/";
$this->file_target=$this->file_dir.$this->file_name;
if(in_array($this->file_extension, $this->file_valid)):
$this->image64=base64_encode(file_get_contents($this->file_tmp));
$this->image="data::image/".$this->file_extension.";base64,".$this->image64;
if(move_uploaded_file($this->file_tmp, $this->file_target)):
if($this->insertImage($this->file_name, $this->image)):
return true;
else:
return false;
endif;
endif;
endif;
}
public function getImage2($data)
{
//method 2
# Get information
$this->file_name=$_FILES[$data]['name'];
$this->file_tmp=$_FILES[$data]['tmp_name'];
$this->file_size=$_FILES[$data]['size'];
# get ekteksion
$this->file_extension=strtolower(pathinfo($this->file_name, PATHINFO_EXTENSION));
# get file valid
$this->file_valid=array('jpg','jpeg','png');
#target upload
$this->file_dir="image/";
# upload with target dir and name of file
$this->file_target=$this->file_dir.$this->file_name;
# randon name image store to database if you wanna
$this->file_item=rand(100,100000).".".$this->file_extension;
# get encode to base 64
$this->image64=base64_encode(file_get_contents($this->file_tmp));
# store to database with encode data
$this->image="data::image/".$this->file_extension.";base64,".$this->image64;
}
public function fileExtension($extension, $valid)
{
if(in_array($extension, $valid))
{
return true;
}
else
{
return false;
}
}
public function fileSize($size)
{
if($size>300000)
{
return true;
}
else
{
return false;
}
}
public function getError($data)
{
if(count($data)>0)
{
foreach ($data as $err) {
echo $err;
}
}
}
}
?>
<file_sep><?php
class crud extends database
{
public function prepare($data)
{
$perintah = $this->koneksi->prepare($data);
if(!$perintah)die("Terjadi kesalahan pada prepare statement".$this->koneksi->error);
return $perintah;
}
public function query($data)
{
$perintah = $this->koneksi->query($data);
if(!$perintah)die("Terjadi kesalahan sql".$this->koneksi->error);
return $perintah;
}
public function tampilMahasiswa()
{
$sql ="SELECT id_mahasiswa, nim, nama_mahasiswa FROM tb_mahasiswa";
$perintah=$this->query($sql);
return $perintah;
}
public function insertData($nim, $nama_mahasiswa)
{
$sql="INSERT INTO tb_mahasiswa (nim, nama_mahasiswa) VALUES(?,?)";
if($stmt=$this->prepare($sql)):
$stmt->bind_param("ss",$param_nim, $param_nama);
$param_nim=$nim;
$param_nama=$nama_mahasiswa;
if($stmt->execute()):
return true;
else:
return false;
endif;
endif;
$stmt->close();
}
public function detailData($data)
{
$sql = "SELECT id_mahasiswa, nim, nama_mahasiswa FROM tb_mahasiswa WHERE id_mahasiswa=?";
if($stmt=$this->prepare($sql)):
$stmt->bind_param("i",$param_data);
$param_data=$data;
if($stmt->execute()):
$stmt->store_result();
$stmt->bind_result($this->id_mahasiswa, $this->nim, $this->nama_mahasiswa);
$stmt->fetch();
if($stmt->num_rows==1):
return true;
else:
return false;
endif;
endif;
endif;
$stmt->close();
}
public function updateData($nim, $nama, $data)
{
$sql="UPDATE tb_mahasiswa SET nim=?, nama_mahasiswa=? WHERE id_mahasiswa=?";
if($stmt=$this->prepare($sql)):
$stmt->bind_param("ssi",$param_nim, $param_nama, $param_data);
$param_nim=$nim;
$param_nama=$nama;
if($stmt->execute()):
return true;
else:
return false;
endif;
endif;
$stmt->close();
}
public function deleteData($data)
{
$sql="DELETE FROM tb_mahasiswa WHERE id_mahasiswa=?";
if($stmt=$this->prepare($sql)):
$stmt->bind_param("i",$param_data);
$param_data=$data;
if($stmt->execute()):
return true;
else:
return false;
endif;
endif;
$stmt->close();
}
}<file_sep><?php
class database
{
private $host="localhost";
private $user="root";
private $pass="";
private $db="codexam";
protected $koneksi;
public function __construct()
{
$this->koneksi = new mysqli($this->host, $this->user, $this->pass, $this->db);
if($this->koneksi==false)die("Tidak dapart tersambung ke database".$this->koneksi->connect_error());
return $this->koneksi;
}
}
?><file_sep><?php
require_once ('db.php');
$obj = new main;
if(!empty($_GET['id_fakultas'])){
$data = $_GET['id_fakultas'];
$result=$obj->listProdi_selectAjax($data);
?>
<option value="">Pilih Prodi</option>
<?php foreach ($result as $prodi) { ?>
<option value="<?php echo $prodi["id_prodi"]; ?>"><?php echo $prodi["nama_prodi"]; ?></option>
<?php }} ?>
?><file_sep>
<?php
require_once ('database.php');
require_once ('sql.php');
$obj = new crud;
if($_SERVER['REQUEST_METHOD']=='POST'):
$nim = $_POST['nim'];
$nama = $_POST['nama_mahasiswa'];
if($obj->insertData($nim, $nama)):
echo '<div class="alert alert-success">Data berhasil disimpan</div>';
else:
echo '<div class="alert alert-danger">Data berhasil disimpan</div>';
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<title>Tutorial PHP : CRUD PDO PHP</title>
<link href="../assets/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link href="../assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="card shadow mb-4 mt-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Tutotrial PHP : CRUD PDO OOP PHP - ROOT93.CO.ID</h6>
</div>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="card-body">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>NIM :</label>
<input type="text" class="form-control" name="nim"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>NAMA MAHASISWA :</label>
<input type="text" class="form-control" name="nama_mahasiswa"/>
</div>
</div>
<div class="col-md-4">
<button type="submit" class="mt-4 btn btn-md btn-primary"> Simpan</button>
</div>
</div>
</div>
</form>
<div class="row m-auto">
<table class="table table-bordered">
<tr>
<th>NO</th>
<th>NIM</th>
<th>NAMA MAHASISWA</th>
<th>AKSI</th>
</tr>
<?php
$no=1;
$data=$obj->showData();
if($data->rowCount()>0){
while($row=$data->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $no; ?></td>
<td><?php echo $row['nim']; ?></td>
<td><?php echo $row['nama_mahasiswa']; ?></td>
<td>
<?php echo "<a class='btn btn-sm btn-primary' href='edit.php?id_mahasiswa=".$row['id_mahasiswa']."'>edit</a>"; ?>
<?php echo "<a class='btn btn-sm btn-primary' href='delete.php?id_mahasiswa=".$row['id_mahasiswa']."'>delete</a>"; ?>
</td>
</tr>
<?php $no+=1; } $data->closeCursor();
}else{
echo '
<tr>
<td> Not found</td>
</tr>
';
}
?>
</table>
</div>
</div>
</div>
<script src="../assets/jquery/jquery.min.js"></script>
<script src="../assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html><file_sep><?php
require_once('database.php');
require_once('Absenclass.php');
$obj = new Absensiswa;
$d = $obj->data_Absen(1); //kita set usernya misal punya id satu
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Data Absensi - Tutorial PHP Supaya user hanya bisa input sekali dalam sehari - root93</title>
</head>
<body>
<div style="margin-top: 20px;">
<p> Anggap saja disini user sedang aktif dengan membawa sesion yang berisi idnya <br>
. Jadi kita query berdasarkan iduser pada session</p>
<table border="1" width="500">
<tr>
<th colspan="4">Tutorial PHP - root93</th>
</tr>
<tr>
<th colspan="2"><a href="absen_masuk.php">Absen masuk</a></th>
<th colspan="2"><a href="absen_keluar.php">Absen keluar</a></th>
<tr>
<th>UserId</th>
<th>Tgl Masuk</th>
<th>Jam masuk</th>
<th>Jam Keluar</th>
</tr>
<?php
if($d->rowCount()>0)
{
while($row = $d->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<th><?=$row['userid'];?></th>
<th><?=$row['tgl_masuk'];?></th>
<th><?=$row['jam_masuk'];?></th>
<th><?=$row['jam_keluar'];?></th>
</tr>
<?php }}?>
</table>
</div>
</body>
</html><file_sep>
<?php
require_once ('db.php');
$obj = new main;
?>
<!DOCTYPE html>
<html>
<head>
<title>Menyederhanakan Input</title>
<link href="../assets/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link href="../assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<script type="text/javascript">
function getprodi(){
var str='';
var val=document.getElementById('list-fakultas');
for(i=0; i<val.length; i++){
if(val[i].selected){
str += val[i].value + ',';
}
}
var str=str.slice(0, str.length -1);
$.ajax({
type:"GET",
url:"ajax_get_prodi.php",
data:'id_fakultas='+str,
success:function(data){
$("#list-prodi").html(data);
}
});
}
</script>
<div class="container">
<div class="card shadow mb-4 mt-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Tutotrial PHP : Menampilkan Option Lain Saat Salah Satu Option Dipilih - ROOT93.CO.ID</h6>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<select class="form-control" name="fakultas" id="list-fakultas" onChange="getprodi();">
<option value="">Pilih fakultas</option>
<?php
$fakultas=$obj->listFakultas();
while($row=$fakultas->fetch_array()){
echo'
<option value="'.$row['id_fakultas'].'">
'.$row['nama_fakultas'].'
</option>
';
}
$fakultas->free_result();
?>
</select>
</div>
<div class="col-md-6">
<select class="form-control" name="prodi" id="list-prodi" size="5">
</select>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/jquery/jquery.min.js"></script>
<script src="../assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Sep 06, 2021 at 08:20 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `codexam`
--
-- --------------------------------------------------------
--
-- Table structure for table `absen_masuk`
--
CREATE TABLE `absen_masuk` (
`id_absen` int(11) UNSIGNED NOT NULL COMMENT 'id absensi',
`userid` int(10) NOT NULL COMMENT 'user id pengguna',
`tgl_masuk` date DEFAULT NULL COMMENT 'tanggal absen',
`jam_masuk` time DEFAULT NULL COMMENT 'jam absen masuk',
`tgl_keluar` date DEFAULT NULL,
`jam_keluar` time DEFAULT NULL COMMENT 'jam pulang kerja'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `absen_masuk`
--
INSERT INTO `absen_masuk` (`id_absen`, `userid`, `tgl_masuk`, `jam_masuk`, `tgl_keluar`, `jam_keluar`) VALUES
(1, 1, '2021-09-05', '22:12:45', NULL, NULL),
(2, 1, '2021-09-06', '08:15:12', '2021-09-06', '08:15:22');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `absen_masuk`
--
ALTER TABLE `absen_masuk`
ADD PRIMARY KEY (`id_absen`),
ADD KEY `id_absen` (`id_absen`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `absen_masuk`
--
ALTER TABLE `absen_masuk`
MODIFY `id_absen` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'id absensi', AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
require_once('database.php');
require_once('Absenclass.php');
$obj = new Absensiswa;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Absensi masuk siswa</title>
</head>
<body>
<?php
# Sebelum kita menampilkan formulir, kita cek dulu apakah dia sudah absen sebelumnya
if($obj->cek_Absenmasuk(1))
{
//jika sudah absen sebelumnya arahkan ke index.php
echo
'
<script>
window.alert("Anda sudah absen hari ini");
window.location.href="index.php";
</script>
';
}
else
{
//jika belum, tampilkan formulirnya
if($_SERVER['REQUEST_METHOD']=='POST')
{
//format tanggal akan dibuat seperti format di mysql
$tgl_masuk = date('Y-m-d');
$jam_masuk = date('H:i:s');
if($obj->insert_Absenmasuk(1,$tgl_masuk, $jam_masuk))
{
echo
'
<script>
window.alert("Anda berhasil absen hari ini");
window.location.href="index.php";
</script>
';
}
else
{
echo
"
<script>
alert('Anda gagal absen hari ini');
</script>
";
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table style="border: 1px solid #ccc;" width="500px">
<tr>
<td colspan="2">Formulir Absen masuk</td>
</tr>
<tr>
<td>Siap untuk absen ?</td>
<td><input type="submit" name="absen" value="Klik Absen"></td>
</tr>
</table>
</form>
<?php }?>
</body>
</html><file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Dec 25, 2020 at 01:29 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `codexam`
--
-- --------------------------------------------------------
--
-- Table structure for table `tb_mahasiswa`
--
CREATE TABLE `tb_mahasiswa` (
`id_mahasiswa` int(10) NOT NULL,
`nim` varchar(10) NOT NULL,
`nama_mahasiswa` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `tb_mahasiswa`
--
INSERT INTO `tb_mahasiswa` (`id_mahasiswa`, `nim`, `nama_mahasiswa`) VALUES
(12, '10256874', '<NAME>'),
(13, '10256875', '<NAME>'),
(14, '10256876', 'Rudi Alamsyah'),
(15, '10256877', 'Sinta Oktasari'),
(16, '10256878', '<NAME>'),
(17, '10256879', 'Sari Purnama');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tb_mahasiswa`
--
ALTER TABLE `tb_mahasiswa`
ADD PRIMARY KEY (`id_mahasiswa`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tb_mahasiswa`
--
ALTER TABLE `tb_mahasiswa`
MODIFY `id_mahasiswa` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>
<?php
require_once ('database.php');
require_once ('sql.php');
$obj = new crud;
if(!$obj->detailData($_GET['id_mahasiswa'])) die("Error : id mahasiswa tidak ada");
if($_SERVER['REQUEST_METHOD']=='POST'):
if($obj->delete($obj->id_mahasiswa)):
echo '<div class="alert alert-success">Data berhasil dihapus</div>';
else:
echo '<div class="alert alert-danger">Data berhasil disimpan</div>';
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<title>Tutorial PHP : CRUD OOP PHP</title>
<link href="../assets/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link href="../assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="card shadow mb-4 mt-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Tutotrial PHP : CRUD PDO OOP PHP - ROOT93.CO.ID</h6>
</div>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<div class="card-body">
<button type="submit" class="mt-4 btn btn-md btn-primary">Delete</button>
<a href="index.php" class="mt-4 btn btn-md btn-primary">Kembali</a>
</div>
</form>
</div>
</div>
<script src="../assets/jquery/jquery.min.js"></script>
<script src="../assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html> | dcaa63b6a41b9ebbf854b248755516abc898179d | [
"Markdown",
"SQL",
"PHP"
] | 18 | PHP | myroot593/codexam | 3482e086f59d8f557454a6f59332f09be7094a7f | 8e6028e1563b8d2ccc7025d403358c728dcb3f26 |
refs/heads/master | <repo_name>d-robertson/express-pokedex<file_sep>/public/js/pokemon-ajax.js
$(document).ready(function(){
$('.pokemonDelete').click(function(e){
e.preventDefault();
var that = this;
console.log($(this).prev().html());
$.ajax({
url: '/pokemon/' + $(this).prev().html(),
method: 'DELETE',
success: function(){
$(that).parent().remove();
}
});
});
$('.home').click(function(e){
e.preventDefault();
});
});<file_sep>/controllers/pokemon.js
var express = require('express');
var router = express.Router();
var db = require('../models');
// GET - return a page with favorited Pokemon
router.get('/', function(req, res) {
db.pokemon.findAll().then(function(pokemon){
res.render('pokemon.ejs', { pokemon: pokemon})
});
});
// POST - receive the name of a pokemon and add it to the database
router.post('/', function(req, res) {
db.pokemon.create(req.body).then(function(){
res.redirect('/pokemon');
});
});
router.delete('/:name', function(req, res){
db.pokemon.destroy({
where: {
name: req.params.name
}
}).then(function(){
res.status(200).send('success');
});
});
module.exports = router;
| 64fbbc5f7ceb3dcb6a282af05fc70cb05f6e9434 | [
"JavaScript"
] | 2 | JavaScript | d-robertson/express-pokedex | e08fe9fb4407a995d934ef93f71bbec8b86c1674 | 7da81ccdd500ef51543744539c2fb1854488e35b |
refs/heads/master | <repo_name>xamanu/xmpp-server<file_sep>/build/filer/Dockerfile
FROM debian:stretch-slim
EXPOSE 5050
VOLUME ["/app/uploads"]
ENV DEBIAN_FRONTEND noninteractive
# Install xmpp-filer
RUN apt-get update --yes && apt-get install --yes wget
RUN wget -q https://github.com/xamanu/xmpp-filer/raw/compiled/xmpp-filer -O /app/xmpp-filer
RUN chmod +x /app/xmpp-filer
COPY files/config.toml /app/config.toml
COPY files/start.sh /start.sh
# Clean up
RUN apt-get purge wget --yes && apt-get autoremove --yes && apt-get clean && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# TOOD: Implement regular (cron) job to automatically purge and clean up old files.
WORKDIR /app
CMD [ "/start.sh" ]
<file_sep>/build/prosody/README.md
Docker image for XMPP Prosody
======================
Prosody is a server for [XMPP](https://xmpp.org) - open technology for real-time communication.
This setup comes out-of-the-box with standard configuration. Only the following environment variables need to be specified:
* `NAME`: A freely chooseable name (required)
* `SECRET`: A freely definable common secret for the components to interact (required)
* `XMPP_ADMIN`: XMPP account of the server's administrator (required)
* `XMPP_SERVER_URL`: Domain for the xmpp server (required)
* `XMPP_GROUPS_URL`: Domain for the group chat (muc) server (required)
* `XMPP_WEBCLIENT_URL`: Domain for the web chat client (required)
* `XMPP_HOST_URLS`: Virtual hosts for xmpp addresses, TLS certificates need to be provided (optional)
You can start this container with one single command:
`docker run --env NAME="My setup" ... xamanu/xmpp-prosody`
This is image part of the easy to setup and full featured [xmpp server configuration](https://github.com/xamanu/xmpp-server) but can be used otherwise.
### Resources
* [Report issues](/issues) and [send Pull Requests](https://github.com/xamany/xmpp-server/pulls) in the [main xmpp-server repository](https://github.com/xamanu/xmpp-server).
### License
This is Free and Open Source Software. Released under the [MIT license](./LICENSE.md). You can use, study share and improve it at your will. Any contribution is highly appreciated. Together we can make the world a better place.
<file_sep>/build/filer/README.md
Docker image for Prosody Filer
======================
Prosody filer is an external http upload service for [XMPP](https://xmpp.org), open technology for real-time communication.
This setup comes out-of-the-box with standard configuration. Only the following environment variable(s) need to be specified:
* `SECRET`: A common secret also specified in the xmmp server configuration, which allows this server to upload.
You can start this container with one single command:
`docker run --env SECRET="<KEY>" xamanu/xmpp-filer` _(of course use your own secret!)_
This is image part of the easy to setup and full featured [xmpp server configuration](https://github.com/xamanu/xmpp-server) but can be used otherwise.
### Resources
* [Report issues](/issues) and [send Pull Requests](https://github.com/xamany/xmpp-server/pulls) in the [main xmpp-server repository](https://github.com/xamanu/xmpp-server).
### License
This is Free and Open Source Software. Released under the [MIT license](./LICENSE.md). You can use, study share and improve it at your will. Any contribution is highly appreciated. Together we can make the world a better place.
<file_sep>/build/conversejs/Dockerfile
FROM debian:stretch-slim
ENV DEBIAN_FRONTEND noninteractive
# Add dependencies
RUN apt-get update --yes && apt-get install --yes curl nginx python-twisted python-openssl
# Setup and install conversejs (https://conversejs.org)
WORKDIR /tmp
# Download the conversejs app
RUN curl -L https://github.com/jcbrand/converse.js/archive/v0.9.5.tar.gz -o /tmp/conversejs_v0.9.5.tar.gz && \
echo "94ea63c2fea4fd73e0c3f9fc8f48f2373da8b631 /tmp/conversejs_v0.9.5.tar.gz" | sha1sum -c - && \
tar xfv /tmp/conversejs_v0.9.5.tar.gz && rm -f /tmp/conversejs_v0.9.5.tar.gz
# Clean up
RUN apt-get purge --yes curl && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Move everything in its place
RUN cp /tmp/converse.js-*/css/converse.min.css /usr/share/nginx/html/ && \
cp /tmp/converse.js-*/builds/converse.min.js /usr/share/nginx/html/ && \
rm /etc/nginx/conf.d/*
# Place configuration
COPY files/index.html /usr/share/nginx/html/
COPY files/site.conf /etc/nginx/conf.d/
COPY files/start.sh /start.sh
ENTRYPOINT ["/start"]
<file_sep>/build/prosody/files/conf/virtual-hosts.cfg.lua
-- Standard host
VirtualHost ("{{XMPP_SERVER_URL}}")
ssl = {
certificate = "/etc/prosody/certs/{{XMPP_SERVER_URL}}.crt";
key = "/etc/prosody/certs/{{XMPP_SERVER_URL}}.key";
}
disco_items = {
{ "{{XMPP_GROUPS_URL}}", "A group chat (muc) service" };
}
-- Virtual hosts (optional)
<file_sep>/build/prosody/files/conf/components.cfg.lua
-- Set up a MUC (multi-user chat) room server:
Component ("{{XMPP_GROUPS_URL}}") "muc"
name = "Groups"
muc_log_by_default = true; -- Enable logging by default (can be disabled in room config)
muc_log_all_rooms = true; -- set to true to force logging of all rooms
max_history_messages = 30;
restrict_room_creation = false
modules_enabled = {
"muc_mam"; -- Store mucs' chat history server sided.
"vcard_muc"; -- Avatars for group chats
}
ssl = {
key = "/etc/prosody/certs/{{XMPP_GROUPS_URL}}.key";
certificate = "/etc/prosody/certs/{{XMPP_GROUPS_URL}}.crt";
}
<file_sep>/docs/dns.md
# DNS
Basically you need one A record pointing to the server and a couple of CNAME records for each additional subdomain we need (for group chat and the web client) pointing to the domain of the server:
```
XMPP_SERVER_URL. A XXX.XXX.XXX.XXX
XMPP_GROUPS_URL. CNAME XMPP_SERVER_URL.
XMPP_CLIENT_URL. CNAME XMPP_SERVER_URL.
```
In my case I use the same hostname (chat.example.com) for both group chats (MUC) and for the web client Kaiwa, as they work on different ports, there is no problem.
```
XMPP_SERVER_URL. A XXX.XXX.XXX.XXX
XMPP_GROUPS_URL. CNAME XMPP_SERVER_URL.
```
www.XMPP_SERVER_URL A YYY.YYY.YYY.YYY
_Often times and commonly SRV records are used in XMMP. For this setup they are not necessary. However, in case you still want to add them, please see the [official documentation of Prosody](https://prosody.im/doc/dns#srv_records)._<file_sep>/build/conversejs/README.md
Docker image for ConverseJS
======================
ConverseJS is a web client for [XMPP](https://xmpp.org) chat - open technology for real-time communication.
This is image part of the easy to setup and full featured [xmpp server configuration](https://github.com/xamanu/xmpp-server) but can be used otherwise.
### Resources
* [Report issues](/issues) and [send Pull Requests](https://github.com/xamany/xmpp-server/pulls) in the [main xmpp-server repository](https://github.com/xamanu/xmpp-server).
### License
This is Free and Open Source Software. Released under the [MIT license](./LICENSE.md). You can use, study share and improve it at your will. Any contribution is highly appreciated. Together we can make the world a better place.
<file_sep>/README.md
# XMPP server distribution
Easy to setup and full featured [XMPP](https://xmpp.org/) server based on Docker Compose using open technology for real-time communication.
## Idea
Everybody needs an open communication tool without walls and gated communities. This configuration allows you to setup a solid full working jabber/xmpp server without much hassle.
## Components
[Docker](https://www.docker.com/) images containing the [Prosody](https://prosody.im) server and the web client [Converse.js](https://conversejs.org/). It is orchestrated by the reverse proxy [traefik](https://traefik.io) and provides out-of-the-box secure connections with certificates by [Let's Encrypt](https://letsencrypt.org).
## Installation
Before you start, you have to configure your domain's **dynamic name server (DNS) settings**. Basically you need one A record pointing to the server and a couple of CNAME records for each additional subdomain we need (for group chat and the web client) pointing to the domain of the server:
```
xmpp.example.com. A XXX.XXX.XXX.XXX (XMPP_SERVER_URL)
conference.xmpp.example.com. CNAME xmpp.example.com. (XMPP_GROUPS_URL)
chat.example.com. CNAME xmpp.example.com. (XMPP_WEBCLIENT_URL)
```
After this, you can **install the xmpp server** just with a few easy steps:
* Make sure you have recent versions [Docker](https://docs.docker.com/) and [Docker Compose](https://docs.docker.com/compose/) working.
* Copy over the [configuration file](./env-example) and edit it: `cp env-example .env`
* Run docker compose to spin it all up: `docker-compose up -d`
Done.
## Variables
Only some variables you have to specify in the [configuration file](./env-example).
* `NAME`: A freely chooseable name (required)
* `SECRET`: A freely definable common secret for the components to interact (required)
* `XMPP_ADMIN`: XMPP account of the server's administrator (required)
* `XMPP_SERVER_URL`: Domain for the xmpp server (required)
* `XMPP_GROUPS_URL`: Domain for the group chat (muc) server (required)
* `XMPP_WEBCLIENT_URL`: Domain for the web chat client (required)
* `XMPP_HOST_URLS`: Virtual hosts for xmpp addresses, TLS certificates need to be provided (optional)
### License
This is Free and Open Source Software. Released under the [MIT license](./LICENSE.md). You can use, study share and improve it at your will. Any [contribution](./CONTRIBUTING.md) is highly appreciated. Only together we can make the world a better place.
<file_sep>/docs/multiple-domains.md
# Domains
There are basically three options how host your setup and setups the domains and Dynamic Domain Server entries. All of them have advantages and disadvantages, mostly on how the xmpp address is formed and if or if not automatic certificate generation is possible. This is giving you a short overview, so you can take the most suitable decision for yourself before setting anything up:
#### 1. Main domain with automatic certificates
You can run the server on the main domain `example.com`and you get nicely formed user names like `<EMAIL>`. This works perfectly out of the box and all certificates are generated automatically.
The magic trick: Your main domain DNS record must point to the server where the xmpp server is running, and all http/s requests not related to the XMPP server are redirected to `www.example.com`.
To configure this option, just specify the configuration file `.env` accordingly:
```
XMPP_HOST_URL=example.com
XMPP_SERVER_URL=example.com
```
#### 2. Sub-domain
You can also run the server on a subdomain `xmpp.example.com`, but then you have to decide between two constraints:
##### a) Automatic certificate creation
The simple solution is that your users are formed with the sub-domain, like `<EMAIL>`. This works out of the box and all certificates are generated automatically.
To configure this option, just specify the configuration file `.env` accordingly:
```
XMPP_HOST_URL=xmpp.example.com
XMPP_SERVER_URL=xmpp.example.com
```
##### b) You provide the certificate for the main domain
However, if want the server to run on a subdomain `xmpp.example.com` and you still want have to have nicely formed user names like `<EMAIL>` then you have to be in charge of providing this certificate, it can not be created automatically for you.
To configure this option, just specify the configuration file `.env` accordingly:
```
XMPP_HOST_URL=example.com
XMPP_SERVER_URL=xmpp.example.com
```
<file_sep>/docs/users.md
# Manage users
#### Register a new user in one command
docker exec -it xmpp-server_xmpp-server_1 prosodyctl register USERNAME EXAMPLE-DOMAIN.TLD PASSWORD
#### Add user
docker exec -it xmpp-server_xmpp-server_1 prosodyctl adduser USERNAME@EXAMPLE-DOMAIN.TLD
#### Change password
docker exec -it xmpp-server_xmpp-server_1 prosodyctl passwd USERNAME@EXAMPLE-DOMAIN.TLD
#### Delete user
docker exec -it xmpp-server_xmpp-server_1 prosodyctl deluser USERNAME@EXAMPLE-DOMAIN.TLD
<file_sep>/build/prosody/files/conf/prosody.cfg.lua
-- Prosody XMPP Server Configuration
--
---------- Server-wide settings ----------
-- Settings in this section apply to the whole server and are the default settings
-- for any virtual hosts
admins = { "{{XMPP_ADMIN}}" }
-- Paths for data and modules
data_path = "/var/lib/prosody/data"
plugin_paths = { "/usr/lib/prosody-modules" }
-- Enable use of libevent for better performance under high load
-- For more information see: http://prosody.im/doc/libevent
use_libevent = true
-- Disallow to run as a daemon. Necessary in a docker setup.
daemonize = false;
-- Disable account creation by default, for security
-- For more information see http://prosody.im/doc/creating_accounts
allow_registration = false
-- Force clients to use encrypted connections? This option will
-- prevent clients from authenticating unless they are using encryption.
c2s_require_encryption = true
-- Force certificate authentication for server-to-server connections?
-- This provides ideal security, but requires servers you communicate
-- with to support encryption AND present valid, trusted certificates.
-- NOTE: Your version of LuaSec must support certificate verification!
-- For more information see http://prosody.im/doc/s2s#security
s2s_secure_auth = false
-- Many servers don't support encryption or have invalid or self-signed
-- certificates. You can list domains here that will not be required to
-- authenticate using certificates. They will be authenticated using DNS.
--
-- Let's just trust the big guys.
s2s_insecure_domains = { "gmail.com", "googlemail.com" }
-- Even if you leave s2s_secure_auth disabled, you can still require valid
-- certificates for some domains by specifying a list here.
--s2s_secure_domains = { "jabber.org" }
ssl = {
key = "/etc/prosody/certs/{{XMPP_SERVER_URL}}.key";
certificate = "/etc/prosody/certs/{{XMPP_SERVER_URL}}.crt";
}
-- Required for init scripts posix and prosodyctl
pidfile = "/var/run/prosody/prosody.pid"
-- Logging configuration
-- For advanced logging see http://prosody.im/doc/logging
log = {
{levels = {min = "info"}, to = "console"};
};
-- HTTP Settings
-- bind to traditional BOSH port on localhost only, don't use HTTPS
-- as this sits behind a reverse proxy that handles HTTPS.
http_host = "{{XMPP_SERVER_URL}}"
http_external_url = "https://{{XMPP_SERVER_URL}}/"
http_paths = {
bosh = "/_xmpp/http-bind";
register_web = "/_xmpp/register";
websocket = "/_xmpp/websocket"
}
-- Registration settings
-- Allow only one registration every 5 minutes
-- allow_registration = true
-- registration_throttle_max = 1
-- registration_throttle_period = 300
-- register_web_template = "/usr/lib/prosody-register-web-template"
-- BOSH and websocket settings
-- cross_domain_bosh = "*";
cross_domain_websocket = true;
consider_websocket_secure = true;
consider_bosh_secure = true
-- MAM
archive_expires_after = "1y"
-- HTTP upload settings
http_upload_external_base_url = "https://{{XMPP_SERVER_URL}}/_xmpp/upload/"
http_upload_external_secret = "{{SECRET}}"
http_upload_external_file_size_limit = 50000000 -- 50 MB
-- Select the authentication backend to use. The 'internal' providers
-- use Prosody's configured data storage to store the authentication data.
-- To allow Prosody to offer secure authentication mechanisms to clients, the
-- default provider stores passwords in plaintext. If you do not trust your
-- server please see http://prosody.im/doc/modules/mod_auth_internal_hashed
-- for information about using the hashed backend.
authentication = "internal_plain"
storage = {
archive2 = "sql";
}
sql = { driver = "SQLite3", database = "prosody.sqlite3" }
-- Provide information where to contact the administrator
contact_info = {
abuse = { "mailto:{{ADMIN_EMAIL}}", "xmpp:{{ADMIN_XMPP}}" };
admin = { "mailto:{{ADMIN_EMAIL}}", "xmpp:{{ADMIN_XMPP}}" };
};
-- Most of configuration is split up in separate files
Include "modules.cfg.lua";
Include "components.cfg.lua";
Include "virtual-hosts.cfg.lua";
-- Include configuration to be added if needed (for example for more hosts)
Include "conf.d/*.cfg.lua";
<file_sep>/build/prosody/files/conf/modules.cfg.lua
-- This is the list of modules Prosody will load on startup.
-- Documentation on modules can be found at: http://prosody.im/doc/modules
modules_enabled = {
-- General server modules
"version"; -- Replies to server version requests
"uptime"; -- Report how long server has been running
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"saslauth"; -- Authentication for clients and servers.
"tls"; -- Add support for secure TLS on connections
"dialback"; -- s2s dialback support
"disco"; -- Service discovery
"posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
"http_upload_external"; -- Upload files to a server and share with others.
"bosh"; -- Enable BOSH ("XMPP over HTTP") for web clients
-- "websocket"; -- Websockets are cool, but probably not ready, yet.
-- "http_files"; -- Serve static files from a directory over HTTP
-- Admin interface modules
-- "admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands
-- "admin_telnet"; -- Opens telnet console interface on localhost port 5582
-- User modules
"roster"; -- Allow users to have a roster.
"vcard"; -- Allow users to set vCards
"private"; -- Private XML storage (for room bookmarks, etc.)
"offline"; -- Store offline messages
"blocklist"; -- Support privacy lists
"blocking"; -- Allow users to block communications with other users
-- "pep"; -- Enables users to publish their mood, activity, playing music and more
"pep_simple"; -- Old pep implementation, until omemo_all_access supports it
"mam"; -- Store chat history server sided.
--"groups"; -- Shared roster support
--"announce"; -- Send announcement to all online users
--"motd"; -- Send a message to users when they log in
-- Registration modules
"register"; -- Allow users to register on this server using a client and change passwords
"register_web"; -- Allow users to register online
"watchregistrations"; -- Alert admins of registrations
--"welcome"; -- Welcome users who register accounts
-- Community modules (let's have a modern chat server)
"auto_answer_disco_info"; -- Answers disco#info queries on the behalf of the recipient
"cache_c2s_caps"; -- Cache caps on user sessions
"carbons"; -- Syncing of messages between compatible devices
"csi"; -- Drop "less urgent" stanzas for mobile to save energy
"csi_battery_saver"; -- Hold unimportant stanzas until client comes online.
"cloud_notify"; -- "Push notifcations" for new messages
"graceful_shutdown"; -- Experiment in improving the shutdown experience
"invite"; -- Allows users to invite new users
"omemo_all_access"; -- Allow encryption with unaccepted accounts
"pep_vcard_avatar"; -- Advice other clients about changes of the avatar
"s2s_keepalive"; -- Keepalive s2s connections
"server_contact_info"; -- Advertise various contact addresses for your XMPP service
"smacks"; -- Support for unstable (mobile) Networks
"smacks_offline"; -- Optimize for clients that implement "mam"
"smacks_noerror"; -- Optimize for clients that implement "mam"
}<file_sep>/build/filer/files/start.sh
#!/usr/bin/env bash
if [ -z "${SECRET}" ]; then
echo "Failure starting prosody-filer: The environment variable SECRET must be set."
else
sed -i "s#{{SECRET}}#${SECRET}#" /app/config.toml
exec ./xmpp-filer
fi<file_sep>/build/prosody/Dockerfile
FROM debian:buster-slim
VOLUME ["/etc/prosody"]
VOLUME ["/var/lib/prosody"]
# 5000/tcp: mod_proxy65
# 5222/tcp: client to server
# 5223/tcp: deprecated, SSL client to server
# 5269/tcp: server to server
# 5280/tcp: http server (bosh, http_upload, etc.)
# 5347/tcp: XMPP component
EXPOSE 5222 5223 5269 5280
ENV DEBIAN_FRONTEND noninteractive
# Add backports repository
RUN printf "deb http://deb.debian.org/debian buster-backports main main non-free" > /etc/apt/sources.list.d/backports.list
# Install software
RUN apt-get update --yes && apt-get install -y --no-install-recommends \
bash \
lsb-base \
procps \
adduser \
libidn11 \
libicu63 \
libssl1.1 \
lua-bitop \
lua-dbi-mysql \
lua-dbi-postgresql \
lua-dbi-sqlite3 \
lua-event \
lua-expat \
lua-filesystem \
lua-sec \
lua-socket \
lua-zlib \
lua5.1 \
lua5.2 \
openssl \
ca-certificates \
ssl-cert \
mercurial \
git \
&& apt-get -t buster-backports install prosody \
&& apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Adding additional prosody modules
RUN service prosody stop
WORKDIR /usr/lib/
RUN hg clone https://hg.prosody.im/prosody-modules/
RUN git clone https://github.com/xamanu/prosody-register-web-template.git prosody-register-web-template
RUN mkdir -p /var/run/prosody && chown prosody:prosody /var/run/prosody
# Add necessary scripts
ADD files/start.sh /start.sh
ADD files/dumpcerts.sh /dumpcerts.sh
# Place configuration
RUN mkdir -p /etc/prosody/conf.d && mkdir -p /etc/prosody/certs
COPY files/conf/* /etc/prosody/
#USER prosody
CMD [ "/start.sh" ]
<file_sep>/build/prosody/files/start.sh
#!/bin/sh
# Check if required variables are available
if [ -z "${XMPP_SERVER_URL}" ]; then
echo "Failure starting xmpp server: The environment variable XMPP_SERVER_URL must be set."
elif [ -z "${XMPP_GROUPS_URL}" ]; then
echo "Failure starting xmpp server: The environment variable XMPP_GROUPS_URL must be set."
elif [ -z "${ADMIN_EMAIL}" ]; then
echo "Failure starting xmpp server: The environment variable ADMIN_EMAIL must be set."
elif [ -z "${ADMIN_XMPP}" ]; then
echo "Failure starting xmpp server: The environment variable ADMIN_XMPP must be set."
elif [ -z "${SECRET}" ]; then
echo "Failure starting xmpp server: The environment variable SECRET must be set."
else
echo "Welcome to your xmpp-server"
echo "Main server url: ${XMPP_SERVER_URL}"
echo "HTTP upload endpoint url: ${XMPP_SERVER_URL}/_xmpp/upload"
echo "Multi user chat (MUC) url: ${XMPP_GROUPS_URL}"
# Replace variables in configuration
sed -i "s#{{ADMIN_EMAIL}}#${ADMIN_EMAIL}#" /etc/prosody/prosody.cfg.lua
sed -i "s#{{ADMIN_XMPP}}#${ADMIN_XMPP}#" /etc/prosody/prosody.cfg.lua
sed -i "s#{{XMPP_SERVER_URL}}#${XMPP_SERVER_URL}#" /etc/prosody/prosody.cfg.lua
sed -i "s#{{XMPP_SERVER_URL}}#${XMPP_SERVER_URL}#" /etc/prosody/components.cfg.lua
sed -i "s#{{XMPP_GROUPS_URL}}#${XMPP_GROUPS_URL}#" /etc/prosody/components.cfg.lua
sed -i "s#{{XMPP_SERVER_URL}}#${XMPP_SERVER_URL}#" /etc/prosody/virtual-hosts.cfg.lua
sed -i "s#{{XMPP_GROUPS_URL}}#${XMPP_GROUPS_URL}#" /etc/prosody/virtual-hosts.cfg.lua
sed -i "s#{{SECRET}}#${SECRET}#" /etc/prosody/prosody.cfg.lua
mkdir -p /tmp/certs && mkdir -p /etc/prosody/certs
# Prepare certificates to be in the default location where prosody expects them
if [ -f /cert/acme.json ]; then
/dumpcerts.sh /cert/acme.json /tmp/certs
mv /tmp/certs/certs/${XMPP_SERVER_URL}.crt /tmp/certs/private/${XMPP_SERVER_URL}.key /etc/prosody/certs/
mv /tmp/certs/certs/${XMPP_GROUPS_URL}.crt /tmp/certs/private/${XMPP_GROUPS_URL}.key /etc/prosody/certs/
fi
# Eventually add virtual hosts
for host in ${XMPP_HOST_URLS}; do
echo "Virtual host for: ${host}"
if [ -f /tmp/certs/certs/${host}.crt ]; then
mv /tmp/certs/certs/${host}.crt /tmp/certs/private/${host}.key /etc/prosody/certs/
fi
echo 'VirtualHost ("'${host}'")' >> /etc/prosody/virtual-hosts.cfg.lua
echo ' http_external_url = "https://'${XMPP_SERVER_URL}'/"' >> /etc/prosody/virtual-hosts.cfg.lua
echo ' ssl = {' >> /etc/prosody/virtual-hosts.cfg.lua
echo ' certificate = "/etc/prosody/certs/'${host}'.crt";' >> /etc/prosody/virtual-hosts.cfg.lua
echo ' key = "/etc/prosody/certs/'${host}'.key";' >> /etc/prosody/virtual-hosts.cfg.lua
echo ' }' >> /etc/prosody/virtual-hosts.cfg.lua
echo ' disco_items = {' >> /etc/prosody/virtual-hosts.cfg.lua
echo ' { "'${XMPP_GROUPS_URL}'", "A group chat (muc) service" };' >> /etc/prosody/virtual-hosts.cfg.lua
echo ' }' >> /etc/prosody/virtual-hosts.cfg.lua
echo '' >> /etc/prosody/virtual-hosts.cfg.lua
done
# Make sure everything has the right owner
chown -R prosody:prosody /etc/prosody/certs
chown -R prosody:prosody /var/lib/prosody/data
# Go jabber go
prosodyctl start
fi
| 2f0d6c95ae4f553e11d16d53bf8f035dd5cf550a | [
"Markdown",
"Dockerfile",
"Shell",
"Lua"
] | 16 | Dockerfile | xamanu/xmpp-server | 8d1e646d2a512488728f971ac52ff6515520a6de | 5068b5dddcaaec097e4a65f479dcd0265f0efbec |
refs/heads/master | <repo_name>suchifan/base6-1<file_sep>/README.md
# base6-1
1. 编写函数,函数功能是:将小写英文字母变为对应的大写字母,要求输入输出均在主函数中完成。样例输入:a 样例输出:A<file_sep>/base6-1/main.cpp
//
// main.cpp
// base6-1
//
// Created by suchao on 4/24/18.
// Copyright © 2018 cs.nju. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
cout << "input:\n";
char lowcase;
cin >> lowcase;
cout << (char) (lowcase + 'A' - 'a') << endl;
return 0;
}
| c78c3a75fb444e3d73d0596b06a35bcfd0722526 | [
"Markdown",
"C++"
] | 2 | Markdown | suchifan/base6-1 | 4eee256f1cef23c3070ee2834c291a463a935384 | e8bccebade2e08f0b006995ca46966f9e9804e6a |
refs/heads/master | <repo_name>KeitaMoromizato/types-assert-loader<file_sep>/README.md
# types-assert loader for webpack
Using [types-assert](https://github.com/KeitaMoromizato/types-assert) in browser.
## Install
```
$ npm i types-assert-loader -D
```
## How To Use
`webpack.config`.
```
{
module: {
loaders: [
{ test: /\.ts$/, loader: "types-assert" }
]
}
}
```
Using TypeScript type definition files.
`type.ts`
```ts
interface Interface1 {
stringProp: string;
numProp: number;
}
```
```
import { assert } from 'types-assert/assert';
import { Interface1 } from './type.ts';
const obj1 = {
stringProp: "hoge",
numProp: "2"
};
assert(obj1, Interface1);
// => throw Error!!
```
## License
MIT
<file_sep>/index.js
var compileFromString = require('types-assert/compiler').compileFromString;
module.exports = function(content) {
return 'module.exports = ' + JSON.stringify(compileFromString(content));
};
| f49f0ebe88b07fe6bb96371476fe543a67630573 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | KeitaMoromizato/types-assert-loader | 22b7f0c025f6b19c2f1b2114887ecedb0dd153b8 | ea2d6eb38a8521f5605376e31c82be729b899861 |
refs/heads/master | <repo_name>K1Z0L/airodump<file_sep>/main.cpp
#include "main.h"
IRH *rhdr;
IH *hdr;
int cnt = 0;
vector<BEACON> v;
void usage(void){
puts("syntax : airodump <interface>");
puts("sample : airodump wlan1");
}
void print_mac(uint8_t *mac_addr){
for(int i=0;i<MAC_SIZE-1;i++){
printf("%02X:", mac_addr[i]);
}
printf("%02X", mac_addr[MAC_SIZE-1]);
}
void print_state(void){
printf("\033[H\033[J\n");
puts(" BSSID PWR Beacons #Data, #/s CH MB ENC CIPHER AUTH ESSID");
puts("");
for(auto tmp: v){
printf(" ");
print_mac(tmp.bss_id);
printf(" %03d ", tmp.beacons);
if(tmp.channels){
printf("%2d", tmp.channels);
}
else{
printf(" ");
}
printf(" ");
if(tmp.essid_set){
printf("%s", tmp.ess_id);
}
printf("\n");
}
}
void analyze(const u_char* packet, int length){
rhdr = (IRH*)packet;
hdr = (IH*)(packet+rhdr->it_len);
uint8_t* lan_data = (uint8_t*)(packet+rhdr->it_len+sizeof(IH)+12);
if(hdr->subtype == 0x80){
int check = 1;
for(int i=0; i<v.size();i++){
if(!memcmp(v[i].bss_id, hdr->bss_id, MAC_SIZE)){
check = 0;
v[i].beacons++;
int idx = rhdr->it_len+sizeof(IH)+12;
while(idx < length){
uint8_t num = packet[idx++];
int len = packet[idx++];
if(idx + len >= length) break;
if(num == 0){
v[i].essid_set = true;
memcpy(v[i].ess_id, packet+idx, len);
}
else if(num == 3){
v[i].channels = packet[idx];
}
idx += len;
}
}
}
if(check){
BEACON now;
memcpy(now.bss_id, hdr->bss_id, MAC_SIZE);
now.beacons = 1;
now.data = 0;
now.channels = 0;
int idx = rhdr->it_len+sizeof(IH)+12;
while(idx < length){
uint8_t num = packet[idx++];
int len = packet[idx++];
if(idx + len >= length) break;
if(num == 0){
now.essid_set = true;
memcpy(now.ess_id, packet+idx, len);
}
else if(num == 3){
now.channels = packet[idx];
}
idx += len;
}
v.push_back(now);
}
}
print_state();
}
int main(int argc, char* argv[]){
if(argc != 2){
usage();
return 0;
}
char* dev = argv[1];
char err_buf[PCAP_ERRBUF_SIZE] = { 0 };
pcap_t *handle = pcap_open_live(dev, BUFSIZ, 1, 1000, err_buf);
if(handle == nullptr){
fprintf(stderr, "couldn't open device(%s)(%s)\n", dev, err_buf);
return 0;
}
while(1){
print_state();
struct pcap_pkthdr* header;
const u_char* packet;
int res = pcap_next_ex(handle, &header, &packet);
if(res == 0){
continue;
};
if(res == -1 || res == -2){
printf("pcap_next_ex return %d(%s)\n", res, pcap_geterr(handle));
}
int length = header->caplen;
cnt++;
analyze(packet, length);
}
}
<file_sep>/main.h
#include <stdio.h>
#include <pcap/pcap.h>
#include <libnet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <stdint.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
#define MAC_SIZE 6
typedef struct ieee80211_radiotap_header {
u_int8_t it_version; /* set to 0 */
u_int8_t it_pad;
u_int16_t it_len; /* entire length */
u_int32_t it_present; /* fields present */
} __attribute__((__packed__)) IRH;
typedef struct ieee80211_header {
uint8_t subtype;
uint8_t flags;
uint16_t duration_id;
uint8_t dst_addr[MAC_SIZE];
uint8_t src_addr[MAC_SIZE];
uint8_t bss_id[MAC_SIZE];
uint16_t seq_ctl;
} __attribute__((__packed__)) IH;
typedef struct beacon {
uint8_t bss_id[MAC_SIZE];
int beacons;
int data;
bool essid_set;
char ess_id[256];
int channels;
}BEACON;
<file_sep>/Makefile
all: airodump
airodump: main.o
g++ -o airodump main.o -lpcap
main.o: main.cpp
clean:
rm -f *.o airodump | 6b9057102a9a4c2e438477738e72e7f48d8e730f | [
"Makefile",
"C++"
] | 3 | C++ | K1Z0L/airodump | b63d7d3184e23fefec0f49bbc1a4dc1c643f7313 | f79618a1ae6da6019fe28369008fdaa229fe88ef |
refs/heads/master | <repo_name>Maxx105/shopping_list<file_sep>/client/src/utils/ListAPI.js
import axios from "axios";
const ListAPI = {
getLists: function () {
return axios
.get("/api/user/userLists")
.then((res) => res.data)
.catch((err) => {
if (err.response.status === 401) {
return { message: "Not Signed In", error: true };
}
});
},
getListById: function(id) {
return axios
.get("/api/list/lists/" + id)
.then(res => res.data)
.catch((err) => {
if (err.response.status === 401) {
return { message: "Not Signed In", error: true };
}
});
},
deleteList: function (id) {
return axios
.delete("/api/list/lists/" + id)
.then(res => res.data)
.catch((err) => {
if (err.response.status === 401) {
return { message: "Not Signed In", error: true };
}
});
},
createList: function (list) {
return axios
.post("/api/list/lists", list)
.then((res) => res.data)
.catch((err) => {
if (err.response.status === 401) {
return { message: "Not Signed In", error: true };
}
});
},
// updateById: function (item) {
// return axios
// .put("/api/list/lists", item)
// .then(res => res.data)
// .catch(err => console.log(err.response))
// },
createListItem: function (listItem) {
return axios
.post("/api/list/items", listItem)
.then((res) => res.data)
.catch((err) => {
if (err.response.status === 401) {
return { message: "Not Signed In", error: true };
}
});
},
deleteListItem: function (id) {
return axios
.delete("/api/list/items/" + id)
.then(res => res.data)
.catch((err) => {
if (err.response.status === 401) {
return { message: "Not Signed In", error: true };
}
});
},
updateStyle: function (style) {
return axios
.put("/api/list/items", style)
.then(res => res.data)
.catch((err) => {
if (err.response.status === 401) {
return { message: "Not Signed In", error: true };
}
});
}
};
export default ListAPI;<file_sep>/client/src/pages/Lists.js
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import ListAPI from "../utils/ListAPI";
import List from "../components/List";
import ListAddForm from "../components/ListAddForm";
function Lists(props) {
const [listName, setListName] = useState('');
const [listItems, setListItems] = useState([]);
const [item, setItem] = useState('');
const [quantity, setQuantity] = useState(1);
const [textDecStyle, setTextDecStyle] = useState({});
const { id } = useParams();
useEffect(() => {
loadList()
document.getElementById('quantity').value = "";
}, []);
function loadList() {
ListAPI.getListById(id)
.then(res => {
setListName(res.name);
setListItems(res.items);
})
.catch((err) => console.log(err.response));
}
function handleInputChange(e) {
setItem({[e.target.name]: e.target.value})
}
function handleQuantityChange(e) {
e.preventDefault();
if (parseInt(e.target.value) < 1 ) {
document.getElementById('quantity').value = "1";
}
setQuantity(parseInt(e.target.value));
}
function handleFormSubmit(e) {
e.preventDefault();
setQuantity(1);
setItem('');
document.getElementById('listItem').value = "";
document.getElementById('quantity').value = "";
postItem();
}
function postItem() {
ListAPI.createListItem({
listID: id,
quantity: quantity,
name: item.listItem
})
.then(res => loadList())
.catch((err) => console.log(err.response));
}
function updateStyle(style) {
ListAPI.updateStyle(style)
.then(res => loadList())
.catch((err) => console.log(err.response));
}
function setTextDec(id, style) {
if (!document.getElementById(id).style.textDecoration) {
document.getElementById(id).style.textDecoration = "line-through"
updateStyle({
textDec: "line-through",
id: document.getElementById(id).id
})
} else {
document.getElementById(id).style.textDecoration = ""
updateStyle({
textDec: "",
id: document.getElementById(id).id
})
}
}
return (
<div className="container">
<h1 style={{textAlign: "center"}}>{listName}</h1>
<ListAddForm
onSubmit = {handleFormSubmit}
onChange = {handleInputChange}
onQuantityChange = {handleQuantityChange}
></ListAddForm>
<List
loadList={() => loadList()}
listItems = {listItems}
setTextDec = {setTextDec}
></List>
</div>
);
}
export default Lists;<file_sep>/models/ListItems.js
const mongoose = require("mongoose");
const ListItemsSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
quantity: {
type: Number,
default: 1,
},
textDec: {
type: String,
default: ""
},
listID: {
type: String
}
});
module.exports = mongoose.model("ListItems", ListItemsSchema);<file_sep>/README.md
# Simple Shopping List
Personal Project 01 - Basic Shopping List
Click [here](https://basic-shopping-list.herokuapp.com/) to open the deployed application.
<!--  -->
(image coming soon)
## Description
This is a very simple, user authenticated shopping list that allows you to create/remove lists as well as create/remove items to/from each of those lists. You can also click on the item to cross it out to signify that it is has been selected.
## Table of Contents
* [Technologies](#Technologies)
* [Usage](#Usage)
* [License](#License)
* [Badges](#Badges)
* [Test](#Test)
* [Questions](#Questions)
## Technologies
* This application uses the MERN stack (MongoDB, Express.js, React, Node.js)
* It used the Router component in React.
* Mongoose ORM for database storage.
* It uses CSS/Bootstrap for styling.
* Deployed on Heroku.
* Passport for user authentication.
* JWT for the creation of a webaccess token.
## Usage
If using from the Heroku deployed application, just go to the deployed application's [link](https://basic-shopping-list.herokuapp.com/). Start by creating a user account. At that point, you can create a list name (maybe the name of the store, the date, the type of products, etc.). You can then click on that list and start adding items along with the quantity. You can click on the item to cross it off or you can delete items as well. If running off a local server, first do an npm install then run the server by running the "npm start" command in a gitbash terminal. This will initialize the React app.
## License
MIT
## Badges


## Tests
No tests are currently in place for this project.
## Questions
For any questions, contact me at [<EMAIL>](mailto:<EMAIL>).
#### [](https://github.com/maxx105)
<file_sep>/client/src/Context/AuthContext.js
import React, { createContext, useState, useEffect } from "react";
import AuthAPI from "../utils/AuthAPI";
export const AuthContext = createContext();
export default ({ children }) => {
const [user, setUser] = useState(null);
const [id, setId] = useState(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
AuthAPI.isAuthenticated().then((data) => {
// console.log(data)
setId(data.id);
setUser(data.user);
setIsAuthenticated(data.isAuthenticated);
setIsLoaded(true);
});
}, []);
return (
<div>
{!isLoaded ? (
<div
style={{
height: "100vh",
backgroundImage:
"url(" + process.env.PUBLIC_URL + "/loadingBG.jpg" + ")",
}}
></div>
) : (
<AuthContext.Provider
value={{
user,
setUser,
isAuthenticated,
setIsAuthenticated,
id,
setId
}}
>
{children}
</AuthContext.Provider>
)}
</div>
);
};
<file_sep>/client/src/components/ListOfLists/ListOfLists.js
import React from "react";
import { Link } from "react-router-dom";
import ListAPI from "../../utils/ListAPI";
import "./style.css";
function ListOfLists(props) {
function deleteListName(id) {
ListAPI.deleteList(id)
.then((res) => props.loadLists())
.catch((err) => console.log(err.response));
}
return (
<div>
<ul className="list-group">
{props.lists.map((list) => (
<div className="input-group mb-1" key={list._id}>
<Link to={`/lists/${list._id}`} style={{color: "black"}}>
<li className="list-group-item" id="list-name">{list.name}</li>
</Link>
<div className="input-group-append">
<button type="submit" className="btn btn-danger" onClick={() => deleteListName(list._id)}>
-
</button>
</div>
</div>
))}
</ul>
</div>
);
}
export default ListOfLists;<file_sep>/routes/api/list.js
const express = require("express");
const router = express.Router();
const passport = require("passport");
const listController = require("../../controllers/listController");
const listItemsController = require("../../controllers/ListItemsController");
const path = require("path");
const List = require("../../models/List");
const ListItems = require("../../models/ListItems");
router
.route("/lists")
.get(listController.findAll)
// .post(listController.findOneThenSave);
router
.route("/lists/:id")
.get(listController.findById)
// .post(listController.addItemToList)
.delete(listController.remove);
router
.route("/items")
.get(listItemsController.findAll)
.put(listItemsController.updateStyle)
.post(listItemsController.create);
router
.route("/items/:id")
.get(listItemsController.findById)
.delete(listItemsController.remove);
router.post(
"/lists",
passport.authenticate("jwt", { session: false }),
function (req, res) {
const list = new List(req.body);
list.save((err) => {
if (err) {
res.json({ message: err.message, error: true });
} else {
req.user.lists.push(list);
req.user.save((err) => {
if (err) {
res.json({ message: err.message, error: true });
} else {
res.json({ message: "Successfully created list", error: false });
}
});
}
});
}
);
module.exports = router;<file_sep>/client/src/pages/Home.js
import React, { useState, useEffect, useContext } from "react";
import ListAPI from "../utils/ListAPI";
import { Link } from "react-router-dom";
import { AuthContext } from "../Context/AuthContext";
import CreateListForm from "../components/CreateListForm";
import ListOfLists from "../components/ListOfLists/ListOfLists";
function CreateList() {
const {isAuthenticated} = useContext(AuthContext);
const [listName, setListName] = useState('');
const [lists, setLists] = useState([]);
useEffect(() => {
loadLists()
}, []);
function preLoginHomePage() {
return (
<div>
<Link to="/login">
<h1 className="nav-item nav-h1nk" id="link" style={{textAlign: "center"}}>Login/Register</h1>
</Link>
</div>
);
}
function loadLists() {
ListAPI.getLists()
.then(res => {
setLists(res.lists)
})
.catch((err) => console.log(err.response));
}
function handleInputChange(e) {
setListName({[e.target.name]: e.target.value})
}
function handleFormSubmit(e) {
e.preventDefault();
ListAPI.createList({name: listName.listname})
.then(res => {
loadLists();
})
.catch((err) => console.log(err.response));
document.getElementById('listname').value = "";
}
return (
<div className="container">
{!isAuthenticated ? preLoginHomePage() :
<div>
<CreateListForm
onChange = {handleInputChange}
onSubmit = {handleFormSubmit}
></CreateListForm>
<ListOfLists
lists = {lists}
loadLists={() => loadLists()}
></ListOfLists>
</div>
}
</div>
);
}
export default CreateList;<file_sep>/controllers/listController.js
const List = require("../models/List");
module.exports = {
findAll: function (req, res) {
List
.find(req.query)
.then((dbModel) => res.json(dbModel))
.catch((err) => res.status(422).json(err));
},
findById: function (req, res) {
List
.findById(req.params.id)
.populate("items")
.exec((err, document) => {
if (err) {
res.json({ message: "Error has occurred", error: true });
} else {
res.json(document);
}
})
},
create: function(req, res) {
List
.create(req.body)
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
remove: function (req, res) {
List
.findById({ _id: req.params.id })
.then((dbModel) => dbModel.remove())
.then((dbModel) => res.json(dbModel))
.catch((err) => res.status(422).json(err));
},
updateById: function (req, res) {
List
.findByIdAndUpdate( {_id: req.body.id },
{ "$push": {"items": req.body} })
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
addItemToList: function (req, res) {
const list = new List(req.body);
list.save(err => {
if (err) {
res.json({ message: "Error has occurred", error: true });
} else {
list.items.push(req.body.listID)
}
})
}
}
<file_sep>/client/src/components/List.js
import React from "react";
import ListAPI from "../utils/ListAPI";
function List(props) {
function deleteItem(id) {
ListAPI.deleteListItem(id)
.then(res => props.loadList())
.catch((err) => console.log(err.response));
}
return (
<div>
<h1 style = {{textAlign: "center"}}>{props.listName}</h1>
{props.listItems.map((listItem) => (
<div className="input-group mb-1" key={listItem._id}>
<li className="list-group-item" id={listItem._id} style = {{textDecoration: listItem.textDec}} onClick={() => props.setTextDec(listItem._id, listItem.textDec)} >
{/* <input className="form-check-input me-1" type="checkbox" value="" aria-label="..."/> */}
x{listItem.quantity} {listItem.name}
</li>
<div className="input-group-append">
<button type="submit" className="btn btn-danger" onClick={() => deleteItem(listItem._id)}>
-
</button>
</div>
</div>
))}
</div>
);
}
export default List; | 1150ad754e0278d3e26fa82b2aaf7aa730d4b4f2 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | Maxx105/shopping_list | 29f1a0558398add960c44adff5f3453d61b5a14b | 23ea1922a82c17b2ef2e23fa86e52dd8c173c7cb |
refs/heads/master | <repo_name>sheltonanton/Cricker<file_sep>/app/src/main/java/com/folkscube/auxillary/NoActionBar.java
package com.folkscube.auxillary;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.view.Window;
import android.view.WindowManager;
import static com.folkscube.cricker.R.color.status_bar_color;
/**
* Created by infant-pt1977 on 4/1/2018.
*/
public class NoActionBar {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void execute(Activity a){
Window window = a.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
int color = a.getResources().getColor(status_bar_color);
window.setStatusBarColor(color);
}
}
<file_sep>/app/src/main/java/com/folkscube/cricker/MainActivity.java
package com.folkscube.cricker;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.LoggingBehavior;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.folkscube.auxillary.NoActionBar;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private CallbackManager callbackManager = null;
private MainActivity ma = null;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ma = this;
checkForAlreadyLoggedIn();
NoActionBar.execute(this);
FacebookSdk.sdkInitialize(getApplicationContext());
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
}
AppEventsLogger.activateApp(this);
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile"));
Log.d("MainActivity","Has Obtained the LoginButton");
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("MainActivity","Has been successfuL");
AccessToken accessToken = loginResult.getAccessToken();
if(accessToken!=null){
SharedPreferences preferences = getSharedPreferences("USER_PREF",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("loggedIn",true);
editor.putString("userid",accessToken.getUserId());
editor.putString("token",accessToken.getToken());
editor.commit();
}
Log.d("MainActivity","Has been logged in successfully");
Log.d("MainActivity","USerid: "+accessToken.getUserId());
Intent intent = new Intent(ma,LoadActivity.class);
intent.putExtra("command","LIS");
intent.putExtra("access_token",accessToken);
startActivity(intent);
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
Log.d("MainActivity","Error inside");
}
});
}
protected void checkForAlreadyLoggedIn(){
SharedPreferences preferences = getSharedPreferences("USER_PREF",MODE_PRIVATE);
String userid = preferences.getString("userid",null);
if(userid!=null){
Intent intent = new Intent (ma,LoadActivity.class);
intent.putExtra("command","ALI");
startActivity(intent);
}
}
}
<file_sep>/app/src/main/java/com/folkscube/cricker/PageAActivity.java
package com.folkscube.cricker;
import android.os.Bundle;
import android.widget.TextView;
import com.folkscube.auxillary.NoActionBar;
import com.folkscube.database.Database;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.util.Iterator;
import java.util.Set;
public class PageAActivity extends Database {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_a);
NoActionBar.execute(this);
this.execute("http://192.168.0.106:8080/cricker/home.do?function=get");
}
@Override
public void onPostResponse(String response) {
String output = "";
JSONObject master = null;
try {
master = (JSONObject) new JSONParser().parse(response);
} catch (ParseException e) {
e.printStackTrace();
}
JSONArray array = (JSONArray)master.get("data");
for(int i=0;i<array.size();i++){
JSONObject obj = (JSONObject) array.get(i);
Set<String> set = obj.keySet();
Iterator<String> ite = set.iterator();
while(ite.hasNext()){
String key = ite.next();
output=output+key+":\t";
output=output+obj.get(key);
}
output=output+"\n";
}
TextView text = findViewById(R.id.display_page_a_text);
text.setText(output);
}
} | 8928a4d71ec41ee69c9f058dc820d39c075ec480 | [
"Java"
] | 3 | Java | sheltonanton/Cricker | 0c396d8ecad933447e2be7741d190c690b5913b4 | d9876f30b557ccd1ace1bbfe9268d552d6577365 |
refs/heads/master | <file_sep>Fluent for PHP
============
Programmatic approach to generating and sending responsive user notifications via e-mail
### Benefits ###
- Easy API to generate HTML based e-mail bodies in your app
- Less time wrestling with CSS inlining
- Automatically responsive
### Install ###
```
php composer.phar require fivesqrd/fluent:3.3
```
### Quick Examples ###
Create and send a message:
```
$messageId = Fluent::message()->create()
->setTitle('My little pony')
->addParagraph('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ornare pellentesque neque non rutrum. Sed a sagittis lacus.')
->addNumber(['caption' => 'Today', value => date('j M Y')])
->addButton('http://www.mypony.com', 'Like my pony')
->addParagraph('Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.')
->setTeaser('This is a teaser')
->subject('Testing it')
->header('Reply-To', '<EMAIL>')
->to('<EMAIL>')
->send();
```
Find problematic events related to a user's email adress:
```
$response = \Fluent::event()->find()
->to('<EMAIL>')
->since(date('Y-m-d H:i:s', $timeframe))
->type(['hard_bounce', 'soft_bounce', 'reject'])
->fetch();
```
<file_sep><?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../library'),
get_include_path(),
)));
if (count($argv) != 4) {
echo "Usage: {$argv[0]} <filename> <filetype> <filepath>\n";
exit;
}
list($script, $name, $type, $path) = $argv;
require_once 'Fluent.php';
require_once 'Fluent/Content.php';
require_once 'Fluent/Message.php';
require_once 'Fluent/Transport.php';
require_once 'Fluent/Transport/Remote.php';
Fluent::$defaults = array(
'key' => '9fe630283b5a62833b04023c20e43915',
'secret' => 'test',
'sender' => array('name' => 'ACME', 'address' => '<EMAIL>'),
);
Fluent\Transport\Remote::$endpoint = 'http://localhost/fluent-web-service/v3';
Fluent\Transport\Remote::$debug = true;
try {
$messageId = Fluent::message()
->setTitle('My little pony')
->addParagraph('I love my pony very much.')
->addCallout('http://www.mypony.com', 'Like my pony')
->setTeaser('This is a teaser')
->subject('Testing attachments')
->attach($name, $type, file_get_contents($path))
->to('<EMAIL>')
->send('remote');
echo 'Sent message: ' . $messageId . "\n";
} catch (Fluent\Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
<file_sep><?php
namespace Fluent;
interface Template
{
/**
* @return \Fluent\Content
*/
public function getContent();
}
<file_sep><?php
namespace Fluent\Content;
class Markup
{
protected $_title;
protected $_teaser;
protected $_content;
public function __construct($content = null)
{
$xml = new \DOMDocument();
if ($content) {
$xml->loadXML($content);
} else {
$xml->appendChild(new \DOMElement('content'));
}
$this->_content = $xml->childNodes->item(0);
}
/**
* @param string $text
* @return \Fluent\Content\Markup
*/
public function setTitle($text)
{
$this->_content->appendChild(new \DOMElement('title', htmlentities($text)));
return $this;
}
/**
* @param string $text
* @return \Fluent\Content\Markup
*/
public function addParagraph($text)
{
$element = new \DOMElement('paragraph');
$this->_content->appendChild($element);
$element->appendChild($this->_getCData($text));
return $this;
}
/**
* @param array $numbers Up to 3 number/caption pairs
* @return \Fluent\Content\Markup
*/
public function addNumber(array $numbers)
{
if (array_key_exists('value', $numbers)) {
/* we have been given one number only */
$numbers = array($numbers);
}
$parent = $this->_content
->appendChild(new \DOMElement('numbers'));
foreach ($numbers as $number) {
$element = $this->_getNumberElement(
$parent->appendChild(new \DOMElement('number')), $number
);
}
return $this;
}
protected function _getNumberElement($element, $number)
{
if (array_key_exists('value', $number)) {
$element->appendChild(
new \DOMElement('value', htmlentities($number['value']))
);
}
if (array_key_exists('caption', $number)) {
$element->appendChild(
new \DOMElement('caption', $number['caption'])
);
}
return $element;
}
protected function _getCData($text)
{
return $this->_content->ownerDocument->createCDATASection($text);
}
/**
* @param string $href
* @param string $text
* @return \Fluent\Content\Markup
*/
public function addButton($href, $text)
{
$element = new \DOMElement('button', htmlentities($text));
$this->_content->appendChild($element);
$element->setAttribute('href', $href);
return $this;
}
public function getFormat()
{
return 'markup';
}
/**
* @return string
*/
public function toString()
{
$doc = $this->_content->ownerDocument;
return $doc->saveXml();
}
public function setTeaser($text)
{
$this->_teaser = $text;
return $this;
}
public function getTeaser()
{
return $this->_teaser;
}
public function __toString()
{
return $this->toString();
}
}
<file_sep><?php
use Fluent\Content;
use Fluent\Template;
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../library'),
get_include_path(),
)));
require_once 'Fluent/Email.php';
class MyTemplate extends Fluent\Template
{
const THEME = 'minimal';
protected $_user;
public function __construct($user)
{
/* setup for your content here */
$this->_user = $user;
}
/**
* (non-PHPdoc)
* @see \Fluent\Template::getContent()
* @return \Fluent\Content
*/
public function getContent()
{
$content = new \Fluent\Content(self::THEME);
return $content->setTitle($text)
->addParagraph($text)
->addParagraph($text)
->addCallout($href, $text);
}
}
$message = new Fluent\Message();
$messageId = $message->to($to)
->subject($subject)
->content(new MyTemplate($user))
->send();
<file_sep><?php
namespace Fluent\Storage;
class Sqlite implements \Fluent\Storage
{
/**
* @var \PDO
*/
protected $_adapter;
protected static $_instance;
protected $_path;
public static $path;
/**
* @return Fluent\Storage\Db
*/
public static function getInstance($path = null)
{
if (self::$_instance) {
return self::$_instance;
}
return new self($path);
}
public function __construct($path = null)
{
$path = $this->_getPath($path);
if (!is_dir($path)) {
throw new \Exception('Failed trying to create temporary Fluent message store in: '. $path);
}
$file = $path. '/Fluent-Queue.sqlite3';
$exists = file_exists($file);
$this->_adapter = new \PDO('sqlite:' . $file);
$this->_adapter->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION);
if (!$exists) {
$this->_createSchema($this->_adapter);
chmod($file, 0777);
}
}
protected function _getPath($default)
{
if (!empty($default)) {
$this->_path = $default;
return $this->_path;
}
if (!empty(self::$path)) {
return self::$path;
}
return sys_get_temp_dir();
}
protected function _createSchema(\PDO $db)
{
$db->query('CREATE TABLE messages (id integer primary key autoincrement, sender varchar(255), recipient varchar(255), subject varchar(255), headers varchar(512), content blob, status varchar(255), options varchar(512), created_at datetime, transmitted_at datetime, reference varchar(255), error varchar(255))');
$db->query('CREATE TABLE attachments (id integer primary key autoincrement, message_id int(11), type varchar(255), name varchar(255), content blob)');
}
public function isLocked($mypid)
{
$lockfile = $this->_getPath($this->_path) . '/Fluent-Queue.lock';
if (file_exists($lockfile)) {
$pid = (int) file_get_contents($lockfile);
}
if (!isset($pid) || $pid == 0 || posix_getsid($pid) === false) {
file_put_contents($lockfile, $mypid); // create lockfile
} else {
return true;
}
}
public function persist(\Fluent\Message\Create $message)
{
$properties = $message->toArray();
$data = array(
':sender' => json_encode($properties['sender']),
':recipient' => json_encode($properties['recipient']),
':headers' => json_encode($properties['headers']),
':options' => json_encode($properties['options']),
':subject' => $properties['subject'],
':content' => $properties['content'],
':status' => 'queued',
':created_at'=> date("Y-m-d H:i:s"),
);
$stmt = $this->_adapter->prepare('INSERT INTO messages (sender,recipient,subject,content,headers,options,status,created_at) values (:sender,:recipient,:subject,:content,:headers,:options,:status,:created_at)');
$stmt->execute($data);
$id = $this->_adapter->lastInsertId();
foreach ($properties['attachments'] as $data) {
$stmt = $this->_adapter->prepare('INSERT INTO attachments (message_id,name,type,content) values (:message_id,:name,:type,:content)');
$stmt->execute(array(
':message_id' => $id,
':content' => base64_decode($data['content']),
':name' => $data['name'],
':type' => $data['type']
));
}
return $id;
}
public function delete($messageId)
{
$this->_adapter->query('DELETE FROM attachments WHERE message_id = ' . $this->_adapter->quote($messageId));
$this->_adapter->delete('DELETE FROM messages WHERE id = ' . $this->_adapter->quote($messageId));
}
public function moveToSent($messageId, $reference)
{
$data = array(
':id' => $messageId,
':reference' => $reference,
':status' => 'sent',
':time' => date("Y-m-d H:i:s"),
);
$stmt = $this->_adapter
->prepare('UPDATE messages SET reference = :reference, status = :status, transmitted_at = :time, error = null WHERE id = :id');
$stmt->execute($data);
}
public function moveToFailed($messageId, $error)
{
$data = array(
':id' => $messageId,
':status' => 'failed',
':error' => $error,
':time' => date("Y-m-d H:i:s")
);
$stmt = $this->_adapter
->prepare('UPDATE messages SET status = :status, transmitted_at = :time, error = :error WHERE id = :id');
$stmt->execute($data);
}
public function getMessage($id)
{
$stmt = $this->_adapter
->prepare('SELECT * FROM messages WHERE id = :id');
$stmt->execute(array(':id' => $id));
return $stmt->fetch();
}
public function getQueue()
{
$stmt = $this->_adapter
->prepare('SELECT * FROM messages WHERE status = :status');
$stmt->execute(array(':status' => 'queued'));
return $stmt->fetchAll();
}
public function getAttachments($messageId)
{
$stmt = $this->_adapter
->prepare('SELECT * FROM attachments WHERE message_id = :messageId');
$stmt->execute(array(':messageId' => $messageId));
return $stmt->fetchAll();
}
public function purge($days)
{
$messages = $this->_adapter
->prepare('DELETE FROM messages WHERE status != :status AND messages.created_at < :date');
$messages->execute(array(
':status' => 'queued',
':date' => date("Y-m-d H:i:s", time() - $days * 86400)
));
$attachments = $this->_adapter
->prepare('DELETE FROM attachments WHERE id IN (SELECT a.id FROM attachments a left join messages m on a.message_id = m.id where m.id is null)');
$attachments->execute();
}
}
<file_sep><?php
require_once(__DIR__ . '/bootstrap.php');
if (count($argv) < 2) {
echo "Usage: {$argv[0]} <messageId> [address]\n";
exit;
}
$storage = Fluent\Storage\Sqlite::getInstance();
$message = $storage->getMessage($argv[1]);
$recipient = isset($argv[2]) ? $argv[2] : json_decode($message['recipient'], true);
$response = Fluent::message($message['content'])
->from(json_decode($message['sender'], true))
->to($recipient)
->headers(json_decode($message['headers'], true))
->options(json_decode($message['options'], true))
->subject($message['subject'])
->attachments($storage->getAttachments($message['id']))
->send('remote');
echo date("Y-m-d H:i:s") . ": Delivered '{$message['subject']}' e-mail to " . $recipient . " - {$response}\n";
/*
if ($response) {
$storage->moveToSent($message['id'], $response);
}
*/
<file_sep><?php
namespace Fluent\Transport;
class Remote implements \Fluent\Transport
{
protected $_api;
public function __construct($api)
{
$this->_api = $api;
}
public function send(\Fluent\Message\Create $message)
{
$properties = $message->toArray();
$params = array(
'sender' => $properties['sender'],
'subject' => $properties['subject'],
'recipient' => $properties['recipient'],
'content' => $properties['content'],
'header' => $properties['headers'],
'attachment' => $properties['attachments'],
'option' => $properties['options'],
);
$response = $this->_api->call('message', 'create', $params);
return $response->_id;
}
}
<file_sep><?php
namespace Fluent;
use Fluent\Content as Content;
class Content
{
public static function markup($content = null)
{
return new Content\Markup($content);
}
public static function raw()
{
return new Content\Raw();
}
}
<file_sep><?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../library'),
get_include_path(),
)));
require_once 'Fluent.php';
require_once 'Fluent/Content.php';
require_once 'Fluent/Content/Markup.php';
require_once 'Fluent/Message.php';
require_once 'Fluent/Transport.php';
require_once 'Fluent/Transport/Remote.php';
$text = '<content><paragraph>Imported paragraph</paragraph></content>';
$content = Fluent\Content::markup($text)
->setTitle('Hello Earth & World')
->addParagraph('Hello Paragraph & All')
->addParagraph('<table border="1"><tr><td>Hello Paragraph</td><td>& All</td></tr></table>')
->addCallout('http://www.fluentmsg.com?test=1&another=2', 'Hello Callout & Href');
echo $content->toString();
Fluent::$defaults = array(
'key' => '9fe630283b5a62833b04023c20e43915',
'secret' => 'test',
'sender' => array('name' => 'ACME', 'address' => '<EMAIL>'),
);
if (isset($argv[1])) {
Fluent::message($content)
->to($argv[1])
->from('<EMAIL>')
->subject('Fluent Content Test')
->send('remote');
}
<file_sep><?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../library'),
get_include_path(),
)));
require_once 'Fluent.php';
require_once 'Fluent/Content.php';
require_once 'Fluent/Message.php';
require_once 'Fluent/Transport.php';
require_once 'Fluent/Transport/Remote.php';
Fluent::$defaults = array(
'key' => '9fe630283b5a62833b04023c20e43915',
'secret' => 'test',
'sender' => array('name' => 'ACME', 'address' => '<EMAIL>'),
);
Fluent\Transport\Remote::$endpoint = 'http://localhost/fluent-web-service/v3';
Fluent\Transport\Remote::$debug = true;
try {
$messageId = Fluent::message()
->setRawContent("<p>This is plain text</p> <p>With a twist</p>")
->subject('Testing it raw')
->to('<EMAIL>')
->send('remote');
echo 'Sent message: ' . $messageId . "\n";
} catch (Fluent\Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
<file_sep><?php
namespace Fluent;
interface Storage
{
public function persist(\Fluent\Message\Create $email);
public function delete($messageId);
public function moveToSent($messageId, $reference);
public function moveToFailed($messageId, $error);
public function getQueue();
public function purge($days);
}
<file_sep><?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../library'),
get_include_path(),
)));
require_once 'Fluent.php';
require_once 'Fluent/Api.php';
require_once 'Fluent/Exception.php';
require_once 'Fluent/Content.php';
require_once 'Fluent/Content/Markup.php';
require_once 'Fluent/Message.php';
require_once 'Fluent/Message/Create.php';
require_once 'Fluent/Transport.php';
require_once 'Fluent/Transport/Remote.php';
require_once 'Fluent/Transport/Local.php';
require_once 'Fluent/Storage.php';
require_once 'Fluent/Storage/Sqlite.php';
Fluent::$defaults = array(
//'key' => '9fe630283b5a62833b04023c20e43915',
//'secret' => 'test',
'key' => '60ced422',
'secret' => '<KEY>',
'sender' => array('name' => 'The Acme Company', 'address' => '<EMAIL>'),
'endpoint' => 'http://localhost/fluent/service/v3',
//'endpoint' => 'https://fluent.clickapp.co.za/v3',
'debug' => true
);
$numbers = array(
['value' => '$95.00', 'caption' => 'Billed'],
['value' => '$95.00', 'caption' => 'Paid'],
['value' => '$0.00', 'caption' => 'Balance']
);
try {
$messageId = Fluent::message()->create()
->addParagraph('We have just processed your monthly payment for Musixmatch monthly subscription (10 Feb - 9 Mar).')
->addNumber($numbers)
->addButton('http://www.myinvoices.com', 'Download Invoice')
->addParagraph('Please note the transaction will reflect on your statement as <b>"Musixmatch"</b>. Please <a href="#">contact us</a> if you have any questions about this receipt or your account.')
->setTeaser('This is a test receipt teaser.')
->setTitle('Receipt')
->subject('Test E-mail Receipt')
->header('Reply-To', '<EMAIL>')
->to('<EMAIL>')
//->send(\Fluent\Transport::LOCAL);
->send(\Fluent\Transport::REMOTE);
echo 'Sent message: ' . $messageId . "\n";
} catch (Fluent\Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
<file_sep><?php
namespace Fluent;
class Api
{
protected $_curl;
protected $_key;
protected $_secret;
protected $_endpoint;
protected $_debug = false;
const ENDPOINT = 'https://fluent.5sq.io/service/v3';
public function __construct($key, $secret, $endpoint = null, $debug = false)
{
$this->_curl = curl_init();
$this->_key = $key;
$this->_secret = $secret;
$this->_endpoint = $endpoint;
$this->_debug = $debug;
}
public function getEndpoint()
{
if ($this->_endpoint !== null) {
return $this->_endpoint;
}
return self::ENDPOINT;
}
public function isDebugOn()
{
return ($this->_debug === true);
}
public function call($resource, $method, $params)
{
$payload = http_build_query($params);
$url = $this->getEndpoint() . '/' . $resource;
curl_setopt($this->_curl, CURLOPT_VERBOSE, $this->isDebugOn());
curl_setopt($this->_curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->_curl, CURLOPT_USERPWD, $this->_key . ':' . $this->_secret);
curl_setopt($this->_curl, CURLOPT_USERAGENT, 'Fluent-Library-PHP-v3.3');
switch ($method) {
case 'create':
curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $payload);
curl_setopt($this->_curl, CURLOPT_POST, true);
break;
case 'get':
$url .= '/' . $params['id'];
break;
case 'index':
$url .= ($payload) ? '?' . $payload : null;
break;
default:
if (!array_key_exists('id', $params)) {
throw new Exception('id missing from REST RPC call');
}
$url .= '/' . $params['id'] . '/' . $method;
break;
}
curl_setopt($this->_curl, CURLOPT_URL, $url);
$start = microtime(true);
$this->_log('Call to ' . $url . ': ' . $payload);
if ($this->isDebugOn()) {
$curl_buffer = fopen('php://memory', 'w+');
curl_setopt($this->_curl, CURLOPT_STDERR, $curl_buffer);
}
$response_body = curl_exec($this->_curl);
$info = curl_getinfo($this->_curl);
$time = microtime(true) - $start;
if ($this->isDebugOn()) {
rewind($curl_buffer);
$this->_log(stream_get_contents($curl_buffer));
fclose($curl_buffer);
}
$this->_log('Completed in ' . number_format($time * 1000, 2) . 'ms');
$this->_log('Got response: ' . $response_body);
if(curl_error($this->_curl)) {
throw new \Fluent\Exception("API call to " . $url . " failed: " . curl_error($this->_curl));
}
$result = json_decode($response_body);
if ($result === null) {
throw new \Fluent\Exception('We were unable to decode the JSON response from the Fluent API: ' . $response_body);
}
if (floor($info['http_code'] / 100) >= 4) {
throw new \Fluent\Exception("{$info['http_code']}, " . $result->message);
}
return $result;
}
protected function _log($msg) {
if ($this->isDebugOn()) {
error_log($msg);
}
}
}
<file_sep>
<?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../library'),
get_include_path(),
)));
require_once 'Fluent.php';
require_once 'Fluent/Api.php';
require_once 'Fluent/Event.php';
require_once 'Fluent/Event/Find.php';
require_once 'Fluent/Content.php';
require_once 'Fluent/Message.php';
require_once 'Fluent/Exception.php';
require_once 'Fluent/Transport.php';
require_once 'Fluent/Transport/Remote.php';
Fluent::$defaults = array(
'key' => '9fe630283b5a62833b04023c20e43915',
'secret' => 'test',
'sender' => array('name' => 'ACME', 'address' => '<EMAIL>'),
);
Fluent\Api::$endpoint = 'http://localhost/fluent-web-service/v3';
//Fluent\Api::$endpoint = 'https://fluent.clickapp.co.za/v3';
Fluent\Api::$debug = true;
try {
$response = Fluent::event()->find()
//->from('<EMAIL>')
->type(array('send', 'open'))
->fetch();
print_r($response);
} catch (Fluent\Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
<file_sep><?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(dirname(__FILE__) . '/../library'),
get_include_path(),
)));
require_once 'Fluent/Message.php';
require_once 'Fluent/Storage/Sqlite.php';
require_once 'Fluent/Transport/Standard.php';
require_once 'Fluent.php';
Fluent::setDefaults(array(
'key' => '9fe630283b5a62833b04023c20e43915',
'from' => '<EMAIL>',
'name' => 'Fluent E-mailer',
));
Fluent\Storage\Sqlite::$path = dirname(__FILE__) . '/../temp';
Fluent\Transport\Standard::$url = 'http://localhost/jifno-api/v1';
<file_sep><?php
namespace Fluent;
interface Transport
{
const LOCAL = 'local';
const REMOTE = 'remote';
public function send(\Fluent\Message\Create $message);
}
<file_sep><?php
require_once dirname(__FILE__) . '/bootstrap.php';
$path = dirname(__FILE__) . '/../temp';
$storage = Fluent\Storage\Sqlite::getInstance();
if ($storage->isLocked(getmypid())) {
print "PID is still alive! can not run twice!\n";
exit;
}
foreach ($storage->getQueue() as $message) {
try {
echo date("Y-m-d H:i:s") . " Sending '{$message['subject']}' to {$message['recipient']}\n";
$response = Fluent::message($message['content'])
->from(json_decode($message['sender'], true))
->to(json_decode($message['recipient'], true))
->headers(json_decode($message['headers'], true))
->subject($message['subject'])
->attachments($storage->getAttachments($message['id']))
->send('remote');
if ($response) {
$storage->moveToSent($message['id'], $response);
}
} catch (Exception $e) {
$storage->moveToFailed($message['id'], $e->getMessage());
echo $e->getMessage() . "\n";
}
}
$result = $storage->purge(30);
if ($result) {
echo "{$result} messages purged\n";
}
<file_sep><?php
namespace Fluent\Transport;
class Local implements \Fluent\Transport
{
protected $_debug;
protected $_storage;
public function __construct($defaults)
{
if (array_key_exists('storage', $defaults)) {
$class = 'Fluent\\Storage\\' . ucfirst($defaults['storage']);
} else {
$class = 'Fluent\\Storage\\Sqlite';
}
$this->_storage = $class::getInstance();
}
public function send(\Fluent\Message\Create $message)
{
return $this->_storage->persist($message);
}
}
<file_sep><?php
use Fluent\Message;
use Fluent\Content;
use Fluent\Template;
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../library'),
get_include_path(),
)));
require_once 'Fluent/Email.php';
$messageId = Fluent::factory(new MyTemplate())
->send('<EMAIL>', 'My little pony');
$message = new Fluent\Message();
$message->to($to)
->subject($subject)
->content('<html><body>Build from scratch</body></html>')
->send();
<file_sep><?php
namespace Fluent\Message;
/**
*
* @author cjb
*
* @method \Fluent\Message\Create setTitle(string $text)
* @method \Fluent\Message\Create addParagraph(string $text)
* @method \Fluent\Message\Create addButton(string $href, string $text)
* @method \Fluent\Message\Create addNumber(array $numbers)
* @method \Fluent\Message\Create setRawContent(string $value)
* @method \Fluent\Message\Create setTeaser(string $value)
*/
use Fluent\Content;
use Fluent\Transport;
use Fluent\Exception;
class Create
{
/**
* @var \Fluent\Content
*/
protected $_content;
protected $_sender = array('address' => null, 'name' => null);
protected $_recipient = array('address' => null, 'name' => null);
protected $_subject;
protected $_options = array();
protected $_headers = array();
protected $_attachments = array();
protected $_defaults = array();
public function __construct($content, $defaults = array())
{
if ($content instanceof \Fluent\Template) {
$this->_content = $content->getContent();
} elseif ($content instanceof Content\Markup) {
$this->_content = $content;
} elseif ($content instanceof Content\Raw) {
$this->_content = $content;
} elseif ($content === null) {
$this->_content = new Content\Markup();
} elseif (is_string($content) && strstr($content, '<content>')) {
$this->_content = new Content\Markup($content);
} else {
$this->_content = new Content\Raw($content);
}
$this->_defaults = $defaults;
}
protected function _getDefault($name, $fallback = null)
{
if (array_key_exists($name, $this->_defaults)) {
return $this->_defaults[$name];
}
return $fallback;
}
public function __toString()
{
return $this->_content->toString();
}
/**
* @param string $name
* @param array $arguments
* @throw \Fluent\Exception
* @return Fluent
*/
public function __call($name, $arguments)
{
if (method_exists($this->_content, $name)) {
$object = $this->_content;
} else {
throw new Exception('Invalid method ' . $name . ' for ' . get_class($this->_content));
}
call_user_func_array(array($object, $name), $arguments);
return $this;
}
/**
* @param string $transport
*/
public function send($transport = null)
{
if ($transport === null) {
$transport = $this->_getDefault('transport');
}
switch (strtolower($transport)) {
case 'local':
$client = new Transport\Local($this->_defaults);
break;
default:
$client = new Transport\Remote(
new \Fluent\Api(
$this->_getDefault('key'), $this->_getDefault('secret'), $this->_getDefault('endpoint'), $this->_getDefault('debug')
)
);
break;
}
return $client->send($this);
}
/**
* @return \Fluent\Message
*/
public function subject($value)
{
$this->_subject = $value;
return $this;
}
/**
* @return \Fluent\Message
*/
public function to($address, $name = null)
{
if (is_array($address)) {
$this->_recipient = $address;
} else {
$this->_recipient = array(
'address' => $address,
'name' => $name
);
}
return $this;
}
/**
* @param string $name
* @param string $contentType
* @param string $content
* @return \Fluent\Message
*/
public function attach($name, $type, $content)
{
array_push($this->_attachments, array(
'name' => $name,
'type' => $type,
'content' => base64_encode($content)
));
return $this;
}
/**
* @param array $values
* @return \Fluent\Message
*/
public function attachments(array $values)
{
foreach ($values as $attachment) {
$this->attach($attachment['name'], $attachment['type'], $attachment['content']);
}
return $this;
}
/**
* @param string $address
* @param string $name
* @return \Fluent\Message
*/
public function from($address, $name = null)
{
if (is_array($address)) {
$this->_sender = $address;
} else {
$this->_sender = array(
'address' => $address,
'name' => $name
);
}
return $this;
}
/**
*
* @param string $name
* @param string $value
* @return \Fluent\Message
*/
public function option($name, $value)
{
$this->_options[$name] = $value;
return $this;
}
public function options($values)
{
$this->_options = array_merge($this->_options, $values);
return $this;
}
/**
*
* @param string $name
* @param string $value
* @return \Fluent\Message
*/
public function header($name, $value)
{
if (!is_string($name)) {
throw new Exception("Invalid header name provided ({$name})");
}
if (empty($value)) {
throw new Exception("Invalid header value provided for {$name}");
}
$this->_headers[$name] = $value;
return $this;
}
/**
*
* @param array $values
* @return \Fluent\Message
*/
public function headers(array $values)
{
foreach ($values as $name => $value) {
$this->header($name, $value);
}
return $this;
}
/**
* @return array
*/
public function getSender()
{
if (isset($this->_sender['address']) && !empty($this->_sender['address'])) {
return array('address' => $this->_sender['address'], 'name' => $this->_sender['name']);
}
return $this->_getDefault('sender');
}
/**
* @return \Fluent\Content
*/
public function getContent()
{
return $this->_content;
}
public function getOptions()
{
$content = array(
'format' => $this->_content->getFormat(),
'teaser' => $this->_content->getTeaser()
);
return array_merge($this->_options, $content);
}
public function getHeaders()
{
if (!array_key_exists('headers', $this->_defaults) || !is_array($this->_defaults['headers'])) {
return $this->_headers;
}
return array_merge($this->_defaults['headers'], $this->_headers);
}
/**
* @return array
*/
public function toArray()
{
return array(
'sender' => $this->getSender(),
'subject' => $this->_subject,
'recipient' => $this->_recipient,
'content' => $this->_content->toString(),
'headers' => $this->getHeaders(),
'attachments' => $this->_attachments,
'options' => $this->getOptions(),
);
}
}
| f44946616a361bebd0138b2e9297c0753345d6db | [
"Markdown",
"PHP"
] | 21 | Markdown | Click-Science/Fluent-Library-PHP | 7bf85e6b250f4c06f8824f191f192c2e147a7817 | 8dd43f8533f319f8f92cfceadf68fbf445f28d2f |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-smart-services-home',
templateUrl: './smart-services-home.component.html',
styleUrls: ['./smart-services-home.component.css']
})
export class SmartServicesHomeComponent implements OnInit {
constructor(private _route: Router) { }
ngOnInit() {
}
navigateToSmartServiceCapabilities(): void {
this._route.navigate(['/tabs/smartServiceCapabilities']);
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import {RouterModule, Routes} from '@angular/router';
import {FormsModule} from '@angular/forms';
import {APP_BASE_HREF} from '@angular/common';
import { TelcoMenuesComponent } from './telco-menues/telco-menues.component';
import { SmartServicesHomeComponent } from './smart-services-home/smart-services-home.component';
import {SmartServicesCapabilitiesComponent} from './smart-services-capabilities/smart-services-capabilities.component';
import { ValueIntegrationComponent } from './value-integration/value-integration.component';
import { ValueIntegrationCapabilitiesComponent } from './value-integration-capabilities/value-integration-capabilities.component';
import { DigitalExperianceComponent } from './digital-experiance/digital-experiance.component';
import { DigitalExperianceCapabilitiesComponent } from './digital-experiance-capabilities/digital-experiance-capabilities.component';
import { TelcoTabsComponent } from './telco-tabs/telco-tabs.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MaterialAnimationModule} from './modules/material-animation/material-animation.module';
const _appRoutes: Routes = [
{ path: '', component: HomeComponent},
{ path: 'menu', component: TelcoMenuesComponent},
/**
{ path: 'smartService', component: SmartServicesHomeComponent},
{ path: 'smartServiceCapabilities', component: SmartServicesCapabilitiesComponent},
{ path: 'digitalExperiance', component: DigitalExperianceComponent},
{ path: 'digitalExperianceCapabilities', component: DigitalExperianceCapabilitiesComponent},
{ path: 'valueIntegraion', component: ValueIntegrationComponent},
{ path: 'valueIntegraionCapabilities', component: ValueIntegrationCapabilitiesComponent},
**/
{ path: 'tabs', component: TelcoTabsComponent, children: [
{ path: 'smartService', component: SmartServicesHomeComponent},
{ path: 'smartServiceCapabilities', component: SmartServicesCapabilitiesComponent},
{ path: 'digitalExperiance', component: DigitalExperianceComponent},
{ path: 'digitalExperianceCapabilities', component: DigitalExperianceCapabilitiesComponent},
{ path: 'valueIntegraion', component: ValueIntegrationComponent},
{ path: 'valueIntegraionCapabilities', component: ValueIntegrationCapabilitiesComponent}
]}
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
TelcoMenuesComponent,
SmartServicesHomeComponent,
SmartServicesCapabilitiesComponent,
ValueIntegrationComponent,
ValueIntegrationCapabilitiesComponent,
DigitalExperianceComponent,
DigitalExperianceCapabilitiesComponent,
TelcoTabsComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MaterialAnimationModule,
FormsModule,
RouterModule.forRoot(_appRoutes)
],
providers: [{provide: APP_BASE_HREF, useValue: '/'}],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-telco-menues',
templateUrl: './telco-menues.component.html',
styleUrls: ['./telco-menues.component.css']
})
export class TelcoMenuesComponent implements OnInit {
constructor(private _route: Router) { }
ngOnInit() {
}
navigateToSmartServicesHome(): void {
this._route.navigate(['/tabs/smartService']);
}
navigateToValueIntegrationHome(): void {
this._route.navigate(['/tabs/valueIntegraion']);
}
navigateToDigitalExperianceHome(): void {
this._route.navigate(['/tabs/digitalExperiance']);
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SmartServicesCapabilitiesComponent } from './smart-services-capabilities.component';
describe('SmartServicesCapabilitiesComponent', () => {
let component: SmartServicesCapabilitiesComponent;
let fixture: ComponentFixture<SmartServicesCapabilitiesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SmartServicesCapabilitiesComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SmartServicesCapabilitiesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ValueIntegrationCapabilitiesComponent } from './value-integration-capabilities.component';
describe('ValueIntegrationCapabilitiesComponent', () => {
let component: ValueIntegrationCapabilitiesComponent;
let fixture: ComponentFixture<ValueIntegrationCapabilitiesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ValueIntegrationCapabilitiesComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ValueIntegrationCapabilitiesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TelcoMenuesComponent } from './telco-menues.component';
describe('TelcoMenuesComponent', () => {
let component: TelcoMenuesComponent;
let fixture: ComponentFixture<TelcoMenuesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ TelcoMenuesComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TelcoMenuesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-value-integration',
templateUrl: './value-integration.component.html',
styleUrls: ['./value-integration.component.css']
})
export class ValueIntegrationComponent implements OnInit {
constructor(private _route: Router) { }
ngOnInit() {
}
navigateToValueIntegrationCapabilities(): void{
this._route.navigate(['/tabs/valueIntegraionCapabilities']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-digital-experiance',
templateUrl: './digital-experiance.component.html',
styleUrls: ['./digital-experiance.component.css']
})
export class DigitalExperianceComponent implements OnInit {
constructor(private _route: Router) { }
ngOnInit() {
}
navigateToDigitalExperianceCapabilities(): void {
this._route.navigate(['/tabs/digitalExperianceCapabilities']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-telco-tabs',
templateUrl: './telco-tabs.component.html',
styleUrls: ['./telco-tabs.component.css']
})
export class TelcoTabsComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatTabsModule } from '@angular/material/tabs';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatIconModule } from '@angular/material/icon';
import { MatDividerModule } from '@angular/material/divider';
import {
MatAutocompleteModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatGridListModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatStepperModule,
MatTableModule,
MatToolbarModule,
MatTooltipModule
} from '@angular/material';
@NgModule({
imports: [
CommonModule,
MatTabsModule,
MatButtonModule,
MatButtonToggleModule,
MatIconModule,
MatDividerModule,
MatCardModule
],
exports: [
MatTabsModule,
MatButtonModule,
MatButtonToggleModule,
MatIconModule,
MatCardModule,
MatDividerModule
],
declarations: []
})
export class MaterialAnimationModule { }
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ValueIntegrationComponent } from './value-integration.component';
describe('ValueIntegrationComponent', () => {
let component: ValueIntegrationComponent;
let fixture: ComponentFixture<ValueIntegrationComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ValueIntegrationComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ValueIntegrationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 845b9814a228932f3b6c368e47b614359044d1ee | [
"TypeScript"
] | 11 | TypeScript | ad123412/ipad-home-app-v2 | 2d6f2564797c2204105f8cb0eaa5fd8201d322e5 | 6add503b23c3137551e393167d9a3f3c55998b2e |
refs/heads/master | <repo_name>Lord-Kanzler/DS-Unit-3-Sprint-2-SQL-and-Databases<file_sep>/module1-introduction-to-sql/rpg_queries.py
import os
import sqlite3
# construct a path to wherever your database exists
DB_FILEPATH = os.path.join(os.path.dirname(__file__), "rpg_db.sqlite3")
connection = sqlite3.connect(DB_FILEPATH)
cursor = connection.cursor()
print("CURSOR", cursor)
# How many total Characters are there?
query = "SELECT COUNT (*) FROM charactercreator_character;"
character_total = cursor.execute(query).fetchall()
print("character_total", character_total)
# How many of each specific subclass?
query2 = "SELECT COUNT (*) FROM charactercreator_cleric;"
cleric = cursor.execute(query2).fetchall()
print("cleric", cleric)
query3 = "SELECT COUNT (*) FROM charactercreator_fighter;"
fighter = cursor.execute(query3).fetchall()
print("fighter", fighter)
query4 = "SELECT COUNT (*) FROM charactercreator_mage;"
mage = cursor.execute(query4).fetchall()
print("mage", mage)
query5 = "SELECT COUNT (*) FROM charactercreator_necromancer;"
necromancer = cursor.execute(query5).fetchall()
print("necromancer", necromancer)
query6 = "SELECT COUNT (*) FROM charactercreator_thief;"
thief = cursor.execute(query6).fetchall()
print("thief", thief)
# How many total Items?
query7 = "SELECT COUNT (*) FROM armory_item;"
item_total = cursor.execute(query7).fetchall()
print("item_total", item_total)
# How many of the Items are weapons? How many are not?
query7 = "SELECT COUNT (*) FROM armory_weapon;"
weapons = cursor.execute(query7).fetchall()
print("weapons", weapons)
print("non weapon", 174 - 37)
# How many Items does each character have? (Return first 20 rows)
query8 = """select
c.character_id
, c."name" as character_name
, count(distinct inv.item_id) as item_count
FROM charactercreator_character c
left join charactercreator_character_inventory inv
on c.character_id = inv.character_id
group by 1, 2 limit 20"""
items_per_char = cursor.execute(query8).fetchall()
print("Items per character", items_per_char)
# How many Weapons does each character have? (Return first 20 rows)
query9 = """SELECT
c.character_id
, c.name
, count(distinct w.item_ptr_id) as weapon_count
FROM charactercreator_character c
left join charactercreator_character_inventory i on c.character_id = i.character_id
left join armory_weapon w on i.item_id = w.item_ptr_id
group by c.character_id limit 20
"""
weapons_per_char = cursor.execute(query9).fetchall()
print("Weapons per character", weapons_per_char)
# On average, how many Items does each Character have?
query10 = """select avg(item_count) as avg_items
from (select
c.character_id
, c."name" as character_name
, count(distinct inv.item_id) as item_count
FROM charactercreator_character c
left join charactercreator_character_inventory inv
on c.character_id = inv.character_id
group by 1, 2
)subq
"""
items_char = cursor.execute(query10).fetchall()
print("Avg.Items per character", items_char)
# On average, how many Weapons does each character have?
query11 = """select avg(weapon_count) as avg_weapons_per_count
from (
SELECT
c.character_id
, c.name
, count(distinct w.item_ptr_id) as weapon_count
FROM charactercreator_character c
left join charactercreator_character_inventory i on c.character_id = i.character_id
left join armory_weapon w on i.item_id = w.item_ptr_id
group by c.character_id
) subq
"""
weapons_char_avg = cursor.execute(query11).fetchall()
print("Avg.weapons per character", weapons_char_avg)
##Part 2, Making and populating a Database
import pandas as pd
df = pd.read_csv('buddymove_holidayiq.csv')
DB_FILEPATH = os.path.join(os.path.dirname(__file__), "buddymove_holidayiq.sqlite3")
connection = sqlite3.connect(DB_FILEPATH)
cursor = connection.cursor()
print("CURSOR", cursor)
df.to_sql('review', connection, if_exists='replace', index=False)
# Count how many rows you have - it should be 249!
query1 = "SELECT * FROM review;"
rows = cursor.execute(query1).fetchall()
print len(rows)
# How many users who reviewed at least 100 Nature in the category
# also reviewed at least 100 in the Shopping category?
query2 = """
Select Nature >=100 and Shopping >=100 from review
order by 1 DESC
"""
count = cursor.execute(query2).fetchall()
print("Number of Nature and Shopping >100", count.count((1, )))
# (Stretch) What are the average number of reviews for each category?
<file_sep>/module2-sql-for-analysis/insert_titanic.py
import pandas as pd
import os
from dotenv import load_dotenv
import psycopg2
from psycopg2.extras import execute_values
from sqlalchemy import create_engine
load_dotenv() # > loads contents of the .env file into the script's environment
DB_NAME = os.getenv('DB_NAME')
DB_USER = os.getenv('DB_USER')
DB_PASSWORD = os.getenv('DB_PASSWORD')
DB_HOST = os.getenv('DB_HOST')
URL = os.getenv('URL')
connection = psycopg2.connect(
dbname=DB_NAME, user=DB_USER, password=<PASSWORD>, host=DB_HOST)
print('CONNECTION:', connection)
cursor = connection.cursor()
titanic_filepath = 'titanic.csv'
df = pd.read_csv(titanic_filepath)
engine = create_engine(URL)
df.to_sql('character', engine)
connection = engine.raw_connection()
connection.commit()
<file_sep>/module3-nosql-and-document-oriented-databases/ETL_rpg_data_to_MongoDB.py
import pymongo
import os
from dotenv import load_dotenv
import sqlite3
load_dotenv() # > loads contents of the .env file into the script's environment
DB_USER = os.getenv("MONGO_USER", default="OOPS")
DB_PASSWORD = os.getenv("MONGO_PASSWORD", default="<PASSWORD>")
CLUSTER_NAME = os.getenv("MONGO_CLUSTER_NAME", default="OOPS")
DB_FILEPATH = os.path.join(os.path.dirname(__file__), "rpg_db.sqlite3")
sqlite_connection = sqlite3.connect(DB_FILEPATH)
sqlite_cursor = sqlite_connection.cursor()
row_count = 'SELECT COUNT (*) FROM charactercreator_character'
print(sqlite_cursor.execute(row_count).fetchall())
get_characters = 'SELECT * FROM charactercreator_character'
characters = sqlite_cursor.execute(get_characters).fetchall()
# mongodb+srv: // Lord-Kanzler: < password > @cluster0-arnec.mongodb.net/test?retryWrites = true & w = majority
connection_uri = f"mongodb+srv://{DB_USER}:{DB_PASSWORD}@{CLUSTER_NAME}.mongodb.net/test?retryWrites=true&w=majority"
print("----------------")
print("URI:", connection_uri)
client = pymongo.MongoClient(connection_uri)
print("----------------")
print("CLIENT:", type(client), client)
db = client.test_database # "test_database" or whatever you want to call it
print("----------------")
print("DB:", type(db), db)
collection = db.characters_test # "pokemon_test" or whatever you want to call it
print("----------------")
print("COLLECTION:", type(collection), collection)
rpg_character = (1, "<NAME>", 10, 3, 0, 0, 0, 0, 0)
rpg_doc = {
'sql_key' : [0],
'name': characters[1],
'level': characters[2],
'exp': characters[3],
'hp': characters[4],
'strength': characters[5],
'intelligence': characters[6],
'dexterity': characters[7],
'wisdom': characters[8],
}
collection.insert_one(rpg_doc)
print(type(rpg_character))
print(type(characters))
print(characters)
# Assignment
# Insert values
for character in characters:
collection.insert_one(characters)
<file_sep>/Unit-3-Weel-2-SC/demo_data.py
### Part 1 - Making and populating a Database
# Consider the following data:
# | s | x | y |
# |----- | --- | ---|
# | 'g' | 3 | 9 |
# | 'v' | 5 | 7 |
# | 'f' | 8 | 7 |
# Using the standard `sqlite3` module:
import sqlite3
# - Open a connection to a new(blank) database file `demo_data.sqlite3`
connection = sqlite3.connect('demo_data.sqlite3')
# - Make a cursor, and execute an appropriate `CREATE TABLE` statement to accept
# the above data(name the table `demo`)
cursor = connection.cursor()
print("CURSOR", cursor)
# - Write and execute appropriate `INSERT INTO` statements to add the data(as
# shown above) to the database
table_demo = '''
CREATE TABLE demo (
id PRIMARY KEY,
s VARCHAR(20) UNIQUE NOT NULL,
x INT,
y INT
);
'''
cursor.execute(table_demo)
connection.commit()
insert_demo = '''
INSERT INTO demo
(s, x, y)
VALUES
('g', 3, 9),
('v', 5, 7),
('f', 8, 7);
'''
cursor.execute(insert_demo).fetchall()
connection.commit()
# Make sure to `commit()` so your data is saved! The file size should be non-zero.
# Then write the following queries(also with `sqlite3`) to test:
# - Count how many rows you have - it should be 3!
rows = "SELECT COUNT (*) FROM demo;"
rows = cursor.execute(rows).fetchall()
print("rows", rows)
# - How many rows are there where both `x` and `y` are at least 5?
rows_bigger_5 = """SELECT x >= 5 and y >= 5 from demo
order by 1 DESC;"""
rows_bigger_5 = cursor.execute(rows_bigger_5).fetchall()
print("rows_bigger_5", rows_bigger_5.count((1, )))
# - How many unique values of `y` are there(hint - `COUNT()` can accept a keyword
# `DISTINCT`)?
unique_values = "SELECT COUNT (DISTINCT y) FROM demo;"
unique_values = cursor.execute(unique_values).fetchall()
print("unique_values", unique_values)
<file_sep>/Unit-3-Weel-2-SC/northwind.py
# ### Part 2 - The Northwind Database
# Using `sqlite3`, connect to the given `northwind_small.sqlite3` database.
import sqlite3
connection = sqlite3.connect('northwind_small.sqlite3')
cursor = connection.cursor()
print("CURSOR", cursor)
# 
# Above is an entity-relationship diagram - a picture summarizing the schema and
# relationships in the database. Note that it was generated using Microsoft
# Access, and some of the specific table/field names are different in the provided
# data. You can see all the tables available to SQLite as follows:
# ```python
# >> > cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").fetchall()
# [('Category',), ('Customer',), ('CustomerCustomerDemo',),
# ('CustomerDemographic',), ('Employee',), ('EmployeeTerritory',), ('Order',),
# ('OrderDetail',), ('Product',), ('Region',), ('Shipper',), ('Supplier',),
# ('Territory',)]
# ```
# *Warning*: unlike the diagram, the tables in SQLite are singular and not plural
# (do not end in `s`). And you can see the schema(`CREATE TABLE` statement)
# behind any given table with:
# ```python
# >> > cursor.execute('SELECT sql FROM sqlite_master WHERE name="Customer";').fetchall()
# [('CREATE TABLE "Customer" \n(\n "Id" VARCHAR(8000) PRIMARY KEY, \n
# "CompanyName" VARCHAR(8000) NULL, \n "ContactName" VARCHAR(8000) NULL, \n
# "ContactTitle" VARCHAR(8000) NULL, \n "Address" VARCHAR(8000) NULL, \n "City"
# VARCHAR(8000) NULL, \n "Region" VARCHAR(8000) NULL, \n "PostalCode"
# VARCHAR(8000) NULL, \n "Country" VARCHAR(8000) NULL, \n "Phone" VARCHAR(8000)
# NULL, \n "Fax" VARCHAR(8000) NULL \n)',)]
# ```
# In particular note that the * primary * key is `Id`, and not `CustomerId`. On
# other tables(where it is a * foreign * key) it will be `CustomerId`. Also note -
# the `Order` table conflicts with the `ORDER` keyword! We'll just avoid that
# particular table, but it's a good lesson in the danger of keyword conflicts.
# Answer the following questions(each is from a single table):
# - What are the ten most expensive items(per unit price) in the database?
# query = "SELECT COUNT (*) FROM charactercreator_character;"
# character_total = cursor.execute(query).fetchall()
# print("character_total", character_total)
query = """
SELECT ProductName, UnitPrice FROM Product
ORDER BY UnitPrice DESC LIMIT 10;
"""
exp_items = cursor.execute(query).fetchall()
print("10_exp_items", exp_items)
# - What is the average age of an employee at the time of their hiring?
# (Hint: a lot of arithmetic works with dates.)
query = """
SELECT AVG(HireDate) -AVG(BirthDate) as avg_hiring_age FROM Employee
"""
avg_age = cursor.execute(query).fetchall()
print("avg_age", avg_age)
# - (*Stretch*) How does the average age of employee at hire vary by city?
# Your code(to load and query the data) should be saved in `northwind.py`, and
# added to the repository. Do your best to answer in purely SQL, but if necessary
# use Python/other logic to help.
### Part 3 - Sailing the Northwind Seas
# You've answered some basic questions from the Northwind database, looking at
# individual tables - now it's time to put things together, and `JOIN`!
# Using `sqlite3` in `northwind.py`, answer the following:
# - What are the ten most expensive items(per unit price) in the database * and*
# their suppliers?
query1 = """
SELECT * FROM Product
LEFT JOIN Supplier ON Product.SupplierId = Supplier.Id
ORDER BY UnitPrice DESC LIMIT 10;
"""
exp_items_suppliers = cursor.execute(query1).fetchall()
print("10_exp_items_and_suppliers", exp_items_suppliers)
# - What is the largest category(by number of unique products in it)?
query1 = """
SELECT * FROM Category
LEFT JOIN Product ON Category.Id = Product.CategoryId
ORDER BY CategoryName DESC;
"""
#This is not finished, ran out of time!!
largest_category = cursor.execute(query1).fetchall()
print("largest_category", largest_category)
# - (*Stretch*) Who's the employee with the most territories? Use `TerritoryId`
# (not name, region, or other fields) as the unique identifier for territories.
<file_sep>/module2-sql-for-analysis/ETL_rpg_data_to_postgreSQL.py
from psycopg2.extras import execute_values
import psycopg2
from dotenv import load_dotenv
import pandas as pd
import sqlite3
import os
DB_NAME = os.getenv('DB_NAME')
DB_USER = os.getenv('DB_USER')
DB_PASSWORD = os.getenv('DB_PASSWORD')
DB_HOST = os.getenv('DB_HOST')
URL = os.getenv('URL')
load_dotenv() # > loads contents of the .env file into the script's environment
DB_FILEPATH = os.path.join(os.path.dirname(__file__), "rpg_db.sqlite3")
sqlite_connection = sqlite3.connect(DB_FILEPATH)
sqlite_cursor = sqlite_connection.cursor()
row_count = 'SELECT COUNT (*) FROM charactercreator_character'
print(sqlite_cursor.execute(row_count).fetchall())
get_characters = 'SELECT * FROM charactercreator_character'
characters = sqlite_cursor.execute(get_characters).fetchall()
#rpg schema
print(sqlite_cursor.execute('PRAGMA table_info(charactercreator_character);').fetchall())
#pg part
create_character_table = """
CREATE TABLE charactercreator_character (
character_id SERIAL PRIMARY KEY,
name VARCHAR(30),
level INT,
exp INT,
hp INT,
strength INT,
intelligence INT,
dexterity INT,
wisdom INT
);
"""
pg_connection = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=<PASSWORD>, host=DB_HOST)
print('CONNECTION:', pg_connection)
pg_cursor = pg_connection.cursor()
pg_cursor.execute(create_character_table)
pg_connection.commit()
# Insert values
for character in characters:
insert_character = """
INSERT INTO charactercreator_character
(name, level,exp, hp, strength, intelligence, dexterity, wisdom)
VALUES """ + str(characters[0][1:]) + ";"
pg_cursor.execute(insert_character)
pg_connection.commit()
<file_sep>/module2-sql-for-analysis/elephant_queries.py
import os
from dotenv import load_dotenv
import psycopg2
load_dotenv() # > loads contents of the .env file into the script's environment
### Connect to ElephantSQL-hosted PostgreSQL
DB_NAME = os.getenv("DB_NAME")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_HOST = os.getenv("DB_HOST")
connection = psycopg2.connect(dbname=DB_NAME, user=DB_USER,
password=<PASSWORD>, host=DB_HOST)
print(type(connection))
### A "cursor", a structure to iterate over db records to perform queries
cursor = connection.cursor()
### An example query
cursor.execute('SELECT * from test_table;')
### Note - nothing happened yet! We need to actually *fetch* from the cursor
# first_results = cursor.fetchone()
# print(first_results)
print('-----------------------')
all_results = cursor.fetchall()
print(all_results)
<file_sep>/Unit-3-Weel-2-SC/Unit-3-Week-2-SC_ALEX_KAISER.py
import sqlite3
connection = sqlite3.connect('study_part1.sqlite3')
<file_sep>/chinook/chinook_query.md
--this is a comment
/*
Select PlaylistId, Name as playlistName
*/
--for all customers who live in the US
--what are their email adresses
/*
Select
-- CustomerId, FirstName, LastName, Country, Email
count(CustomerId) as CustomerCount
from customers
where Country in ("USA", "Brazil")
*/
-- select Country, count(distinct CustomerId) as CustomerCount
-- from customers
-- group by Country
-- order by CustomerCount DESC
-- limit 5
-- what are all the playlists like classical (classical-related playlist)
-- SELECT
-- PlaylistId
-- , Name as playlistName
-- -- ,otherCol
-- FROM playlists
-- WHERE playlistName LIKE "%Classical%"
-- for each track, what is the name of that track's genre
-- row per track (3,503)
-- SELECT
-- tracks.TrackId
-- ,tracks.Name as TrackName
-- ,tracks.GenreId
-- ,genres.Name as GenreName
-- FROM tracks
-- JOIN genres ON tracks.GenreId = genres.GenreId
-- WHERE GenreId IS NULL -- there are no rows with null genres
--for each artist, how many albums?
-- Select *
-- from artists
-- join albums on artists.ArtistId =albums.ArtistId
-- order by ArtistId
-- for each artist, how many albums?
-- rows per artist (275 rows)
-- columns for artist id, artist name, count of album
-- FYI: some artists don't have any albums
SELECT
r.ArtistId
,r."Name" as ArtistName
,l.Title as AlbumTitle
FROM artists r
LEFT JOIN albums l ON r.ArtistId = l.ArtistId
ORDER BY 1
| a70f9fb60597a0f30a3e5fcc33ecd2e9b2a3bd81 | [
"Markdown",
"Python"
] | 9 | Python | Lord-Kanzler/DS-Unit-3-Sprint-2-SQL-and-Databases | c176a4c58d59e03cd930e42737dfd9c01bb58ead | 54f074c9ddccb9aceb2bf49aeab7c435752b17d8 |
refs/heads/master | <repo_name>Sunreaver/github_hook<file_sep>/lua/my80server.lua
-- require("./sys")
DIR_MYSERVER = "$GOPATH/src/github.com/sunreaver/myserver/"
function gitpull(...)
local exc = {}
exc[1] = "cd " .. DIR_MYSERVER
exc[2] = "git pull"
local result = ""
for i=1,#exc do
result = result .. exc[i] .. ";"
end
r = string.sub(result, 0, string.len(result)-1)
-- print(r)
os.execute(r)
end
function restart(...)
local exc = {}
exc[1] = "cd " .. DIR_MYSERVER
exc[2] = "go build"
exc[3] = "cp myserver.d /etc/init.d/myserver.d"
exc[4] = "mv myserver ~/Doc/bin/"
exc[5] = "service myserver.d restart"
local result = ""
for i=1,#exc do
result = result .. exc[i] .. ";"
end
os.execute(string.sub(result, 0, string.len(result)-1))
end
print("pull...")
gitpull()
print("restart...")
restart()
print(string.format([[↑ DO AT: %s]], os.date("%Y-%m-%d %H:%M:%S")))
<file_sep>/lua/warms.lua
local lfs = require"lfs"
local DIR_WARMS = "$GOPATH/src/github.com/sunreaver/warms/"
-- 查找.go文件
function attrdir (path)
local fNames = {}
local i = 1
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path..'/'..file
local attr = lfs.attributes(f)
if type(attr) == "table" then
-- assert (type(attr) == "table")
-- if attr.mode == "directory" then
if attr.mode == "file" then
if string.find(file, "^.+%.go$") then
fNames[i] = file
i = i + 1
end
end
end
end
end
return fNames
end
function gitpull(path)
local exc = {}
exc[1] = "cd " .. path
exc[2] = "git pull"
local result = ""
for i=1,#exc do
result = result .. exc[i] .. ";"
end
r = string.sub(result, 0, string.len(result)-1)
os.execute(r)
end
function buildAndDo(fileNames, path)
for j=1,#fileNames do
local exc = {}
exc[1] = "cd " .. path
exc[2] = "go build " .. fileNames[j]
print("build: " .. fileNames[j])
local fn = ""
if string.find(fileNames[j], ".*%.go$") then
fn = string.sub(fileNames[j], 0, string.len(fileNames[j]) - 3)
end
if string.find(fileNames[j], "^huaban_warm.*%.go$") then
exc[3] = "mv " .. fn .. " /root/Doc/bin/huaban/huaban_warm"
exc[4] = "service huaban restart"
elseif string.find(fileNames[j], "^stock_warms%.go$") then
exc[3] = "mv " .. fn .. " /root/Doc/bin/stock/stockwarm"
exc[4] = "cp stock.json /root/Doc/bin/stock/"
end
exc[#exc + 1] = string.format("echo \"%s : Updated At %s\" >> autoUpdate.log", fn, os.date("%Y-%m-%d %H:%M:%S"))
local result = ""
for i=1,#exc do
result = result .. exc[i] .. ";"
end
r = string.sub(result, 0, string.len(result)-1)
os.execute(r)
end
end
-- do
local rp = io.popen("echo " .. DIR_WARMS)
local realPath = rp:read("*l")
gitpull(realPath)
local fns = attrdir(realPath)
-- assert(type(fns) == "table")
buildAndDo(fns, realPath)
print(string.format([[↑ DO AT: %s]], os.date("%Y-%m-%d %H:%M:%S")))
<file_sep>/lua/hookpull.lua
-- require("./sys")
DIR_GITHOOK = "$GOPATH/src/github.com/sunreaver/github_hook/"
function gitpull(...)
local exc = {}
exc[1] = "cd " .. DIR_GITHOOK
exc[2] = "git pull"
local result = ""
for i=1,table.maxn(exc) do
result = result .. exc[i] .. ";"
end
r = string.sub(result, 0, string.len(result)-1)
-- print(r)
os.execute(r)
end
print("pull...")
gitpull()
print(string.format([[↑ DO AT: %s]], os.date("%Y-%m-%d %H:%M:%S")))
<file_sep>/main.go
package main
import (
"github.com/go-macaron/pongo2"
"gopkg.in/macaron.v1"
"github.com/sunreaver/github_hook/ctl"
)
func main() {
m := macaron.Classic()
m.Use(pongo2.Pongoer())
m.Post("/github.com/sunreaver/:url", ctl.Hook)
m.Get("/github.com/sunreaver/:url", ctl.Hook)
m.Run("127.0.0.1", 8097)
}
<file_sep>/lua/hook.lua
-- require("./sys")
DIR_GITHOOK = "$GOPATH/src/github.com/sunreaver/github_hook/"
function killprog( prog )
if type(prog) ~= "string" then
return
end
os.execute("pkill -f " .. prog)
end
function gitpull(...)
local exc = {}
exc[1] = "cd " .. DIR_GITHOOK
exc[2] = "git pull"
local result = ""
for i=1,#exc do
result = result .. exc[i] .. ";"
end
r = string.sub(result, 0, string.len(result)-1)
-- print(r)
os.execute(r)
end
function restart(...)
local exc = {}
exc[1] = "cd " .. DIR_GITHOOK
exc[2] = "go build"
exc[3] = "mv github_hook github_hook_run"
exc[4] = "nohup ./github_hook_run >>nohup.out 2>&1 &"
local result = ""
for i=1,table.maxn(exc) do
result = result .. exc[i] .. ";"
end
os.execute(string.sub(result, 0, string.len(result)-1))
end
print("pull...")
gitpull()
print("kill...")
killprog("github_hook_run")
print("restart...")
restart()
print(string.format([[↑ DO AT: %s]], os.date("%Y-%m-%d %H:%M:%S")))
<file_sep>/mode/Conf.go
package mode
import (
"encoding/json"
)
// Conf 配置信息
type Conf struct {
Name string `json:"name"`
DoLua string `json:"dolua"`
}
// MakeConf CreateConf
func MakeConf(data []byte) []Conf {
var c []Conf
e := json.Unmarshal(data, &c)
if e != nil {
c = []Conf{}
}
return c
}
<file_sep>/lua/sys.lua
-- DIR_GITHOOK = "$GOPATH/src/github.com/sunreaver/github_hook/"
function killprog( prog )
if type(prog) ~= "string" then
return
end
os.execute("pkill -f " .. prog)
end<file_sep>/README.md
# github_hook
我的github更新hook
## github配置方式
在giahub项目的配置中,配置webhook到main.go中的Push配置
例如:
``` url
xxx.xxx/github.com/sunreaver/:url
```
## github_hook.conf
names 对应到github配置中的 :url
dolua 对应到./lua/目录中的.lua脚本文件
### tip
配置好后,github项目有push,会自动在url上push一些内容,详见github。
本程序会自动调用github_hook.conf中配置的lua脚本
<file_sep>/ctl/hook.go
package ctl
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"os/exec"
"strings"
"github.com/sunreaver/gotools/system"
"github.com/sunreaver/github_hook/mode"
"gopkg.in/macaron.v1"
)
// Hook 钩子,自动启动一些lua脚本,来处理事宜
func Hook(ctx *macaron.Context) {
luaStr := ""
repo := ctx.Params(":url")
// github_hook 特殊处理
if repo == "github_hook" {
req, e := ctx.Req.Body().Bytes()
if e == nil {
var form mode.GithubHook
e = json.Unmarshal(req, &form)
if e == nil && verification(form) {
//pull & restart
luaStr = "lua/hook.lua"
} else if e == nil {
//pull
luaStr = "lua/hookpull.lua"
}
} else {
log.Println(e)
}
} else {
data, e := ioutil.ReadFile(system.CurPath() + system.SystemSep() + "github_hook.conf")
if e == nil {
conf := mode.MakeConf(data)
log.Println("Conf : ", conf)
for _, item := range conf {
if item.Name == repo {
luaStr = item.DoLua
log.Println("Will do: ", luaStr)
break
}
}
} else {
log.Println(e)
}
}
go func(c string) {
if c == "" {
return
}
c = system.CurPath() + system.SystemSep() + c
cmd := exec.Command("/usr/local/bin/lua", c)
out := bytes.Buffer{}
cmd.Stdout = &out
if err := cmd.Run(); err == nil {
log.Println("OK: " + c)
} else {
log.Println("Faile: " + c)
log.Println(err)
}
log.Println("Cmd Log: ", out.String())
}(luaStr)
ctx.JSON(200, map[string]interface{}{
"status": 200,
"msg": luaStr,
})
}
func verification(v mode.GithubHook) (r bool) {
r = false
for _, item := range v.Commits {
for _, added := range item.Added {
if strings.HasSuffix(added, ".go") {
r = true
log.Println("restart for : " + added)
return
}
}
for _, removed := range item.Removed {
if strings.HasSuffix(removed, ".go") {
r = true
log.Println("restart for : " + removed)
return
}
}
for _, modified := range item.Modified {
if strings.HasSuffix(modified, ".go") {
r = true
log.Println("restart for : " + modified)
return
}
}
}
return
}
| f26ce09b630e1290968c4eb63479b62408bac982 | [
"Markdown",
"Go",
"Lua"
] | 9 | Lua | Sunreaver/github_hook | 11344e1ef287dfd8cd4dd09dde3a303c57ed9e78 | 1076aa638c33266f7e2fdeec88f24c3256214db7 |
refs/heads/master | <repo_name>jainakshansh/CartOwl<file_sep>/README.md
# CartOwl: Shopping Cart
### This is a minimalistic shopping cart built upon AngularJS.
### This basic shopping cart includes dynamic updation of webpage.
<file_sep>/js/cart.js
var myApp = angular.module("ShopCart", []);
myApp.controller("cartCont", function($scope) {
$scope.price1 = 0;
$scope.price2 = 0;
$scope.price3 = 0;
$scope.onequant = 0;
$scope.twoquant = 0;
$scope.threequant = 0;
$scope.res1 = function() {
$scope.price1 = $scope.onequant * 13999;
return $scope.price1;
}
$scope.res2 = function() {
$scope.price2 = $scope.twoquant * 14750;
return $scope.price2;
}
$scope.res3 = function() {
$scope.price3 = $scope.threequant * 13999;
return $scope.price3;
}
$scope.gtotal = function() {
return $scope.price1 + $scope.price2 + $scope.price3;
}
}); | b40a984a0d1ab5f55ba8c241bac9c201884a91dc | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jainakshansh/CartOwl | 2efb5ce2a30b866cbdbd0e51ed9945e34ae11407 | f0994d3cd24f0034864f885a19c9cd2c7db9e13a |
refs/heads/main | <file_sep>using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model.Mapping
{
public class LoginHistoryMapping: ClassMap<LoginHistory>
{
public LoginHistoryMapping()
{
Table("LoginHistory");
Id(x => x.LoginHistoryID, "LoginHistoryID");
Map(x => x.UserID, "UserID").CustomType<int>();
Map(x => x.StartTime, "StartTime");
Map(x => x.EndTime, "EndTime");
}
}
}
<file_sep>using System.Web.Http;
using WebActivatorEx;
using HmsAPI;
using Swashbuckle.Application;
using System.Linq;
namespace HmsAPI
{
public class SwaggerConfig
{
public static void Register(HttpConfiguration httpConfiguration)
{
httpConfiguration.EnableSwagger(c => {
c.SingleApiVersion("v2", "HMS.APi");
}).EnableSwaggerUi(c => { });
}
}
}
<file_sep>using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Topshelf;
namespace HmsAPI
{
static class Program
{
public static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<RestService>(s =>
{
s.ConstructUsing(() => new RestService());
s.WhenStarted(rs => rs.Start("http://localhost:9001"));
s.WhenStopped(rs => rs.Stop());
});
x.RunAsLocalSystem();
// x.StartAutomatically();
x.SetServiceName("WebAPiTest");
x.SetDisplayName("WebAPiTest");
x.SetDescription("Sample WebAPi");
});
}
public class RestService
{
private IDisposable appDisposable;
public void Start(string url)
{
appDisposable = WebApp.Start<Startup>(url);
Console.WriteLine("Service started under http://localhost:9001");
}
public void Stop()
{
if (appDisposable != null)
{
appDisposable.Dispose();
}
}
}
}
}
<file_sep>using HmsAPI.DataAccess.Interface;
using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess.Repository
{
public class UserRoleRepository:BaseRepository<UserRoles>,IUserRoleRepository
{
public void DeleteUserRole(int userRoleID)
{
var objuserRole = GetUserRolesByID(userRoleID);
Delete(objuserRole);
}
public UserRoles GetUserRolesByID(int userRoleID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objUserRole = session.Query<UserRoles>().Where(x => x.UserRoleID == userRoleID).FirstOrDefault();
return objUserRole;
}
}
}
public UserRoles GetUserRolesByuserID(int userID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objUserRole = session.Query<UserRoles>().Where(x => x.UserID == userID).FirstOrDefault();
return objUserRole;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class DoctorCalendarDTO
{
public int DoctorCalendarID { get; set; }
public int DoctorID { get; set; }
public DateTime Date { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public int HospitalID { get; set; }
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public interface ILoginHistoryRepository
{
LoginHistory SaveorUpdate(LoginHistory obj);
IEnumerable<LoginHistory> GetAll();
LoginHistory GetLoginHistoryByID(int LoginHistoryID);
void DeleteLoginHsitory(int LoginHistoryID);
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public interface IRolesRepository
{
Roles SaveorUpdate(Roles obj);
IEnumerable<Roles> GetAll();
Roles GetRolesByID(int RoleID);
void DeleteRole(int RoleID);
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public interface IPatientMedicineRepository
{
PatientMedicine SaveorUpdate(PatientMedicine obj);
IEnumerable<PatientMedicine> GetAll();
PatientMedicine GetMedicineByID(int PatientMedicineID);
void DeleteMedicine(int PatientMedicineID);
PatientMedicine GetMedicinesByAppointmnetID(int appointmentID);
List<PatientMedicine> GetMedicinesByUserID(int userID);
}
}
<file_sep>using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using HmsAPI.Model;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
namespace HmsAPI.DataAccess
{
public class FluentNHibernateHelper
{
public readonly string connectionString;
public FluentNHibernateHelper()
{
connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ToString();
}
public ISessionFactory GetSessionFactory()
{
ISessionFactory sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2012
.ConnectionString(connectionString).ShowSql()
)
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<User>())
.ExposeConfiguration(cfg => new SchemaExport(cfg)
.Create(false, false))
.BuildSessionFactory();
return sessionFactory;
}
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public interface IDoctorRepository
{
Doctor SaveorUpdate(Doctor obj);
IEnumerable<Doctor> GetAll();
Doctor GetDoctorByID(int DoctorID);
void DeleteDoctor(int DoctorID);
List<Doctor> GetDoctorsByHospitalID(int hospitalID);
List<Doctor> GetDoctorsBySpecialization(string specialist);
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess.Interface
{
public interface IUserRoleRepository
{
UserRoles SaveorUpdate(UserRoles obj);
IEnumerable<UserRoles> GetAll();
void DeleteUserRole(int userRoleID);
UserRoles GetUserRolesByID(int userRoleID);
UserRoles GetUserRolesByuserID(int userID);
}
}
<file_sep>using HmsAPI.Dto;
using HmsAPI.Dto.Request;
using HmsAPI.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace HmsAPI.Controllers
{
[RoutePrefix("api/v1/user")]
public class UserController : ApiController
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
/// <summary>
/// Registers new User Details
/// </summary>
/// <param name="userDTO"></param>
/// <returns></returns>
[Route("Register")]
[HttpPost]
public IHttpActionResult Register([FromBody] UserDTO userDTO)
{
if (userDTO == null)
{
return BadRequest();
}
var results = _userService.Register(userDTO);
return Ok(results);
}
/// <summary>
/// Checks whether user is validUser or not
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
[Route("ValidateUser")]
[HttpGet]
public IHttpActionResult ValidateUser([FromUri] LoginParameters parameters)
{
if (string.IsNullOrWhiteSpace(parameters.UserName) || string.IsNullOrWhiteSpace(parameters.Password))
return BadRequest("Invalid UserName or Password");
var ouserInformationDTO = _userService.ValidateUser(parameters.UserName, parameters.Password);
if (ouserInformationDTO == null)
{
return BadRequest();
}
return Ok(ouserInformationDTO);
}
/// <summary>
/// Gets the List of All users
/// </summary>
/// <returns></returns>
[Route("GetAllUsers")]
[HttpGet]
public IHttpActionResult GetAllUsers()
{
var user = _userService.GetAllUsers();
return Ok(user);
}
/// <summary>
/// Get UserDetails
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
[Route("GetUser")]
[HttpGet]
public IHttpActionResult GetUserByID(int userID)
{
if (userID > 0)
{
var oUserDTO = _userService.GetUserByID(userID);
return Ok(oUserDTO);
}
return BadRequest();
}
}
}
<file_sep>using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model.Mapping
{
public class RolesMapping: ClassMap<Roles>
{
public RolesMapping()
{
Table("Roles");
Id(x => x.RoleID, "RoleID");
Map(x => x.Name, "Name");
}
}
}
<file_sep>using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model.Mapping
{
public class ConsultationFeeMapping : ClassMap<ConsulatationFee>
{
public ConsultationFeeMapping()
{
Table("ConsultationFee");
Id(x => x.ConsulatationFeeID, "ConsulatationFeeID");
Map(x => x.DoctorID, "DoctorID").CustomType<int>();
Map(x => x.HospitalID, "HospitalID").CustomType<int>();
Map(x => x.FeeAmount, "FeeAmount");
Map(x => x.DoctorAmount, "DoctorAmount");
Map(x => x.StartDate, "StartDate");
Map(x => x.EndDate, "EndDate");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class ConsulatationFeeDTO
{
public int ConsulatationFeeID { get; set; }
public int DoctorID { get; set; }
public int HospitalID { get; set; }
public float FeeAmount { get; set; }
public float DoctorAmount { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
}
<file_sep>using HmsAPI.Dto;
using HmsAPI.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace HmsAPI.Controllers
{
[RoutePrefix("api/v1/PatientMedicine")]
public class PatientMedicineController: ApiController
{
private readonly IPatientMedicineService _patientMedicineService;
public PatientMedicineController(IPatientMedicineService patientMedicineService)
{
_patientMedicineService = patientMedicineService;
}
/// <summary>
/// Adds PatientMedicine Info
/// </summary>
/// <param name="patientMedicineDTO"></param>
/// <returns></returns>
[Route("PatientMedicine")]
[HttpPost]
public IHttpActionResult AddPatientMedicine([FromBody] PatientMedicineDTO patientMedicineDTO)
{
if (patientMedicineDTO == null)
{
return BadRequest();
}
var results = _patientMedicineService.AddMedicine(patientMedicineDTO);
return Ok(results);
}
/// <summary>
/// Gets PatientMedicine Info
/// </summary>
/// <param name="patientMedicineID"></param>
/// <returns></returns>
[Route("GetMedicine")]
[HttpGet]
public IHttpActionResult GetPatientMedicineByID(int patientMedicineID)
{
if(patientMedicineID > 0)
{
var oPatientMedicineDTO = _patientMedicineService.GetMedicineByID(patientMedicineID);
return Ok(oPatientMedicineDTO);
}
return BadRequest();
}
/// <summary>
/// Gets PatientMedicine Info per Appointment
/// </summary>
/// <param name="appointmentID"></param>
/// <returns></returns>
[Route("Getmedicines")]
[HttpGet]
public IHttpActionResult GetMedicinesByAppointmnetID(int appointmentID)
{
if (appointmentID > 0)
{
var oPatientMedicineDTO = _patientMedicineService.GetMedicinesByAppointmnetID(appointmentID);
return Ok(oPatientMedicineDTO);
}
return BadRequest();
}
/// <summary>
/// Gets PatientMedicine Info for Specific User
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
[Route("GetmedicinesByUser")]
[HttpGet]
public IHttpActionResult GetMedicinesByUserID(int userID)
{
if (userID > 0)
{
var oPatientMedicineDTO = _patientMedicineService.GetMedicinesByUserID(userID);
return Ok(oPatientMedicineDTO.ToList());
}
return BadRequest();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HmsAPI.Model;
namespace HmsAPI.DataAccess
{
public interface IAppointmentRepository
{
Appointment SaveorUpdate(Appointment obj);
IEnumerable<Appointment> GetAll();
Appointment GetAppointmentByID(int AppointmentID);
void DeleteAppointment(int AppointmentID);
List<Appointment> GetAppointmentByUserID(int userID);
List<DoctorAppointment> GetAppointments(int doctorID, DateTime date);
List<Appointment> GetAppointmentsByDoctorID(int doctorID, DateTime date);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class PatientMedicineDTO
{
public int PatientMedicineID { get; set; }
public int UserID { get; set; }
public string MedicineDescription { get; set; }
public int AppointmentID { get; set; }
}
}
<file_sep>using HmsAPI.DataAccess;
using HmsAPI.Dto;
using HmsAPI.Model;
using HmsAPI.Services.Interfaces;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services
{
public class PatientMedicineService: IPatientMedicineService
{
private ILog log = LogManager.GetLogger(typeof(RolesService));
public readonly IPatientMedicineRepository _patientMedicineRepository;
public PatientMedicineService(IPatientMedicineRepository patientMedicineRepository)
{
_patientMedicineRepository = patientMedicineRepository;
}
public PatientMedicineDTO AddMedicine(PatientMedicineDTO obj)
{
try
{
var objMedicine = ConvertTOModel(obj);
var medicine = _patientMedicineRepository.SaveorUpdate(objMedicine);
log.Info("PatientMedicine info Added Successfully");
return ConvertTODTO(medicine);
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while Adding new PatientMedicine Ex:{0}", ex.Message);
return null;
}
}
public PatientMedicineDTO GetMedicineByID(int patientMedicineID)
{
try
{
var patientMedicine = _patientMedicineRepository.GetMedicineByID(patientMedicineID);
return ConvertTODTO(patientMedicine);
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while Adding new PatientMedicine info Ex:{0}", ex.Message);
return null;
}
}
public List<PatientMedicineDTO> GetAllMedicines()
{
try
{
List<PatientMedicineDTO> patientMedicineDTOList = new List<PatientMedicineDTO>();
IEnumerable<PatientMedicine> patientMedicines = _patientMedicineRepository.GetAll();
foreach (var medicine in patientMedicines)
{
var medicineDTO = ConvertTODTO(medicine);
patientMedicineDTOList.Add(medicineDTO);
}
return patientMedicineDTOList;
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retreiving list of PatientMedicine info Ex:{0}", ex.Message);
return null;
}
}
public PatientMedicineDTO GetMedicinesByAppointmnetID(int appointmentID)
{
try
{
var results = _patientMedicineRepository.GetMedicinesByAppointmnetID(appointmentID);
return ConvertTODTO(results);
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retreiving PatientMedicines by Appointment info Ex:{0}", ex.Message);
return null;
}
}
public List<PatientMedicineDTO> GetMedicinesByUserID(int userID)
{
try
{
List<PatientMedicineDTO> patientMedicineDTOList = new List<PatientMedicineDTO>();
IEnumerable<PatientMedicine> patientMedicines = _patientMedicineRepository.GetMedicinesByUserID(userID);
foreach (var medicine in patientMedicines)
{
var medicineDTO = ConvertTODTO(medicine);
patientMedicineDTOList.Add(medicineDTO);
}
return patientMedicineDTOList;
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retreiving all the list of PatientMedicines Ex:{0}", ex.Message);
return null;
}
}
public PatientMedicine ConvertTOModel(PatientMedicineDTO obj)
{
var patientMedicine = new PatientMedicine()
{
PatientMedicineID = obj.PatientMedicineID,
AppointmentID = obj.AppointmentID,
MedicineDescription = obj.MedicineDescription,
UserID = obj.UserID
};
return patientMedicine;
}
public PatientMedicineDTO ConvertTODTO(PatientMedicine obj)
{
var patientMedicineDTO = new PatientMedicineDTO()
{
PatientMedicineID = obj.PatientMedicineID,
AppointmentID = obj.AppointmentID,
MedicineDescription = obj.MedicineDescription,
UserID = obj.UserID
};
return patientMedicineDTO;
}
}
}
<file_sep>using HmsAPI.DataAccess;
using HmsAPI.Dto;
using HmsAPI.Model;
using HmsAPI.Services.Interfaces;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services
{
public class LoginHistoryService: ILoginHistoryService
{
private ILog log = LogManager.GetLogger(typeof(LoginHistoryService));
public readonly ILoginHistoryRepository _loginHistoryRepository;
public LoginHistoryService(ILoginHistoryRepository loginHistoryRepository)
{
_loginHistoryRepository = loginHistoryRepository;
}
public LoginHistoryDTO AddLoginHistory(LoginHistoryDTO obj)
{
try
{
var objHistory = ConvertTOModel(obj);
var loginHistory = _loginHistoryRepository.SaveorUpdate(objHistory);
log.Info("LoginHistory saved Successfully");
return ConvertTODTO(loginHistory);
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while adding LoginHistory Information Ex:{0}", ex.Message);
return null;
}
}
public LoginHistoryDTO GetLoginHistoryByID(int loginHistoryID)
{
try
{
var loginHistory = _loginHistoryRepository.GetLoginHistoryByID(loginHistoryID);
return ConvertTODTO(loginHistory);
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retreiving LoginHistory Information Ex:{0}", ex.Message);
return null;
}
}
public List<LoginHistoryDTO> GetAllHistory()
{
try
{
List<LoginHistoryDTO> loginHistoryDTOList = new List<LoginHistoryDTO>();
IEnumerable<LoginHistory> loginHistoryDTO = _loginHistoryRepository.GetAll();
foreach (var history in loginHistoryDTO)
{
var historyDTO = ConvertTODTO(history);
loginHistoryDTOList.Add(historyDTO);
}
return loginHistoryDTOList;
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while retreiving all the List of LoginHistory Information Ex:{0}", ex.Message);
return null;
}
}
public LoginHistory ConvertTOModel(LoginHistoryDTO obj)
{
var loginHistory = new LoginHistory()
{
LoginHistoryID = obj.LoginHistoryID,
StartTime = obj.StartTime,
EndTime = obj.EndTime,
UserID = obj.UserID
};
return loginHistory;
}
public LoginHistoryDTO ConvertTODTO(LoginHistory obj)
{
var loginHistoryDTO = new LoginHistoryDTO()
{
LoginHistoryID = obj.LoginHistoryID,
StartTime = obj.StartTime,
EndTime = obj.EndTime,
UserID = obj.UserID
};
return loginHistoryDTO;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class Roles
{
public virtual int RoleID { get; set; }
public virtual string Name { get; set; }
public override bool Equals(object obj)
{
return obj is Roles roles &&
RoleID == roles.RoleID &&
Name == roles.Name;
}
public override int GetHashCode()
{
int hashCode = -1773594654;
hashCode = hashCode * -1521134295 + RoleID.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name);
return hashCode;
}
}
}
<file_sep>using HmsAPI.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services.Interfaces
{
public interface IHospitalService
{
HospitalDTO AddHospital(HospitalDTO obj);
HospitalDTO GetHospitalsByID(int hospitalID);
List<HospitalDTO> GetAllHospitals();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class Doctor
{
public virtual int DoctorID { get; set; }
public virtual string LicenseNumber { get; set; }
public virtual string Specialist { get; set; }
public virtual char Active { get; set; }
public virtual int VerifiedBy { get; set; }
public virtual int UserID { get; set; }
public override bool Equals(object obj)
{
return obj is Doctor doctor &&
DoctorID == doctor.DoctorID &&
LicenseNumber == doctor.LicenseNumber &&
Specialist == doctor.Specialist &&
Active == doctor.Active &&
VerifiedBy == doctor.VerifiedBy &&
UserID == doctor.UserID;
}
public override int GetHashCode()
{
int hashCode = 1370643586;
hashCode = hashCode * -1521134295 + DoctorID.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(LicenseNumber);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Specialist);
hashCode = hashCode * -1521134295 + Active.GetHashCode();
hashCode = hashCode * -1521134295 + VerifiedBy.GetHashCode();
hashCode = hashCode * -1521134295 + UserID.GetHashCode();
return hashCode;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class UserRolesDTO
{
public int UserRoleID { get; set; }
public int RoleID { get; set; }
public int UserID { get; set; }
public int HospitalID { get; set; }
}
}
<file_sep>using HmsAPI.DataAccess;
using HmsAPI.DataAccess.Interface;
using HmsAPI.Dto;
using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services
{
public class UserAppointmentService
{
public readonly IUserRepository _userTableRepository;
public readonly IAppointmentRepository _appointmentRepository;
public readonly IHospitalRepository _hospitalRepository;
public UserAppointmentService(IUserRepository userTableRepository, IAppointmentRepository appointmentRepository, IHospitalRepository hospitalRepository)
{
_userTableRepository = userTableRepository;
_appointmentRepository = appointmentRepository;
_hospitalRepository = hospitalRepository;
}
public List<UserAppointmentDTO> GetUserAppointments(int userID)
{
var objUserAppoinytmentList = new List<UserAppointmentDTO>();
var objAppointmnet = _appointmentRepository.GetAppointmentByUserID(userID);
foreach (var objApp in objAppointmnet)
{
var objuser = _userTableRepository.GetUsersByDoctorID(objApp.DoctorID);
var objhospital = _hospitalRepository.GetHospitalByDoctorID(objApp.DoctorID);
UserAppointmentDTO userAppointmnetDTO = new UserAppointmentDTO
{
AppointmentID = objApp.AppointmentID,
UserID = objApp.UserID,
DoctorID = objApp.DoctorID,
DoctorName = objuser.FirstName + " " + objuser.LastName,
StartTime = objApp.StartTime,
EndTime = objApp.EndTime,
HospitalName = objhospital.Name
};
objUserAppoinytmentList.Add(userAppointmnetDTO);
}
return objUserAppoinytmentList;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class DoctorAppointment
{
public virtual int DoctorID { get; set; }
public virtual int UserID { get; set; }
public virtual int AppointmentID { get; set; }
public virtual string UserName { get; set; }
public virtual DateTime StartTime { get; set; }
public virtual DateTime EndTime { get; set; }
public virtual string HospitalName { get; set; }
public virtual DateTime Date { get; set; }
public override bool Equals(object obj)
{
return obj is DoctorAppointment appointment &&
DoctorID == appointment.DoctorID &&
UserID == appointment.UserID &&
AppointmentID == appointment.AppointmentID &&
UserName == appointment.UserName &&
StartTime == appointment.StartTime &&
EndTime == appointment.EndTime &&
HospitalName == appointment.HospitalName &&
Date == appointment.Date;
}
public override int GetHashCode()
{
int hashCode = 1968497320;
hashCode = hashCode * -1521134295 + DoctorID.GetHashCode();
hashCode = hashCode * -1521134295 + UserID.GetHashCode();
hashCode = hashCode * -1521134295 + AppointmentID.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(UserName);
hashCode = hashCode * -1521134295 + StartTime.GetHashCode();
hashCode = hashCode * -1521134295 + EndTime.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(HospitalName);
hashCode = hashCode * -1521134295 + Date.GetHashCode();
return hashCode;
}
}
}
<file_sep>using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model.Mapping
{
public class AppointmentMapping : ClassMap<Appointment>
{
public AppointmentMapping()
{
Table("Appointment");
Id(x => x.AppointmentID, "AppointmentID");
Map(x => x.UserID, "UserID").CustomType<int>();
Map(x => x.DoctorCalendarID, "DoctorCalendarID").CustomType<int>();
Map(x => x.DoctorID, "DoctorID").CustomType<int>();
Map(x => x.AppDate, "AppDate");
Map(x => x.StartTime, "StartTime");
Map(x => x.EndTime, "EndTime");
}
}
}
<file_sep>using HmsAPI.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services.Interfaces
{
public interface IRolesService
{
RolesDTO AddRoles(RolesDTO obj);
RolesDTO GetRolesByID(int roleID);
List<RolesDTO> GetAllRoles();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class User
{
public virtual int UserID { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual DateTime DOB { get; set; }
public virtual char Gender { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public virtual string EmailID { get; set; }
public virtual string PhoneNumber { get; set; }
public override bool Equals(object obj)
{
return obj is User user &&
UserID == user.UserID &&
FirstName == user.FirstName &&
LastName == user.LastName &&
DOB == user.DOB &&
Gender == user.Gender &&
UserName == user.UserName &&
Password == <PASSWORD> &&
EmailID == user.EmailID &&
PhoneNumber == user.PhoneNumber;
}
public override int GetHashCode()
{
int hashCode = 954011070;
hashCode = hashCode * -1521134295 + UserID.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(FirstName);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(LastName);
hashCode = hashCode * -1521134295 + DOB.GetHashCode();
hashCode = hashCode * -1521134295 + Gender.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(UserName);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Password);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(EmailID);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(PhoneNumber);
return hashCode;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class UserRoles
{
public virtual int UserRoleID { get; set; }
public virtual int RoleID { get; set; }
public virtual int UserID { get; set; }
public virtual int HospitalID { get; set; }
public override bool Equals(object obj)
{
return obj is UserRoles roles &&
UserRoleID == roles.UserRoleID &&
RoleID == roles.RoleID &&
UserID == roles.UserID &&
HospitalID == roles.HospitalID;
}
public override int GetHashCode()
{
int hashCode = -1482740488;
hashCode = hashCode * -1521134295 + UserRoleID.GetHashCode();
hashCode = hashCode * -1521134295 + RoleID.GetHashCode();
hashCode = hashCode * -1521134295 + UserID.GetHashCode();
hashCode = hashCode * -1521134295 + HospitalID.GetHashCode();
return hashCode;
}
}
}
<file_sep>using HmsAPI.DataAccess.Interface;
using HmsAPI.Dto;
using HmsAPI.Model;
using HmsAPI.Services.Interfaces;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services
{
public class HospitalService: IHospitalService
{
private ILog log = LogManager.GetLogger(typeof(HospitalService));
public readonly IHospitalRepository _hospitalRepository;
public HospitalService(IHospitalRepository hospitalRepository)
{
_hospitalRepository = hospitalRepository;
}
public HospitalDTO AddHospital(HospitalDTO obj)
{
try
{
var objHospital = ConvertTOModel(obj);
var hospital = _hospitalRepository.SaveorUpdate(objHospital);
log.Info("Hospital info Added Successfully");
return ConvertTODTO(hospital);
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while Adding new Hospital Info Ex:{0}", ex.Message);
return null;
}
}
public List<HospitalDTO> GetAllHospitals()
{
try
{
List<HospitalDTO> hospitalDTOList = new List<HospitalDTO>();
IEnumerable<Hospital> hospitalDTO = _hospitalRepository.GetAll();
foreach (var hospital in hospitalDTO)
{
var objhospitalDTO = ConvertTODTO(hospital);
hospitalDTOList.Add(objhospitalDTO);
}
return hospitalDTOList;
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while retreiving list of Hospital Details Info Ex:{0}", ex.Message);
return null;
}
}
public HospitalDTO GetHospitalsByID(int hospitalID)
{
try
{
var hospital = _hospitalRepository.GetHospitalByID(hospitalID);
return ConvertTODTO(hospital);
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while retreiving Hospital Info Info Ex:{0}", ex.Message);
return null;
}
}
public Hospital ConvertTOModel(HospitalDTO obj)
{
var Hospital = new Hospital()
{
HospitalID = obj.HospitalID,
Name = obj.Name,
PhoneNumber = obj.PhoneNumber,
EmailID = obj.EmailID,
Address = obj.Address
};
return Hospital;
}
public HospitalDTO ConvertTODTO(Hospital obj)
{
var HospitalDTO = new HospitalDTO()
{
HospitalID = obj.HospitalID,
Name = obj.Name,
PhoneNumber = obj.PhoneNumber,
EmailID = obj.EmailID,
Address = obj.Address
};
return HospitalDTO;
}
}
}
<file_sep>using HmsAPI.Dto;
using HmsAPI.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace HmsAPI.Controllers
{
[RoutePrefix("api/v1/doctorcalendar")]
public class DoctorcalendarController: ApiController
{
private readonly IDoctorCalendarService _doctorCalendarService;
public DoctorcalendarController(IDoctorCalendarService doctorCalendarService)
{
_doctorCalendarService = doctorCalendarService;
}
/// <summary>
/// Adds the DoctorCalendar Information
/// </summary>
/// <param name="doctorCalendarDTO"></param>
/// <returns></returns>
[Route("AddDoctorCalendar")]
[HttpPost]
public IHttpActionResult AddDoctorCalendar([FromBody] DoctorCalendarDTO doctorCalendarDTO)
{
if (doctorCalendarDTO == null)
{
return BadRequest();
}
var results = _doctorCalendarService.AddDoctorCalender(doctorCalendarDTO);
return Ok(results);
}
/// <summary>
/// Get DoctorCalendar Details
/// </summary>
/// <param name="doctorCalendarID"></param>
/// <returns></returns>
[Route("GetDoctorCalendar")]
public IHttpActionResult GetDoctorCalendarByID(int doctorCalendarID)
{
if (doctorCalendarID > 0)
{
var odoctorCalendarDTO = _doctorCalendarService.GetDoctorCalendarByID(doctorCalendarID);
return Ok(odoctorCalendarDTO);
}
return BadRequest();
}
/// <summary>
/// Gets all DoctorCalendar details
/// </summary>
/// <returns></returns>
[Route("GetAllDoctorsCalendar")]
[HttpGet]
public IHttpActionResult GetAllDoctorsCalendar()
{
var odoctorCalendarDTOs = _doctorCalendarService.GetAllDoctorsCalendar();
return Ok(odoctorCalendarDTOs);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class DoctorDTO
{
public int DoctorID { get; set; }
public string LicenseNumber { get; set; }
public string Specialist { get; set; }
public char Active { get; set; }
public int VerifiedBy { get; set; }
public int UserID { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class DoctorAvailabilityDTO
{
public int DoctorID { get; set; }
public int DoctorCalendarID { get; set; }
public DateTime Date { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public bool IsAvailable { get; set; }
}
}
<file_sep>using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public class SessionWrapper : IDisposable
{
private bool disposedValue;
public SessionWrapper()
{
Session = HibernateFactoryProvider.CreateSession();
}
public ISession Session { get; private set; } = null;
public void BeginTransaction()
{
Session.BeginTransaction();
}
public void Commit()
{
Session.Transaction.Commit();
}
private void RollBack()
{
if(Session.Transaction!=null && Session.Transaction.IsActive
&& !Session.Transaction.WasCommitted && !Session.Transaction.WasRolledBack)
{
Session.Transaction.Rollback();
}
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
if (Session != null)
{
RollBack();
}
Session.Dispose();
Session = null;
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
disposedValue = true;
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
// ~SessionWrapper()
// {
// // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
// Dispose(disposing: false);
// }
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
<file_sep>using HmsAPI.DataAccess;
using HmsAPI.Dto;
using HmsAPI.Model;
using HmsAPI.Services.Interfaces;
using System;
using System.Collections.Generic;
using log4net;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services
{
public class RolesService : IRolesService
{
private ILog log = LogManager.GetLogger(typeof(RolesService));
public readonly IRolesRepository _roleRepository;
public RolesService(IRolesRepository rolesRepository)
{
_roleRepository = rolesRepository;
}
public RolesDTO AddRoles(RolesDTO obj)
{
try
{
var objRole = ConvertTOModel(obj);
var role = _roleRepository.SaveorUpdate(objRole);
log.Info("Role Added Successfully");
return ConvertTODTO(role);
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while Adding new Role Ex:{0}", ex.Message);
return null;
}
}
public RolesDTO GetRolesByID(int roleID)
{
try
{
var role = _roleRepository.GetRolesByID(roleID);
return ConvertTODTO(role);
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retrieving Role details Ex:{0}", ex.Message);
return null;
}
}
public List<RolesDTO> GetAllRoles()
{
try
{
List<RolesDTO> rolesDTOList = new List<RolesDTO>();
IEnumerable<Roles> roles = _roleRepository.GetAll();
foreach (var role in roles)
{
var roleDTO = ConvertTODTO(role);
rolesDTOList.Add(roleDTO);
}
return rolesDTOList;
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retrieving all the list of Role details Ex:{0}", ex.Message);
return null;
}
}
public Roles ConvertTOModel(RolesDTO obj)
{
var roles = new Roles()
{
RoleID = obj.RoleID,
Name = obj.Name
};
return roles;
}
public RolesDTO ConvertTODTO(Roles obj)
{
var rolesDTO = new RolesDTO()
{
RoleID = obj.RoleID,
Name = obj.Name
};
return rolesDTO;
}
}
}
<file_sep>using HmsAPI.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services.Interfaces
{
public interface IAppointmentService
{
AppointmentDTO AddAppointment(AppointmentDTO obj);
AppointmentDTO GetAppointmentByID(int appointmentID);
List<AppointmentDTO> GetAllAppointments();
List<DoctorAppointmentDTO> GetDoctorAppointmentByDate(int doctorID, DateTime date);
}
}
<file_sep>using HmsAPI.Dto;
using HmsAPI.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace HmsAPI.Controllers
{
[RoutePrefix("api/v1/role")]
public class RoleController: ApiController
{
private readonly IRolesService _roleService;
public RoleController(IRolesService roleService)
{
_roleService = roleService;
}
/// <summary>
/// Adds a new Role Information
/// </summary>
/// <param name="roleDTO"></param>
/// <returns></returns>
[Route("AddRole")]
[HttpPost]
public IHttpActionResult AddRoles([FromBody] RolesDTO roleDTO)
{
if (roleDTO == null)
{
return BadRequest();
}
var results = _roleService.AddRoles(roleDTO);
return Ok(results);
}
/// <summary>
/// Get The Role Info
/// </summary>
/// <param name="roleID"></param>
/// <returns></returns>
[Route("GetRole")]
[HttpGet]
public IHttpActionResult GetRoleByID(int roleID)
{
if (roleID > 0)
{
var oRoleDTO = _roleService.GetRolesByID(roleID);
return Ok(oRoleDTO);
}
return BadRequest();
}
}
}
<file_sep>using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public class HibernateFactoryProvider
{
static FluentNHibernateHelper NHibernateHelper;
private static FluentNHibernateHelper FluentNHibernateHelper
{
get
{
if(NHibernateHelper == null)
{
NHibernateHelper = new FluentNHibernateHelper();
}
return NHibernateHelper;
}
}
public static ISession CreateSession()
{
ISession session = null;
session = FluentNHibernateHelper.GetSessionFactory().OpenSession();
return session;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class DoctorCalendar
{
public virtual int DoctorCalendarID { get; set; }
public virtual int DoctorID { get; set; }
public virtual DateTime Date { get; set; }
public virtual DateTime StartTime { get; set; }
public virtual DateTime EndTime { get; set; }
public virtual int HospitalID { get; set; }
public override bool Equals(object obj)
{
return obj is DoctorCalendar calendar &&
DoctorCalendarID == calendar.DoctorCalendarID &&
DoctorID == calendar.DoctorID &&
Date == calendar.Date &&
StartTime == calendar.StartTime &&
EndTime == calendar.EndTime &&
HospitalID == calendar.HospitalID;
}
public override int GetHashCode()
{
int hashCode = 292862208;
hashCode = hashCode * -1521134295 + DoctorCalendarID.GetHashCode();
hashCode = hashCode * -1521134295 + DoctorID.GetHashCode();
hashCode = hashCode * -1521134295 + Date.GetHashCode();
hashCode = hashCode * -1521134295 + StartTime.GetHashCode();
hashCode = hashCode * -1521134295 + EndTime.GetHashCode();
hashCode = hashCode * -1521134295 + HospitalID.GetHashCode();
return hashCode;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class UserDTO
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
public char Gender { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string EmailID { get; set; }
public string PhoneNumber { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class DoctorAppointmentDTO
{
//DoctorID,UserID,AppointmentID,UserName,StartTime,EndTime,HospitalName,Date
public int DoctorID { get; set; }
public int UserID { get; set; }
public int AppointmentID { get; set; }
public string UserName { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string HospitalName { get; set; }
public DateTime Date { get; set; }
}
}
<file_sep>using HmsAPI.DataAccess.Interface;
using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess.Repository
{
public class HospitalRepository : BaseRepository<Hospital>, IHospitalRepository
{
public void DeleteHospital(int hospitalID)
{
var objHospital = GetHospitalByID(hospitalID);
Delete(objHospital);
}
public Hospital GetHospitalByID(int hospitalID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objHospital = session.Query<Hospital>().Where(x => x.HospitalID == hospitalID).FirstOrDefault();
return objHospital;
}
}
}
public Hospital GetHospitalByDoctorID(int doctorID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var query = "select h.* from Doctor d join DoctorCalendar dc on d.DoctorID = dc.DoctorID and dc.DoctorID = "+ doctorID + " inner join Hospital h on dc.HospitalID = h.HospitalID";
var results = session.CreateSQLQuery(query).AddEntity(typeof(Hospital)).List<Hospital>().FirstOrDefault();
return results;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto.Request
{
public class AppointmentParameters
{
public int DoctorID { get; set; }
public DateTime AppDate { get; set; }
}
}
<file_sep>using HmsAPI.DataAccess;
using HmsAPI.Dto;
using HmsAPI.Model;
using HmsAPI.Services.Interfaces;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services
{
public class DoctorService : IDoctorService
{
private ILog log = LogManager.GetLogger(typeof(DoctorService));
public readonly IDoctorRepository _doctorRepository;
public readonly IDoctorCalendarRepository _doctorCalendarRepository;
public readonly IAppointmentRepository _appointmentRepository;
public DoctorService(IDoctorRepository doctorRepository, IDoctorCalendarRepository doctorCalendarRepository, IAppointmentRepository appointmentRepository)
{
_doctorRepository = doctorRepository;
_doctorCalendarRepository = doctorCalendarRepository;
_appointmentRepository = appointmentRepository;
}
public DoctorDTO AddDoctor(DoctorDTO obj)
{
try
{
var objDoctor = ConvertTOModel(obj);
var doctor = _doctorRepository.SaveorUpdate(objDoctor);
log.Info("Doctor info Added Successfully");
return ConvertTODTO(doctor);
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while Adding new Doctor Info Ex:{0}", ex.Message);
return null;
}
}
public DoctorDTO GetDoctorsByID(int doctorID)
{
try
{
var doctor = _doctorRepository.GetDoctorByID(doctorID);
return ConvertTODTO(doctor);
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retreiving Doctor Information Ex:{0}", ex.Message);
return null;
}
}
public List<DoctorDTO> GetDoctorsByHospitalID(int hospitalID)
{
try
{
List<DoctorDTO> doctorDTOList = new List<DoctorDTO>();
IEnumerable<Doctor> doctor = _doctorRepository.GetDoctorsByHospitalID(hospitalID);
foreach (var item in doctor)
{
var doctorDTO = ConvertTODTO(item);
doctorDTOList.Add(doctorDTO);
}
return doctorDTOList;
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retrieving Doctor Information Ex:{0}", ex.Message);
return null;
}
}
public List<DoctorDTO> GetDoctorsByspecialization(string specialist)
{
try
{
List<DoctorDTO> doctorDTOList = new List<DoctorDTO>();
IEnumerable<Doctor> doctor = _doctorRepository.GetDoctorsBySpecialization(specialist);
foreach (var item in doctor)
{
var doctorDTO = ConvertTODTO(item);
doctorDTOList.Add(doctorDTO);
}
return doctorDTOList;
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while retrieving List of Doctor Information by Specialization Ex:{0}", ex.Message);
return null;
}
}
public List<DoctorDTO> GetAllDoctors()
{
try
{
List<DoctorDTO> doctorDTOList = new List<DoctorDTO>();
IEnumerable<Doctor> doctorDTO = _doctorRepository.GetAll();
foreach (var doctor in doctorDTO)
{
var objdoctorDTO = ConvertTODTO(doctor);
doctorDTOList.Add(objdoctorDTO);
}
return doctorDTOList;
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retrieving List of Doctor Information Ex:{0}", ex.Message);
return null;
}
}
public List<DoctorAvailabilityDTO> GetDoctorAvailability(int doctorID, DateTime date, int hospitalID)
{
try
{
List<DoctorAvailabilityDTO> doctorAvailabilityDTOList = new List<DoctorAvailabilityDTO>();
IEnumerable<DoctorCalendar> doctorCalendarDTO = _doctorCalendarRepository.GetDoctorCalendar(doctorID, date, hospitalID);
//var appointements = getapoointmnetbydoctorcalendarid()
foreach (var item in doctorCalendarDTO)
{
var doctorAppointments = _appointmentRepository.GetAppointmentsByDoctorID(item.DoctorID, item.Date);
var startTime = item.StartTime;// item.starttime-10AM
var endTime = item.StartTime.AddMinutes(15); //item.endtime = 11am
while (endTime <= item.EndTime)
{
bool availability = !doctorAppointments.Where(x => x.EndTime == endTime && x.StartTime == startTime).Any();
var objDTO = new DoctorAvailabilityDTO
{
DoctorCalendarID = item.DoctorCalendarID,
Date = item.Date,
DoctorID = item.DoctorID,
StartTime = startTime,
EndTime = endTime,
IsAvailable = availability
};
doctorAvailabilityDTOList.Add(objDTO);
startTime = endTime;
endTime = endTime.AddMinutes(15);
}
}
return doctorAvailabilityDTOList;
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while retrieving List of DoctorAvailability Information Ex:{0}", ex.Message);
return null;
}
}
public Doctor ConvertTOModel(DoctorDTO obj)
{
var doctor = new Doctor()
{
DoctorID = obj.DoctorID,
UserID = obj.UserID,
Active = obj.Active,
Specialist = obj.Specialist,
LicenseNumber = obj.LicenseNumber,
VerifiedBy = obj.VerifiedBy
};
return doctor;
}
public DoctorDTO ConvertTODTO(Doctor obj)
{
var doctorDTO = new DoctorDTO()
{
DoctorID = obj.DoctorID,
UserID = obj.UserID,
Active = obj.Active,
Specialist = obj.Specialist,
LicenseNumber = obj.LicenseNumber,
VerifiedBy = obj.VerifiedBy
};
return doctorDTO;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto.Request
{
public class DoctorParameters
{
public int DoctorID { get; set; }
public DateTime Docdate { get; set; }
public int HospitalId { get; set; }
}
}
<file_sep>using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model.Mapping
{
public class UserRolesMapping : ClassMap<UserRoles>
{
public UserRolesMapping()
{
Table("UserRoles");
Id(x => x.UserRoleID, "UserRoleID");
Map(x => x.UserID, "UserID").CustomType<int>();
Map(x => x.RoleID, "RoleID").CustomType<int>();
Map(x => x.HospitalID, "HospitalID").CustomType<int>();
}
}
}
<file_sep>using HmsAPI.Dto;
using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services.Interfaces
{
public interface IPatientMedicineService
{
PatientMedicineDTO AddMedicine(PatientMedicineDTO obj);
PatientMedicineDTO GetMedicineByID(int patientMedicineID);
List<PatientMedicineDTO> GetAllMedicines();
PatientMedicineDTO GetMedicinesByAppointmnetID(int appointmentID);
List<PatientMedicineDTO> GetMedicinesByUserID(int userID);
}
}
<file_sep>using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model.Mapping
{
public class DoctorMapping : ClassMap<Doctor>
{
public DoctorMapping()
{
Table("Doctor");
Id(x => x.DoctorID, "DoctorID");
Map(x => x.LicenseNumber, "LicenseNumber");
Map(x => x.Specialist, "Specialist");
Map(x => x.Active, "Active");
Map(x => x.VerifiedBy, "VerifiedBy").CustomType<int>();
Map(x => x.UserID, "UserID").CustomType<int>();
}
}
}
<file_sep>using HmsAPI.DataAccess;
using HmsAPI.DataAccess.Interface;
using HmsAPI.DataAccess.Repository;
using HmsAPI.Services;
using HmsAPI.Services.Interfaces;
using Microsoft.Practices.Unity;
using Owin;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using Unity;
namespace HmsAPI
{
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
Console.WriteLine("Terst Configuration");
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var container = new UnityContainer();
var assemblies = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "Hms*.dll").Select(x => Assembly.LoadFile(x)).ToArray<Assembly>();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterTypes(AllClasses.FromAssemblies(assemblies), WithMappings.FromMatchingInterface, WithName.Default, WithLifetime.None, null, true
);
config.DependencyResolver = new UnityResolver(container);
SwaggerConfig.Register(config);
appBuilder.UseWebApi(config);
}
}
}
<file_sep>using HmsAPI.Model;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public class BaseRepository<T> where T : class
{
public T SaveorUpdate(T obj)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
sessionWrapper.BeginTransaction();
using (var session = sessionWrapper.Session)
{
session.SaveOrUpdate(obj);
sessionWrapper.Commit();
}
}
return obj;
}
public IEnumerable<T> GetAll()
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var results = session.QueryOver<T>().List();
return results;
}
}
}
public void Delete(T obj)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
sessionWrapper.BeginTransaction();
using (var session = sessionWrapper.Session)
{
session.Delete(obj);
sessionWrapper.Commit();
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class PatientMedicine
{
public virtual int PatientMedicineID { get; set; }
public virtual int UserID { get; set; }
public virtual string MedicineDescription { get; set; }
public virtual int AppointmentID { get; set; }
public override bool Equals(object obj)
{
return obj is PatientMedicine medicine &&
PatientMedicineID == medicine.PatientMedicineID &&
UserID == medicine.UserID &&
MedicineDescription == medicine.MedicineDescription &&
AppointmentID == medicine.AppointmentID;
}
public override int GetHashCode()
{
int hashCode = -1443886894;
hashCode = hashCode * -1521134295 + PatientMedicineID.GetHashCode();
hashCode = hashCode * -1521134295 + UserID.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(MedicineDescription);
hashCode = hashCode * -1521134295 + AppointmentID.GetHashCode();
return hashCode;
}
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess.Interface
{
public interface IConsulatationFeeRepository
{
ConsulatationFee SaveorUpdate(ConsulatationFee obj);
IEnumerable<ConsulatationFee> GetAll();
ConsulatationFee GetFeeByID(int ConsulatationFeeID);
void DeleteConsultationFee(int ConsulatationFeeID);
}
}
<file_sep>using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model.Mapping
{
public class DoctorCalendarMapping: ClassMap<DoctorCalendar>
{
public DoctorCalendarMapping()
{
Table("DoctorCalendar");
Id(x => x.DoctorCalendarID, "DoctorCalendarID");
Map(x => x.DoctorID, "DoctorID").CustomType<int>();
Map(x => x.Date, "Date");
Map(x => x.StartTime, "StartTime");
Map(x => x.EndTime, "EndTime");
Map(x => x.HospitalID, "HospitalID");
}
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public interface IDoctorCalendarRepository
{
DoctorCalendar SaveorUpdate(DoctorCalendar obj);
IEnumerable<DoctorCalendar> GetAll();
DoctorCalendar GetDoctorCalendarByID(int DoctorCalendarID);
void DeleteDoctorCalendar(int DoctorCalendarID);
List<DoctorCalendar> GetDoctorCalendar(int doctorID, DateTime date, int hospitalID);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class LoginHistory
{
public virtual int LoginHistoryID { get; set; }
public virtual int UserID { get; set; }
public virtual DateTime StartTime { get; set; }
public virtual DateTime EndTime { get; set; }
public override bool Equals(object obj)
{
return obj is LoginHistory history &&
LoginHistoryID == history.LoginHistoryID &&
UserID == history.UserID &&
StartTime == history.StartTime &&
EndTime == history.EndTime;
}
public override int GetHashCode()
{
int hashCode = 816852927;
hashCode = hashCode * -1521134295 + LoginHistoryID.GetHashCode();
hashCode = hashCode * -1521134295 + UserID.GetHashCode();
hashCode = hashCode * -1521134295 + StartTime.GetHashCode();
hashCode = hashCode * -1521134295 + EndTime.GetHashCode();
return hashCode;
}
}
}
<file_sep>using Microsoft.Practices.Unity;
using System;
using System.IO;
using System.Reflection;
using System.Web.Http;
using Unity;
using Unity.WebApi;
using System.Linq;
namespace HmsAPI
{
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
var assemblies = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "Hms*.dll").Select(x => Assembly.LoadFile(x)).ToArray<Assembly>();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterTypes(AllClasses.FromAssemblies(assemblies), WithMappings.FromMatchingInterface, WithName.Default, WithLifetime.None, null, true
);
GlobalConfiguration.Configuration.DependencyResolver = new UnityResolver(container);
}
}
}<file_sep>using HmsAPI.Model;
using System.Linq;
namespace HmsAPI.DataAccess
{
public class UserRepository : BaseRepository<User>, IUserRepository
{
public void DeleteUser(int UserID)
{
var objUser = GetUsersByID(UserID);
Delete(objUser);
}
public User GetUsersByID(int userID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objUser = session.Query<User>().Where(x => x.UserID == userID).FirstOrDefault();
return objUser;
}
}
}
public User ValidateUser(string userName,string password)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objUser = session.Query<User>().Where(x => x.UserName == userName && x.Password == <PASSWORD>) .FirstOrDefault();
return objUser;
}
}
}
public User GetUsersByDoctorID(int doctorID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var query = "select u.* from UserTable u join Doctor d on u.UserID = d.UserID where d.DoctorID =" + doctorID;
var results = session.CreateSQLQuery(query).AddEntity(typeof(User)).List<User>().FirstOrDefault();
return results;
}
}
}
}
}
<file_sep>using HmsAPI.Dto;
using HmsAPI.Dto.Request;
using HmsAPI.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace HmsAPI.Controllers
{
/// <summary>
/// Provides functionality/Methods to the Appointment.
/// </summary>
[RoutePrefix("api/v1/appointment")]
public class AppointmentController : ApiController
{
private readonly IAppointmentService _appointmentService;
/// <summary>
/// Public constructor to initialize appointmentService instance
/// </summary>
public AppointmentController(IAppointmentService appointmentService)
{
_appointmentService = appointmentService;
}
/// <summary>
/// Adds new Appointment Information
/// </summary>
/// <param name="appointmentDTO"></param>
/// <returns></returns>
[Route("AddAppointment")]
[HttpPost]
public IHttpActionResult AddAppointment([FromBody] AppointmentDTO appointmentDTO)
{
if (appointmentDTO == null)
{
return BadRequest();
}
var results = _appointmentService.AddAppointment(appointmentDTO);
return Ok(results);
}
/// <summary>
/// Get Appointmnent Details
/// </summary>
/// <param name="appointmentID"></param>
/// <returns></returns>
[Route("GetAppointment")]
[HttpGet]
public IHttpActionResult GetAppointmentByID(int appointmentID)
{
if (appointmentID > 0)
{
var appointmentDTO = _appointmentService.GetAppointmentByID(appointmentID);
return Ok(appointmentDTO);
}
return BadRequest();
}
/// <summary>
/// Gets List of Appointments
/// </summary>
/// <returns></returns>
[Route("GetAllAppointments")]
[HttpGet]
public IHttpActionResult GetAllAppointments()
{
var Appointments = _appointmentService.GetAllAppointments();
return Ok(Appointments);
}
/// <summary>
/// Get Appointment Details specific to Doctor and Date
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
/// Changing Get method to post to receive parameters in Body
[Route("GetDoctorAppointment")]
[HttpPost]
public IHttpActionResult GetDoctorAppointmentByDate([FromBody] AppointmentParameters parameters)
{
if (parameters.DoctorID > 0 && parameters.AppDate != null)
{
var oDoctorAppointmentDTO = _appointmentService.GetDoctorAppointmentByDate(parameters.DoctorID, parameters.AppDate);
return Ok(oDoctorAppointmentDTO);
}
return BadRequest();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class LoginHistoryDTO
{
public int LoginHistoryID { get; set; }
public int UserID { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
}
<file_sep>using HmsAPI.Dto;
using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public class PatientMedicineRepository : BaseRepository<PatientMedicine>, IPatientMedicineRepository
{
public PatientMedicine GetMedicineByID(int patientMedicineID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objMedicine = session.Query<PatientMedicine>().Where(x => x.PatientMedicineID == patientMedicineID).FirstOrDefault();
return objMedicine;
}
}
}
public void DeleteMedicine(int PatientMedicineID)
{
var objMedicine = GetMedicineByID(PatientMedicineID);
Delete(objMedicine);
}
public PatientMedicine GetMedicinesByAppointmnetID(int appointmentID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var results = session.Query<PatientMedicine>().Where(x => x.AppointmentID == appointmentID).FirstOrDefault();
return results;
}
}
}
public List<PatientMedicine> GetMedicinesByUserID(int userID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var results = session.Query<PatientMedicine>().Where(x => x.UserID == userID).ToList();
return results;
}
}
}
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public class LoginHistoryRepository : BaseRepository<LoginHistory>, ILoginHistoryRepository
{
public LoginHistory GetLoginHistoryByID(int loginHistoryID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objloginHistory = session.Query<LoginHistory>().Where(x => x.LoginHistoryID == loginHistoryID).FirstOrDefault();
return objloginHistory;
}
}
}
public void DeleteLoginHsitory(int LoginHistoryID)
{
var objLoginHistory = GetLoginHistoryByID(LoginHistoryID);
Delete(objLoginHistory);
}
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public class RolesRepository: BaseRepository<Roles>,IRolesRepository
{
public void DeleteRole(int RoleID)
{
var objRole = GetRolesByID(RoleID);
Delete(objRole);
}
public Roles GetRolesByID(int roleID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objRole = session.Query<Roles>().Where(x => x.RoleID == roleID).FirstOrDefault();
return objRole;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class Appointment
{
public virtual int AppointmentID { get; set; }
public virtual int UserID { get; set; }
public virtual int DoctorID { get; set; }
public virtual DateTime AppDate { get; set; }
public virtual int DoctorCalendarID { get; set; }
public virtual DateTime StartTime { get; set; }
public virtual DateTime EndTime { get; set; }
public override bool Equals(object obj)
{
return obj is Appointment appointment &&
AppointmentID == appointment.AppointmentID &&
UserID == appointment.UserID &&
DoctorID == appointment.DoctorID &&
AppDate == appointment.AppDate &&
DoctorCalendarID == appointment.DoctorCalendarID &&
StartTime == appointment.StartTime &&
EndTime == appointment.EndTime;
}
public override int GetHashCode()
{
int hashCode = 1832843767;
hashCode = hashCode * -1521134295 + AppointmentID.GetHashCode();
hashCode = hashCode * -1521134295 + UserID.GetHashCode();
hashCode = hashCode * -1521134295 + DoctorID.GetHashCode();
hashCode = hashCode * -1521134295 + AppDate.GetHashCode();
hashCode = hashCode * -1521134295 + DoctorCalendarID.GetHashCode();
hashCode = hashCode * -1521134295 + StartTime.GetHashCode();
hashCode = hashCode * -1521134295 + EndTime.GetHashCode();
return hashCode;
}
}
}
<file_sep>using HmsAPI.Dto;
using HmsAPI.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace HmsAPI.Controllers
{
[RoutePrefix("api/v1/loginhistory")]
public class LoginHistoryController: ApiController
{
private readonly ILoginHistoryService _loginHistoryService;
public LoginHistoryController(ILoginHistoryService loginHistoryService)
{
_loginHistoryService = loginHistoryService;
}
/// <summary>
/// Adds LoginHistory Info
/// </summary>
/// <param name="loginHistoryDTO"></param>
/// <returns></returns>
[Route("AddLoginHistory")]
[HttpPost]
public IHttpActionResult AddLoginHistory([FromBody] LoginHistoryDTO loginHistoryDTO)
{
if (loginHistoryDTO == null)
{
return BadRequest();
}
var results = _loginHistoryService.AddLoginHistory(loginHistoryDTO);
return Ok(results);
}
/// <summary>
/// Get LoginHistory Details
/// </summary>
/// <param name="loginHistoryID"></param>
/// <returns></returns>
[Route("GetLoginHistory")]
[HttpGet]
public IHttpActionResult GetLoginHistoryByID(int loginHistoryID)
{
var oLoginHistoryDTO = _loginHistoryService.GetLoginHistoryByID(loginHistoryID);
return Ok(oLoginHistoryDTO);
}
/// <summary>
/// Gets List of LoginHistory Details
/// </summary>
/// <returns></returns>
[Route("GetAllLoginHistory")]
[HttpGet]
public IHttpActionResult GetAllLoginHistory()
{
var oLoginHistoryDTO = _loginHistoryService.GetAllHistory();
return Ok(oLoginHistoryDTO.ToList());
}
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess.Interface
{
public interface IHospitalRepository
{
Hospital SaveorUpdate(Hospital obj);
IEnumerable<Hospital> GetAll();
Hospital GetHospitalByID(int HospitalID);
void DeleteHospital(int HospitalID);
Hospital GetHospitalByDoctorID(int doctorID);
}
}
<file_sep>using HmsAPI.DataAccess;
using HmsAPI.DataAccess.Interface;
using HmsAPI.Dto;
using HmsAPI.Model;
using HmsAPI.Services.Interfaces;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services
{
public class UserService: IUserService
{
private ILog log = LogManager.GetLogger(typeof(UserService));
public readonly IUserRepository _userTableRepository;
public readonly IUserRoleRepository _userRoleRepository;
public UserService(IUserRepository userTableRepository,IUserRoleRepository userRoleRepository)
{
_userTableRepository = userTableRepository;
_userRoleRepository = userRoleRepository;
}
public UserDTO Register(UserDTO obj)
{
try
{
var objUser = ConvertTOModel(obj);
var results = _userTableRepository.SaveorUpdate(objUser);
log.Info("User Added/Modified Successfully");
return ConvertTODTO(results);
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while Registering new User Ex:{0}", ex.Message);
return null;
}
}
public UserInformationDTO ValidateUser(string userName, string password)
{
try
{
var results = _userTableRepository.ValidateUser(userName, password);
if (results != null)
{
var objUserRole = _userRoleRepository.GetUserRolesByuserID(results.UserID);
var userInformation = new UserInformationDTO
{
UserID = results.UserID,
RoleID = objUserRole.RoleID,
Name = results.FirstName + " " + results.LastName
};
log.Info("User Validated Successfully");
return userInformation;
}
return null;
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while Validating the User Ex:{0}", ex.Message);
return null;
}
}
public UserDTO GetUserByID(int userID)
{
try
{
var user = _userTableRepository.GetUsersByID(userID);
return ConvertTODTO(user);
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while retreiving User Details Ex:{0}", ex.Message);
return null;
}
}
public List<UserDTO> GetAllUsers()
{
try
{
List<UserDTO> userTableDTOList = new List<UserDTO>();
IEnumerable<User> user = _userTableRepository.GetAll();
foreach (var item in user)
{
var userDTO = ConvertTODTO(item);
userTableDTOList.Add(userDTO);
}
return userTableDTOList;
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while retreiving List of all Users Ex:{0}", ex.Message);
return null;
}
}
private User ConvertTOModel(UserDTO obj)
{
var User = new User()
{
UserID = obj.UserID,
FirstName = obj.FirstName,
LastName = obj.LastName,
DOB = obj.DOB,
Gender = obj.Gender,
UserName = obj.UserName,
Password = <PASSWORD>,
EmailID = obj.EmailID,
PhoneNumber = obj.PhoneNumber
};
return User;
}
private UserDTO ConvertTODTO(User obj)
{
var UserDTO = new UserDTO()
{
UserID = obj.UserID,
FirstName = obj.FirstName,
LastName = obj.LastName,
DOB = obj.DOB,
Gender = obj.Gender,
UserName = obj.UserName,
Password = <PASSWORD>,
EmailID = obj.EmailID,
PhoneNumber = obj.PhoneNumber
};
return UserDTO;
}
}
}
<file_sep>using HmsAPI.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services.Interfaces
{
public interface IDoctorService
{
DoctorDTO AddDoctor(DoctorDTO obj);
DoctorDTO GetDoctorsByID(int doctorID);
List<DoctorDTO> GetAllDoctors();
List<DoctorDTO> GetDoctorsByHospitalID(int hospitalID);
List<DoctorDTO> GetDoctorsByspecialization(string specialist);
List<DoctorAvailabilityDTO> GetDoctorAvailability(int doctorID, DateTime date, int hospitalID);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class UserAppointmentDTO
{
public int AppointmentID { get; set; }
public int UserID { get; set; }
public int DoctorID { get; set; }
public string DoctorName { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string HospitalName { get; set; }
}
}
<file_sep>using HmsAPI.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services.Interfaces
{
public interface IDoctorCalendarService
{
DoctorCalendarDTO AddDoctorCalender(DoctorCalendarDTO obj);
DoctorCalendarDTO GetDoctorCalendarByID(int doctorCalendarID);
List<DoctorCalendarDTO> GetAllDoctorsCalendar();
}
}
<file_sep>using HmsAPI.Dto;
using HmsAPI.Dto.Request;
using HmsAPI.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace HmsAPI.Controllers
{
[RoutePrefix("api/v1/doctor")]
public class DoctorController: ApiController
{
private readonly IDoctorService _doctorService;
public DoctorController(IDoctorService doctorService)
{
_doctorService = doctorService;
}
/// <summary>
/// Adds new Doctor Information
/// </summary>
/// <param name="doctorDTO"></param>
/// <returns></returns>
[Route("AddDoctor")]
[HttpPost]
public IHttpActionResult AddDoctor([FromBody] DoctorDTO doctorDTO)
{
if (doctorDTO == null)
{
return BadRequest();
}
var results = _doctorService.AddDoctor(doctorDTO);
return Ok(results);
}
/// <summary>
/// Gets Doctor Details
/// </summary>
/// <param name="doctorID"></param>
/// <returns></returns>
[Route("GetDoctor")]
[HttpGet]
public IHttpActionResult GetDoctorsByID(int doctorID)
{
if (doctorID > 0)
{
var odoctorDTO = _doctorService.GetDoctorsByID(doctorID);
return Ok(odoctorDTO);
}
return BadRequest();
}
/// <summary>
/// Gets Doctor Details specific to Hospital
/// </summary>
/// <param name="hospitalID"></param>
/// <returns></returns>
[Route("GetDoctorByHospital")]
[HttpGet]
public IHttpActionResult GetDoctorsByHospitalID(int hospitalID)
{
if(hospitalID > 0)
{
var oDoctorDTO = _doctorService.GetDoctorsByHospitalID(hospitalID);
return Ok(oDoctorDTO);
}
return BadRequest();
}
/// <summary>
/// Gets Doctor Details by Specialization
/// </summary>
/// <param name="specialist"></param>
/// <returns></returns>
[Route("GetDoctorBySpecialist")]
[HttpGet]
public IHttpActionResult GetDoctorsByspecialization(string specialist)
{
if(!string.IsNullOrWhiteSpace(specialist))
{
var oDoctorDTO = _doctorService.GetDoctorsByspecialization(specialist);
return Ok(oDoctorDTO);
}
return BadRequest();
}
/// <summary>
/// Gets List of All Doctors Details
/// </summary>
/// <returns></returns>
[Route("GetAllDoctors")]
[HttpGet]
public IHttpActionResult GetAllDoctors()
{
var doctors = _doctorService.GetAllDoctors();
return Ok(doctors);
}
/// <summary>
/// Gets the DoctorAvailability Information
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
[Route("Availability")]
[HttpPost]
public IHttpActionResult GetDoctorAvailability([FromBody] DoctorParameters parameters)
{
if( (parameters.DoctorID > 0) && (parameters.Docdate== null) && (parameters.HospitalId > 0))
{
var DoctorAvailabilityDTO = _doctorService.GetDoctorAvailability(parameters.DoctorID, parameters.Docdate, parameters.HospitalId);
return Ok(DoctorAvailabilityDTO);
}
return BadRequest();
}
}
}
<file_sep>using HmsAPI.DataAccess.Interface;
using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess.Repository
{
public class ConsultationFeeRepository : BaseRepository<ConsulatationFee>, IConsulatationFeeRepository
{
public void DeleteConsultationFee(int consulatationFeeID)
{
var objAppointment = GetFeeByID(consulatationFeeID);
Delete(objAppointment);
}
public ConsulatationFee GetFeeByID(int consulatationFeeID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objConsultationFee = session.Query<ConsulatationFee>().Where(x => x.ConsulatationFeeID == consulatationFeeID).FirstOrDefault();
return objConsultationFee;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class ConsulatationFee
{
public virtual int ConsulatationFeeID { get; set; }
public virtual int DoctorID { get; set; }
public virtual int HospitalID { get; set; }
public virtual float FeeAmount { get; set; }
public virtual float DoctorAmount { get; set; }
public virtual DateTime StartDate { get; set; }
public virtual DateTime EndDate { get; set; }
public override bool Equals(object obj)
{
return obj is ConsulatationFee fee &&
ConsulatationFeeID == fee.ConsulatationFeeID &&
DoctorID == fee.DoctorID &&
HospitalID == fee.HospitalID &&
FeeAmount == fee.FeeAmount &&
DoctorAmount == fee.DoctorAmount &&
StartDate == fee.StartDate &&
EndDate == fee.EndDate;
}
public override int GetHashCode()
{
int hashCode = -1998789331;
hashCode = hashCode * -1521134295 + ConsulatationFeeID.GetHashCode();
hashCode = hashCode * -1521134295 + DoctorID.GetHashCode();
hashCode = hashCode * -1521134295 + HospitalID.GetHashCode();
hashCode = hashCode * -1521134295 + FeeAmount.GetHashCode();
hashCode = hashCode * -1521134295 + DoctorAmount.GetHashCode();
hashCode = hashCode * -1521134295 + StartDate.GetHashCode();
hashCode = hashCode * -1521134295 + EndDate.GetHashCode();
return hashCode;
}
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public class DoctorCalendarRepository : BaseRepository<DoctorCalendar>, IDoctorCalendarRepository
{
public void DeleteDoctorCalendar(int DoctorCalendarID)
{
var objDoctorCalendar = GetDoctorCalendarByID(DoctorCalendarID);
Delete(objDoctorCalendar);
}
public DoctorCalendar GetDoctorCalendarByID(int doctorCalendarID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objDoctorCalendar = session.Query<DoctorCalendar>().Where(x => x.DoctorCalendarID == doctorCalendarID).FirstOrDefault();
return objDoctorCalendar;
}
}
}
public List<DoctorCalendar> GetDoctorCalendar(int doctorID, DateTime date, int hospitalID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var results = session.Query<DoctorCalendar>().Where(x => x.DoctorID == doctorID && x.Date == date && x.HospitalID == hospitalID).ToList();
return results;
}
}
}
}
}
<file_sep>using HmsAPI.DataAccess;
using HmsAPI.Dto;
using HmsAPI.Model;
using HmsAPI.Services.Interfaces;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services
{
public class AppointmentService: IAppointmentService
{
private ILog log = LogManager.GetLogger(typeof(AppointmentService));
public readonly IAppointmentRepository _appointmentRepository;
public readonly IUserRepository _userTableRepository;
public AppointmentService(IAppointmentRepository appointmentRepository, IUserRepository userTableRepository)
{
_appointmentRepository = appointmentRepository;
_userTableRepository = userTableRepository;
}
public AppointmentDTO AddAppointment(AppointmentDTO obj)
{
try
{
var objAppointment = ConvertTOModel(obj);
var appointment = _appointmentRepository.SaveorUpdate(objAppointment);
log.Info("Appointment Info saved Successfully");
return ConvertTODTO(appointment);
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while Adding new Appointment Info Ex:{0}", ex.Message);
return null;
}
}
public AppointmentDTO GetAppointmentByID(int appointmentID)
{
try
{
var appointment = _appointmentRepository.GetAppointmentByID(appointmentID);
return ConvertTODTO(appointment);
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retrieving Appointment Info Ex:{0}", ex.Message);
return null;
}
}
public List<AppointmentDTO> GetAllAppointments()
{
try
{
List<AppointmentDTO> appointmentDTOList = new List<AppointmentDTO>();
IEnumerable<Appointment> appointmentDTOS = _appointmentRepository.GetAll();
foreach (var appointment in appointmentDTOS)
{
var appointmentDTO = ConvertTODTO(appointment);
appointmentDTOList.Add(appointmentDTO);
}
return appointmentDTOList;
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while retrieving List of all Appointment Info Ex:{0}", ex.Message);
return null;
}
}
public List<DoctorAppointmentDTO> GetDoctorAppointmentByDate(int doctorID, DateTime date)
{
try
{
var doctorAppointmentList = new List<DoctorAppointmentDTO>();
List<DoctorAppointment> appointments = _appointmentRepository.GetAppointments(doctorID, date);
foreach (var app in appointments)
{
var DoctorAppointmentDTO = new DoctorAppointmentDTO
{
AppointmentID = app.AppointmentID,
DoctorID = app.DoctorID,
UserID = app.UserID,
StartTime = app.StartTime,
EndTime = app.EndTime,
UserName = app.UserName,
HospitalName = app.HospitalName,
Date = app.Date
};
doctorAppointmentList.Add(DoctorAppointmentDTO);
}
return doctorAppointmentList;
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while retrieving Appointment Info by DoctorId and Date Ex:{0}", ex.Message);
return null;
}
}
public Appointment ConvertTOModel(AppointmentDTO obj)
{
var appointment = new Appointment()
{
AppointmentID = obj.AppointmentID,
DoctorCalendarID = obj.DoctorCalendarID,
DoctorID = obj.DoctorID,
AppDate = obj.AppDate,
UserID = obj.UserID,
StartTime= obj.StartTime,
EndTime = obj.EndTime
};
return appointment;
}
public AppointmentDTO ConvertTODTO(Appointment obj)
{
var appointmentDTO = new AppointmentDTO()
{
AppointmentID = obj.AppointmentID,
DoctorCalendarID = obj.DoctorCalendarID,
DoctorID = obj.DoctorID,
AppDate=obj.AppDate,
UserID = obj.UserID,
StartTime = obj.StartTime,
EndTime = obj.EndTime
};
return appointmentDTO;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class HospitalDTO
{
public int HospitalID { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string EmailID { get; set; }
public string Address { get; set; }
}
}
<file_sep>using HmsAPI.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services.Interfaces
{
public interface ILoginHistoryService
{
LoginHistoryDTO AddLoginHistory(LoginHistoryDTO obj);
LoginHistoryDTO GetLoginHistoryByID(int loginHistoryID);
List<LoginHistoryDTO> GetAllHistory();
}
}
<file_sep>using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model.Mapping
{
public class PatientMedicineMapping:ClassMap<PatientMedicine>
{
public PatientMedicineMapping()
{
Table("PatientMedicine");
Id(x => x.PatientMedicineID, "PatientMedicineID");
Map(x => x.UserID, "UserID").CustomType<int>();
Map(x => x.MedicineDescription, "MedicineDescription");
Map(x => x.AppointmentID, "AppointmentID").CustomType<int>();
}
}
}
<file_sep>using HmsAPI.DataAccess;
using HmsAPI.Dto;
using HmsAPI.Model;
using HmsAPI.Services.Interfaces;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services
{
public class DoctorCalendarService: IDoctorCalendarService
{
private ILog log = LogManager.GetLogger(typeof(DoctorCalendarService));
public readonly IDoctorCalendarRepository _doctorCalendarRepository;
public DoctorCalendarService(IDoctorCalendarRepository doctorCalendarRepository)
{
_doctorCalendarRepository = doctorCalendarRepository;
}
public DoctorCalendarDTO AddDoctorCalender(DoctorCalendarDTO obj)
{
try
{
var objDoctorCalendar = ConvertTOModel(obj);
var results = _doctorCalendarRepository.SaveorUpdate(objDoctorCalendar);
return ConvertTODTO(results);
}
catch(Exception ex)
{
log.ErrorFormat("Exception occured while Adding new DoctorCalendar Info Ex:{0}", ex.Message);
return null;
}
}
public DoctorCalendarDTO GetDoctorCalendarByID(int doctorCalendarID)
{
try
{
var doctorCalendar = _doctorCalendarRepository.GetDoctorCalendarByID(doctorCalendarID);
return ConvertTODTO(doctorCalendar);
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retrieving DoctorCalendar Info Ex:{0}", ex.Message);
return null;
}
}
public List<DoctorCalendarDTO> GetAllDoctorsCalendar()
{
try
{
List<DoctorCalendarDTO> doctorCalendarDTOList = new List<DoctorCalendarDTO>();
IEnumerable<DoctorCalendar> doctorCalendar = _doctorCalendarRepository.GetAll();
foreach (var calendar in doctorCalendar)
{
var doctorCalendarDTO = ConvertTODTO(calendar);
doctorCalendarDTOList.Add(doctorCalendarDTO);
}
return doctorCalendarDTOList;
}
catch (Exception ex)
{
log.ErrorFormat("Exception occured while retrieving List of DoctorCalendar Info Ex:{0}", ex.Message);
return null;
}
}
public DoctorCalendar ConvertTOModel(DoctorCalendarDTO obj)
{
var doctorCalendar = new DoctorCalendar()
{
DoctorCalendarID = obj.DoctorCalendarID,
DoctorID = obj.DoctorID,
Date = obj.Date,
StartTime = obj.StartTime,
EndTime = obj.EndTime
};
return doctorCalendar;
}
public DoctorCalendarDTO ConvertTODTO(DoctorCalendar obj)
{
var doctorCalendarDTO = new DoctorCalendarDTO()
{
DoctorCalendarID = obj.DoctorCalendarID,
DoctorID = obj.DoctorID,
Date = obj.Date,
StartTime = obj.StartTime,
EndTime = obj.EndTime
};
return doctorCalendarDTO;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Dto
{
public class AppointmentDTO
{
public int AppointmentID { get; set; }
public int UserID { get; set; }
public int DoctorID { get; set; }
public DateTime AppDate { get; set; }
public int DoctorCalendarID { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public class DoctorRepository : BaseRepository<Doctor>, IDoctorRepository
{
public void DeleteDoctor(int DoctorID)
{
var objDoctor = GetDoctorByID(DoctorID);
Delete(objDoctor);
}
public Doctor GetDoctorByID(int doctorID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objDoctor = session.Query<Doctor>().Where(x => x.DoctorID == doctorID).FirstOrDefault();
return objDoctor;
}
}
}
public List<Doctor> GetDoctorsByHospitalID(int hospitalID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var query = "select d.* from doctor d join DoctorCalendar dc on dc.DoctorID = d.DoctorID inner join Hospital h on h.HospitalID = dc.HospitalID where h.HospitalID =" + hospitalID;
var results = session.CreateSQLQuery(query).AddEntity(typeof(Doctor)).List<Doctor>().ToList();
return results;
}
}
}
public List<Doctor> GetDoctorsBySpecialization(string specialist)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var query = session.Query<Doctor>().Where(x => x.Specialist.Contains(specialist)).ToList();
return query;
}
}
}
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public interface IUserRepository
{
User SaveorUpdate(User obj);
IEnumerable<User> GetAll();
User GetUsersByID(int UserID);
void DeleteUser(int USerID);
User ValidateUser(string userName, string password);
User GetUsersByDoctorID(int doctorID);
}
}
<file_sep>using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model.Mapping
{
public class UserTableMapping: ClassMap<User>
{
public UserTableMapping()
{
Table("UserTable");
Id(x => x.UserID, "UserID");
Map(x => x.FirstName, "FirstName");
Map(x => x.LastName, "LastName");
Map(x => x.DOB, "DOB");
Map(x => x.Gender, "Gender");
Map(x => x.UserName, "UserName");
Map(x => x.EmailID, "EmailID");
Map(x => x.Password, "<PASSWORD>");
Map(x => x.PhoneNumber, "PhoneNumber");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Model
{
public class Hospital
{
public virtual int HospitalID { get; set; }
public virtual string Name { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual string EmailID { get; set; }
public virtual string Address { get; set; }
public override bool Equals(object obj)
{
return obj is Hospital hospital &&
HospitalID == hospital.HospitalID &&
Name == hospital.Name &&
PhoneNumber == hospital.PhoneNumber &&
EmailID == hospital.EmailID &&
Address == hospital.Address;
}
public override int GetHashCode()
{
int hashCode = 197011055;
hashCode = hashCode * -1521134295 + HospitalID.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(PhoneNumber);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(EmailID);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Address);
return hashCode;
}
}
}
<file_sep>using HmsAPI.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services.Interfaces
{
public interface IUserAppointmentService
{
List<UserAppointmentDTO> GetUserAppointments(int userID);
}
}
<file_sep>using HmsAPI.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.Services.Interfaces
{
public interface IUserService
{
UserDTO Register(UserDTO obj);
UserInformationDTO ValidateUser(string userName, string password);
UserDTO GetUserByID(int userID);
List<UserDTO> GetAllUsers();
}
}
<file_sep>using HmsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HmsAPI.DataAccess
{
public class AppointmentRepository : BaseRepository<Appointment>, IAppointmentRepository
{
public void DeleteAppointment(int appointmentID)
{
var objAppointment = GetAppointmentByID(appointmentID);
Delete(objAppointment);
}
public Appointment GetAppointmentByID(int appointmentID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objAppointment = session.Query<Appointment>().Where(x => x.AppointmentID == appointmentID).FirstOrDefault();
return objAppointment;
}
}
}
public List<Appointment> GetAppointmentByUserID(int userID)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objAppointment = session.Query<Appointment>().Where(x => x.UserID == userID).ToList();
return objAppointment;
}
}
}
public List<DoctorAppointment> GetAppointments(int doctorID, DateTime date)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var query = "select d.DoctorID,a.UserID,a.AppointmentID,(u.FirstName + ' ' + u.LastName ) as UserName, a.StartTime,a.EndTime,h.Name,dc.Date from Doctor d" +
"join Appointment a on d.DoctorID = a.DoctorID" +
"join DoctorCalendar dc on dc.DoctorID = a.DoctorID" +
"join Hospital h on h.HospitalID = dc.HospitalID" +
"join UserTable u on u.UserID = a.UserID" +
"where AppointmnetDate =" + date + "and d.doctorId =" + doctorID;
var results = session.CreateSQLQuery(query).AddEntity(typeof(DoctorAppointment)).List<DoctorAppointment>().ToList();
return results;
}
}
}
public List<Appointment> GetAppointmentsByDoctorID(int doctorID, DateTime date)
{
using (SessionWrapper sessionWrapper = new SessionWrapper())
{
using (var session = sessionWrapper.Session)
{
var objAppointment = session.Query<Appointment>().Where(x => x.DoctorID == doctorID && x.AppDate == date).ToList();
return objAppointment;
}
}
}
}
}
| b4dbe75d1231a8f7cf44c89d864c5ba00177fc8d | [
"C#"
] | 87 | C# | samuluru28/HmsAPI | 5b76ccb955553b01ddc1078691a4909122b1de72 | 7d5d4dc843f1381cbdcb3326436b600626376d9b |
refs/heads/master | <file_sep>import React from 'react';
import createSchema from 'part:@sanity/base/schema-creator';
// Then import schema types from any plugins that might expose them
import schemaTypes from 'all:part:@sanity/base/schema-type';
import { FiCalendar, FiMapPin, FiCrosshair, FiWatch, FiUser, FiMap } from 'react-icons/fi';
import googleeventattachment from './googleeventattachment';
// Then we give our schema to the builder and provide the result to Sanity
export default createSchema({
// We name our schema
name: 'default',
// Then proceed to concatenate our document type
// to the ones provided by any plugins that are installed
types: schemaTypes.concat([
googleeventattachment,
{
title: 'Municipality',
name: 'municipality',
type: 'document',
icon: FiMap,
fields: [
{
title: 'Name',
name: 'name',
type: 'string',
validation: (Rule) => Rule.required(),
},
{
title: 'URL',
name: 'slug',
type: 'slug',
options: {
source: 'name',
slugify: (input) =>
input
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/ä/g, 'ae')
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/ß/g, 'ss')
.slice(0, 200),
},
validation: (Rule) => Rule.required(),
},
{
title: 'Description',
name: 'description',
type: 'string',
},
{
title: 'Official Twitter User',
name: 'twitter_user',
type: 'string',
},
{
title: 'Google Place ID',
name: 'place_id',
type: 'string',
},
{
title: 'Geolocation',
name: 'geolocation',
type: 'geopoint',
},
{
title: 'Zip Code',
name: 'zip',
type: 'string',
},
{
title: 'Population',
name: 'population',
type: 'number',
},
],
preview: {
select: {
title: 'name',
description: 'description',
},
},
},
{
title: 'Village',
name: 'community',
type: 'document',
icon: FiMapPin,
fields: [
{
title: 'Name',
name: 'name',
type: 'string',
validation: (Rule) => Rule.required(),
},
{
title: 'URL',
name: 'slug',
type: 'slug',
options: {
source: 'name',
slugify: (input) =>
input
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/ä/g, 'ae')
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/ß/g, 'ss')
.slice(0, 200),
},
validation: (Rule) => Rule.required(),
},
{
title: 'Description',
name: 'description',
type: 'string',
},
{
title: 'Google Place ID',
name: 'place_id',
type: 'string',
},
{
title: 'Geolocation',
name: 'geolocation',
type: 'geopoint',
},
{
title: 'Zip Code',
name: 'zip',
type: 'string',
},
{
title: 'Wikidata ID',
name: 'wikidata_id',
type: 'string',
},
{
title: 'Visual',
name: 'image',
type: 'image',
options: {
hotspot: true,
},
},
{
title: 'Wikimedia Commons Images',
name: 'wikimedia_commons_imagelinks',
type: 'array',
of: [{ type: 'string' }],
validation: (Rule) => Rule.unique(),
},
{
title: 'Population',
name: 'population',
type: 'number',
},
{
title: 'Geonames ADM3',
name: 'county_geoname_id',
type: 'number',
},
{
title: 'Municipality',
name: 'municipality',
type: 'reference',
weak: true,
to: [{ type: 'municipality' }],
description: 'To which municipality does that village belong to?',
},
{
title: 'Address aliases',
name: 'address_aliases',
type: 'array',
of: [{ type: 'string' }],
validation: (Rule) => Rule.unique(),
},
{
title: 'Publication status',
name: 'publication_status',
type: 'string',
options: {
list: [
{ title: 'Online', value: '0' },
{ title: 'Beta', value: '1' },
{ title: 'Hidden', value: '2' },
{ title: 'Offline', value: '3' },
],
layout: 'dropdown',
},
},
],
orderings: [
{
title: 'Village',
name: 'community',
by: [{ field: 'name', direction: 'asc' }],
},
],
preview: {
select: {
title: 'name',
municipality: 'municipality.name',
media: 'image.asset.url',
wikimedia: 'wikimedia_commons_imagelinks.0',
description: 'description',
publication_status: 'publication_status',
wikidata_id: 'wikidata_id',
},
prepare(selection) {
const {
title,
municipality,
media,
wikimedia,
description,
publication_status,
wikidata_id = 'Q?',
} = selection;
const thumb = wikimedia ? wikimedia : media + '?h=80&w=80&fit=crop';
return {
title: title,
subtitle: `in ${municipality ? municipality : 'MISSING'} (${wikidata_id}, Public? ${publication_status})`,
media: <img src={thumb} />,
description: description,
};
},
},
},
{
title: 'Organizer',
name: 'organizer',
type: 'document',
icon: FiUser,
fields: [
{
title: 'Name',
name: 'name',
type: 'string',
validation: (Rule) => Rule.required(),
},
{
title: '<NAME>',
name: 'longname',
type: 'string',
},
{
title: 'URL',
name: 'slug',
type: 'slug',
options: {
source: 'name',
slugify: (input) =>
input
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/ä/g, 'ae')
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/ß/g, 'ss')
.slice(0, 200),
},
validation: (Rule) => Rule.required(),
},
{
title: 'Description',
name: 'description',
type: 'string',
},
{
title: 'Google Place ID',
name: 'place_id',
type: 'string',
},
{
title: 'Wikidata ID',
name: 'wikidata_id',
type: 'string',
},
{
title: 'Website',
name: 'website',
type: 'url',
},
],
preview: {
select: {
title: 'name',
subtitle: 'longname',
},
},
},
{
title: 'Calendar',
name: 'calendar',
type: 'document',
icon: FiCalendar,
fields: [
{
title: 'Name',
name: 'name',
type: 'string',
},
{
title: 'Description',
name: 'description',
type: 'string',
},
{
title: 'Google Calendar ID',
name: 'calendar_id',
type: 'string',
validation: (Rule) =>
Rule.custom((calendar_id) => {
if (typeof calendar_id === 'undefined') {
return true;
}
return calendar_id === calendar_id.trim() ? true : 'Avoid white spaces.';
}).warning(),
},
{
title: 'Organizer',
name: 'organizer',
type: 'reference',
weak: true,
to: [{ type: 'organizer' }],
description: 'Which organizer is responsible?',
},
{
title: 'Publication Scope',
name: 'scope',
type: 'string',
options: {
list: [
{ title: 'Village', value: '0' },
{ title: 'Municipality', value: '1' },
{ title: 'Surrounding', value: '2' },
{ title: 'Region', value: '3' },
],
layout: 'radio',
direction: 'horizontal',
},
validation: (Rule) => Rule.required(),
},
{
title: 'Publication status',
name: 'publication_status',
type: 'string',
options: {
list: [
{ title: 'Online', value: '1' },
{ title: 'Offline', value: '0' },
],
layout: 'radio',
direction: 'horizontal',
},
validation: (Rule) => Rule.required(),
},
{
title: 'Display mode',
name: 'display_mode',
type: 'string',
options: {
list: [
{ title: 'Micro (no time)', value: '0' },
{ title: 'Mini (recurring)', value: '1' },
{
title: 'One Line (all events per day in one line)',
value: '4',
},
{ title: 'Default', value: '2' },
{ title: 'Extended (special events)', value: '3' },
{ title: 'One Line (combine times of multiple events)', value: '5' },
{ title: 'Commercial Ad', value: '6' },
],
layout: 'radio',
direction: 'horizontal',
},
validation: (Rule) => Rule.required(),
},
{
title: 'Time display mode',
name: 'time_display_mode',
type: 'string',
options: {
list: [
{ title: 'No time', value: '0' },
{ title: 'Start time only', value: '1' },
{
title: 'Start and end time',
value: '2',
},
],
layout: 'radio',
direction: 'horizontal',
},
validation: (Rule) => Rule.required(),
},
{
title: 'Default Village',
name: 'community',
type: 'reference',
weak: true,
to: [{ type: 'community' }],
description: 'To which village events should belong to, when address cannot be geocoded?',
},
],
initialValue: {
scope: '0',
time_display_mode: '2',
},
preview: {
select: {
title: 'name',
organizer: 'organizer.name',
},
prepare(selection) {
const { title, organizer } = selection;
return {
title: title,
subtitle: `${organizer ? organizer : 'unknown'}`,
};
},
},
},
{
title: 'Event',
name: 'event',
type: 'document',
icon: FiWatch,
fields: [
{
title: 'Summary',
name: 'name',
type: 'string',
validation: (Rule) => Rule.required(),
},
{
title: 'Description',
name: 'description',
type: 'string',
},
{
title: 'Start',
name: 'start',
type: 'datetime',
options: {
dateFormat: 'DD.MM.YYYY',
timeFormat: 'HH:mm',
timeStep: 15,
calendarTodayLabel: 'Today',
},
validation: (Rule) => Rule.required(),
},
{
title: 'Allday?',
name: 'allday',
type: 'boolean',
},
{
title: 'End',
name: 'end',
type: 'datetime',
options: {
dateFormat: 'DD.MM.YYYY',
timeFormat: 'HH:mm',
timeStep: 15,
calendarTodayLabel: 'Today',
},
},
{
title: 'Cancelled?',
name: 'cancelled',
type: 'boolean',
},
{
title: 'Location',
name: 'location',
type: 'string',
},
{
title: 'Geolocation',
name: 'geolocation',
type: 'geopoint',
},
{
title: 'Place',
name: 'placeName',
type: 'string',
},
{
title: 'Place (local name)',
name: 'placeLocalName',
type: 'string',
},
{
title: 'Google Event Attachment',
name: 'googleeventattachment',
type: 'array',
of: [{ type: 'googleeventattachment' }],
},
{
title: 'Village',
name: 'community',
type: 'reference',
weak: true,
to: [{ type: 'community' }],
description: 'To which village does this event belong to?',
},
{
title: 'Calendar',
name: 'calendar',
type: 'reference',
weak: true,
to: [{ type: 'calendar' }],
description: 'To which calendar does the event belong to?',
},
{
title: 'Categories',
name: 'categories',
type: 'array',
of: [{ type: 'string' }],
validation: (Rule) => Rule.unique(),
},
{
title: 'Google Event ID',
name: 'event_id',
type: 'string',
},
],
preview: {
select: {
title: 'name',
start: 'start',
community: 'community.name',
},
prepare(selection) {
const { title, start, community } = selection;
return {
title: title,
subtitle: `in ${community ? community : 'MISSING'} at ${start}`,
};
},
},
},
]),
});
| 08103926ba42a54ce957147a7c0f61a560ce3721 | [
"JavaScript"
] | 1 | JavaScript | schafe-vorm-fenster/platform | 5013258f15dd5d3fd92f8716439ed9c7ed1f9aa3 | 1962646f900c22e67006a804734b5a558345d076 |
refs/heads/master | <file_sep>library(twitteR)
library(urltools)
library(stringr)
library(httr)
library(XML)
library(stringr)
library(RCurl)
library(rJava)
api_key <- "iXMW1rNmQcPSFjSrrPs16eDZB"
api_secret <- "<KEY>"
access_token <- "<KEY>"
access_token_secret <- "<KEY>"
setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)
genre<-c("Acoustic","Alternative & Punk","Blues","Classical","Country & Folk","Dance & Electronic","Easy Listening", "Gospel & Religious", "Hip Hop & Rap", "Holiday", "Jazz","Latin","Metal","Moods","Other","Pop","R&B","Rock","Soundtrack","World")
User<-"RaedAyari"
tweets <- userTimeline(User, n=100)
length(tweets)
tweetdf <- twListToDF(tweets)
#liste des tweets
t<-tweetdf['text']
#retweeted?
rt<-tweetdf['retweeted']
#the number of retweets
retweetnumber<-tweetdf['retweetCount']
#checking if it is a link
j<-0
for(i in 1:nrow(t))
{
j<-j+1
posts[j]<-as.character(t[i,1])
exist[j]<-url.exists(t[i,1])
}
#turning posts into dataframes
Posts<-data.frame(posts)
isLink<-data.frame(exist)
SongCategory<-NULL
#getting the name of the song, the artist and the category
for(i in 1:nrow(t)){
information<-NULL
information
if(exist[i]==TRUE){
r<-GET(posts[i])
f<-content(r, "text")
parsedHtml=htmlParse(f,asText = TRUE)
title.xml <- xpathSApply(parsedHtml,"//span[@id='eow-title']",xmlValue)
information<-unlist(strsplit(title.xml[1],"-"))
information[1]
information[2]
song<-unlist(strsplit(information[2],"[-(.[)]"))
song[1]
Artist[i]<-str_extract(information[1], "[A-Z].*")
songName[i]<-song[1]
songName[i]
genre.xml<-xpathSApply(parsedHtml,"//meta[@property='og:video:tag']",xmlGetAttr, "content")
if (length(genre.xml)>0){
for(j in 1:length(genre.xml)){
if((genre.xml[j] %in% genre)==TRUE){
SongCategory[i]<-genre.xml[j]
}
}
}
}
}
SongCategories<-data.frame(SongCategory)
#filling the rows by the user name
user<-NULL
for(i in 1:nrow(t)){
user[i]<-User
}
#saving data into dataframes
users<-data.frame(user)
songNames<-data.frame(songName)
songNames
Artists<-data.frame(Artist)
Artists
#defining the columns names
col.names = c("user", "posts","exist","songName","Artist", "Category")
#binding all the data together
FinalData<-data.frame(users,Posts,isLink,songNames,Artists,SongCategories)
FinalData
#saving data into csv file
write.csv(FinalData, file = "TwitterData.csv")
| 0b4df39b7836f31c034d45e324bed91e09c8041b | [
"R"
] | 1 | R | chaima-ennar/Twitter-youtube-web-scrapping | a8455879e744cf88b2d0f2f32495ab490751a316 | 462c8f01651ccbfebd9b15c71ef3908baefa704a |
refs/heads/main | <file_sep>const list = [
{
value: 'Пункт 1.',
children: null,
},
{
value: 'Пункт 2.',
children: [
{
value: 'Подпункт 2.1.',
children: null,
},
{
value: 'Подпункт 2.2.',
children: [
{
value: 'Подпункт 2.2.1.',
children: null,
},
{
value: 'Подпункт 2.2.2.',
children: null,
}
],
},
{
value: 'Подпункт 2.3.',
children: null,
}
]
},
{
value: 'Пункт 3.',
children: null,
}
];
function createList(title, list) {
const body = document.querySelector('body');
const newTitle = document.createElement('h2');
const newList = createUl(list);
newTitle.innerHTML = title;
body.appendChild(newTitle);
body.appendChild(newList);
}
function createUl(ul) {
const newUl = document.createElement('ul');
ul.forEach(li => {
const newLi = document.createElement('li');
if (li.children) {
newLi.innerHTML = li.value;
newLi.appendChild(createUl(li.children));
} else {
newLi.innerHTML = li.value;
}
newUl.appendChild(newLi);
})
return newUl;
}
createList("List", list);
<file_sep>function getDay(date) {
let day = date.getDay();
if (day === 0) day = 7;
return day - 1;
}
function createCalendar(elem, year, month) {
let element = document.getElementById(elem);
let table = '<table><tr><th>пн</th><th>вт</th><th>ср</th><th>чт</th><th>пт</th><th>сб</th><th>вс</th></tr><tr>';
let newDate = new Date(year, month-1);
for (let i = 0; i < getDay(newDate); i++) {
table += '<td></td>';
}
while (newDate.getMonth() === month-1) {
table += '<td>' + newDate.getDate() + '</td>';
if (getDay(newDate) % 7 === 6) {
table += '</tr><tr>';
}
newDate.setDate(newDate.getDate() + 1);
}
if (getDay(newDate) !== 0) {
for (let i = getDay(newDate); i < 7; i++) {
table += '<td></td>';
}
}
table += '</tr></table>';
element.innerHTML += table;
}
console.log(createCalendar('cal',2020,11));
console.log(createCalendar('cal',2020,10));
console.log(createCalendar('cal',2020,9));
<file_sep>class Node{
constructor(value){
this.value = value;
this.next = null;
}
}
class List{
constructor(value) {
this.root = new Node(value);
this.length = 0;
}
addNode(value,index = this.length){
let position = 0;
let current = this.root;
if (index<=this.length) {
while (current.next !== null && position !== index) {
current = current.next;
position++;
}
let element = new Node(value);
this.length++;
element.next = current.next;
current.next = element;
return true;
}else return false;
}
removeNode(index=this.length) {
let current = this.root,
position = 0,
beforeNodeToDelete = null,
nodeToDelete = null;
if (index > this.length) {
return false;
}
if (index === 0) {
this.root = current.next;
current = null;
this.length--;
return true;
}
while (position !== index) {
beforeNodeToDelete = current;
current = current.next;
position++;
}
beforeNodeToDelete.next = current.next;
nodeToDelete = null;
--this.length;
return true;
}
print(){
const result = [];
let current = this.root;
while(current){
result.push(current.value);
current = current.next;
}return result;
}
}
let list = new List(70);
console.log(list.addNode(2),
list.addNode(3),
list.addNode(1),
list.addNode(4,1),
list.addNode(6,7),
list.removeNode(1),
list.removeNode(5),
list.removeNode(),
list.print());
<file_sep>function formatDate(date) {
const newDate = new Date(date);
let dd = newDate.getDate();
if (dd < 10) dd = `0${dd}`;
let mm = newDate.getMonth() + 1;
if (mm < 10) mm = `0${mm}`;
const yy = newDate.getFullYear();
return `${dd}/${mm}/${yy}`;
}
function formatTime(date) {
const newDate = new Date(date);
let hours = newDate.getHours();
if (hours < 10) hours = `0${hours}`;
let min = newDate.getMinutes();
if (min < 10) min = `0${min}`;
return `${hours}:${min}`;
}
class Message {
constructor(msg = { }) {
this._id = msg.id || `${+new Date()}`;
this.text = msg.text;
this._createdAt = msg.createdAt ? new Date(msg.createdAt) : new Date();
this._author = msg.author;
this.isPersonal = msg.isPersonal ?? !!msg.to;
this.to = msg.to;
}
get id() {
return this._id;
}
get author() {
return this._author;
}
get createdAt() {
return this._createdAt;
}
}
class MessageList {
static _filterObj = {
author: (message, author) => author && message.author.toLowerCase().includes(author.toLowerCase()),
text: (message, text) => text && message.text.toLowerCase().includes(text.toLowerCase()),
dateTo: (message, dateTo) => dateTo && message.createdAt < new Date(dateTo),
dateFrom: (message, dateFrom) => dateFrom && message.createdAt > new Date(dateFrom),
to: (message, to) => to,
}
static _validateObj = {
text: (message) => message.text && message.text.length <= 200 && message.text.length > 0,
to: (message) => message.to && message.text.length > 0,
}
static _validateEditObj = {
text: (message) => message.text && message.text.length <= 200,
to: (message) => message.to,
}
static validate(msg = {}) {
return Object.keys(this._validateObj).some((key) => this._validateObj[key](msg));
}
static validEditMessage(msg = {}) {
return Object.keys(this._validateEditObj).some((key) => this._validateEditObj[key](msg));
}
constructor(msgs = []) {
// this.restore();
this._arrMessages = msgs;
this._notValidMessages = [];
}
set user(name) {
this._user = name;
}
get user() {
return this._user;
}
getPage(skip = 0, top = 10, filterConfig = {}) {
let resultArr = this._arrMessages.slice();
Object.keys(filterConfig).forEach((key) => {
resultArr = resultArr.filter((message) => MessageList._filterObj[key](message, filterConfig[key]));
});
if (filterConfig.to) resultArr = resultArr.filter((message) => (message.author === this.user && message.to === filterConfig.to) || (message.author === filterConfig.to && message.to === this.user));
else resultArr = resultArr.filter((message) => message.isPersonal === false);
resultArr.sort((d1, d2) => d1.createdAt - d2.createdAt);
resultArr.splice(0, skip);
if (resultArr.length > top) {
resultArr.splice(top);
}
return resultArr;
}
add(msg = {}) {
if (this.user) {
const message = new Message(msg);
if (MessageList.validate(msg)) {
this._arrMessages.push(message);
this.save();
return true;
} return false;
} return false;
}
get(id = '') {
return this._arrMessages.find((message) => message.id === id);
// return this._arrMessages.find((message) => message.id === id);
}
edit(idNew, msg = { text: '', to: null }) {
if (this.user) {
const foundMessage = this.get(idNew);
if (MessageList.validEditMessage(msg) && foundMessage.author === this.user) {
if (msg.text) {
foundMessage.text = msg.text;
}
if (msg.to) {
foundMessage.to = msg.to;
}
this.save();
return true;
} return false;
} return false;
}
remove(idNew) {
if (this.user) {
const index = this._arrMessages.findIndex((message) => message.id === idNew && message.author === this.user);
if (index !== -1) {
this._arrMessages.splice(index, 1);
this.save();
return true;
} return false;
} return false;
}
addAll(msgs = []) {
msgs.forEach((message) => {
const mess = new Message(message);
MessageList.validate(mess) ? this._arrMessages.push(mess) : this._notValidMessages.push(mess);
});
return this._arrMessages;
}
clear() {
this._arrMessages.splice(0);
}
save() {
const newArrMessages = chatController.messageList._arrMessages;
localStorage.setItem('messages', JSON.stringify(newArrMessages));
}
//
// restore() {
// let arr = JSON.parse(localStorage.getItem('messages'));
// if (localStorage.getItem('messages')) {
// arr = arr.map((message) => new Message(message));
// this._arrMessages = [...arr];
// if (this._arrMessages.length > 10) showMore.style.display = 'flex';
// }
// }
}
class UserList {
constructor(users = [], activeUsers = []) {
this._users = users;
// this.restore();
this._activeUsers = activeUsers;
}
get users() {
return this._users;
}
get activeUsers() {
return this._activeUsers;
}
addUser(user) {
chatController.userList.users.push(user);
chatController.messageList.save();
chatController.userList.save();
}
save() {
const newArrUsers = chatController.userList.users;
localStorage.setItem('users', JSON.stringify(newArrUsers));
}
// restore() {
// if (localStorage.getItem('users')) this._users = JSON.parse(localStorage.getItem('users'));
// }
}
class HeaderView {
constructor(containerId = '') {
this.container = document.getElementById(containerId);
}
display(currentUser) {
this.container.textContent = currentUser;
}
}
class MessagesView {
constructor(containerId = '') {
this.container = document.getElementById(containerId);
}
display(arr) {
this.container.innerHTML = arr.map((message) => (message.author === userNameHeader
? `<div class='my-message-container'>
<div class='my-message-author'>${message.author}:</div>
<div class='my-message-body' id="my-message">
<div class='my-message-area' id="my-message-area">
<div class='my-triangle'></div>
<div class='my-message-text'>
<p><span class="textMessage">${message.text}</span>
</p>
</div>
</div>
<div class="message-time-date">
<div class="message-time">${formatTime(message.createdAt)}</div>
<div class="message-date">${formatDate(message.createdAt)}</div>
</div>
<div class="buttons-delete-edit" id="buttons-delete-edit">
<button type="button" class="button-delete">Delete</button>
<button type="button" class="button-edit">Edit</button>
</div>
</div>
</div>`
: `<div class='message-container'>
<div class='message-author'>${message.author}:</div>
<div class='message-body'>
<div class='message-area'>
<div class='triangle'></div>
<div class='message-text'>
<p><span>${message.text}</span>
</p>
</div>
</div>
<div class="message-time-date">
<div class="message-time">${formatTime(message.createdAt)}</div>
<div class="message-date">${formatDate(message.createdAt)}</div>
</div>
</div>
</div>`)).join('');
}
}
class UsersView {
constructor(containerId = '') {
this.container = document.getElementById(containerId);
}
display(arr) {
this.container.innerHTML = arr.map((user) => (user.isActive
? `<div class='active-user'>
<button type="button" class=${user === userNameHeader ? 'my-button-private-messages' : 'button-private-messages'} id="button-private-messages">
<span class="iconify" data-icon="eva:paper-plane-fill" data-inline="false"/>
</button>
<span id="name-private-user">${user.name}</span>
</div>`
: `<div class='user'>
<button type="button" class='button-private-messages' id="button-private-messages">
<span class="iconify" data-icon="eva:paper-plane-fill" data-inline="false"/>
</button>
<span id="name-private-user">${user.name}</span>
</div>`)).join('');
}
}
class ChatApiService {
constructor(url) {
this._url = url;
}
async _fetchRequest(url, options = {}) {
const requestOptions = {
method: options.method,
headers: options.headers,
body: options.body,
redirect: 'follow',
};
try {
return await fetch(`${this._url}/${url}`, requestOptions);
} catch (e) {
errorPage.style.display = 'flex';
logo.style.display = 'none';
buttonLogOut.style.display = 'none';
chatController.setCurrentUser('');
mainPage.style.display = 'none';
errorButton.addEventListener('click', errorToHome);
}
}
async _fetchLogReg(url, form) {
const requestOptions = {
method: 'POST',
body: form,
redirect: 'follow',
};
const response = await fetch(`${this._url}/auth/${url}`, requestOptions);
if (!response.ok) {
throw new Error('error');
} else return response.text();
}
async register(name, pass) {
const formdata = new FormData();
formdata.append('name', name);
formdata.append('pass', pass);
return this._fetchLogReg('register', formdata);
}
async login(name, pass) {
const formdata = new FormData();
formdata.append('name', name);
formdata.append('pass', pass);
return this._fetchLogReg('login', formdata);
}
async logout() {
const myHeaders = new Headers();
myHeaders.append('Authorization', ['Bearer ', chatController.token].join(''));
return this._fetchRequest('auth/logout', { method: 'POST', headers: myHeaders });
}
async getUsers() {
const myHeaders = new Headers();
myHeaders.append('Authorization', ['Bearer ', chatController.token].join(''));
const response = await this._fetchRequest('users', { method: 'GET', headers: myHeaders });
return response.text();
}
async getMessages(skip = 0, top = 10, filterConfig = {}, token) {
const myHeaders = new Headers();
myHeaders.append('Authorization', ['Bearer ', token].join(''));
const arr = [];
arr.push(`skip=${skip}&top=${top}`);
for (const el in filterConfig) {
arr.push(`&${el}=${filterConfig[el]}`);
}
const response = await this._fetchRequest(`messages?${arr.join('')}`, { method: 'GET', headers: myHeaders });
return response.text();
}
async deleteMessages(id = '') {
const myHeaders = new Headers();
myHeaders.append('Authorization', ['Bearer ', chatController.token].join(''));
return this._fetchRequest(`messages/${id}`, { method: 'DELETE', headers: myHeaders });
}
async postMessages(msg = {}) {
const myHeaders = new Headers();
myHeaders.append('Authorization', ['Bearer ', chatController.token].join(''));
myHeaders.append('Content-Type', 'application/json');
let raw;
msg.to ? raw = JSON.stringify({ text: msg.text, isPersonal: true, author: msg.author, to: msg.to })
: raw = JSON.stringify({ text: msg.text, isPersonal: false, author: msg.author });
return this._fetchRequest('messages', { method: 'POST', headers: myHeaders, body: raw });
}
async putMessages(id = '', msg = {}) {
const myHeaders = new Headers();
myHeaders.append('Authorization', ['Bearer ', chatController.token].join(''));
myHeaders.append('Content-Type', 'application/json');
let raw;
msg.to ? raw = JSON.stringify({ text: msg.text, isPersonal: true, to: msg.to })
: raw = JSON.stringify({ text: msg.text, isPersonal: false });
return this._fetchRequest(`messages/${id}`, { method: 'PUT', headers: myHeaders, body: raw });
}
}
const showMore = document.getElementById('button-show-more');
const headerPrivate = document.getElementById('headerPrivateChat');
let myTop = 10;
let buttonIsHidden = false;
class ChatController {
token;
_size;
constructor() {
this.headerView = new HeaderView('userNameId');
this.messagesView = new MessagesView('messages');
this.usersView = new UsersView('users-list');
}
setCurrentUser(user = '') {
this.headerView.display(user);
document.getElementById('input').style.visibility = 'visible';
document.getElementById('button-log-out').textContent = 'Log out';
}
async addMessage(msg = {}) {
if (!msg.to) {
const response = await chatApiService.postMessages({ text: msg.text, author: msg.author, isPersonal: false });
if (response.ok) {
await chatController.showMessages(0, 1000, { isPersonal: false }, 2000);
}
} else {
const response = await chatApiService.postMessages({ text: msg.text, author: msg.author, isPersonal: true, to: msg.to });
if (response.ok) {
await chatController.showMessages(0, 1000, { isPersonal: true, personalToFrom: msg.to }, 2000);
}
}
}
async editMessage(id = '', msg = {}) {
if (!msg.to) {
const response = await chatApiService.putMessages(id, { text: msg.text });
if (response.ok) {
await chatController.showMessages(0, 1000, { isPersonal: false }, 2000);
}
} else {
const response = await chatApiService.putMessages({ text: msg.text, author: msg.author, isPersonal: true, to: msg.to });
if (response.ok) {
await chatController.showMessages(0, 1000, { isPersonal: true, personalToFrom: msg.to }, 2000);
}
}
}
async removeMessage(id = '') {
const response = await chatApiService.deleteMessages(id);
if (response.ok) {
headerPrivate.style.display === 'flex'
? await chatController.showMessages(0, 1000, { isPersonal: true, personalToFrom: currentUserPrivate }, 2000)
: await chatController.showMessages(0, 1000, { isPersonal: false }, 2000);
}
}
async _fetchMessages(skip, top, filterConfig) {
let response;
headerPrivate.style.display === 'flex'
? response = await chatApiService.getMessages(skip, top, filterConfig, chatController.token)
: response = await chatApiService.getMessages(skip, top, filterConfig);
this.messagesView.display((JSON.parse(response)).reverse());
this._size = (JSON.parse(response)).length;
}
async _fetchUsers() {
const response = await chatApiService.getUsers();
this.usersView.display(JSON.parse(response));
}
async showMessages(skip = 0, top = 10, filterConfig = {}, time = 70000) {
setTimeout(() => this._fetchMessages(skip, top, filterConfig), time);
scrollToEndPage();
if (this._size <= 10 || !buttonIsHidden) {
showMore.style.display = 'flex';
} else showMore.style.display = 'none';
if (headerPrivate.style.display === 'flex') showMore.style.display = 'none';
}
async showUsers(time = 70000) {
setInterval(() => this._fetchUsers(), time);
}
async callBackFormLogIn() {
event.preventDefault();
try {
await chatApiService.login(login.value, password.value)
.then((result) => {
chatController.token = JSON.parse(result).token;
logInContainer.style.display = 'none';
buttonLogOut.style.visibility = 'visible';
chatController.showUsers();
myTop = 10;
chatController.setCurrentUser(login.value);
chatController.showMessages(0, 10, {}, 2000);
userNameHeader = login.value;
});
} catch (err) {
if (login.value === '' || password.value === '') {
error.textContent = 'Fill in all the fields.';
} else {
const response = await chatApiService.getUsers();
const users = JSON.parse(response);
users.find((user) => user.name === login.value) ? error.textContent = 'Wrong password.'
: error.textContent = 'Wrong login.';
}
}
}
async callBackFormSignUp() {
event.preventDefault();
const newLogin = document.getElementById('loginSignUp');
const newPassword = document.getElementById('passwordSignUp');
const confirmPassword = document.getElementById('confirmPassword');
try {
if (newPassword.value === confirmPassword.value && newPassword.value !== '') {
await chatApiService.register(newLogin.value, newPassword.value)
.then(() => {
if (newPassword.value === confirmPassword.value && newPassword.value !== '') {
login.value = newLogin.value;
logInContainer.style.display = 'flex';
signUpContainer.style.display = 'none';
login.value = newLogin.value;
}
});
} else {
confirmPassword.value === ''
? errorSignUp.textContent = 'Fill in all the fields.'
: errorSignUp.textContent = 'Passwords do not match.';
confirmPassword.blur();
confirmPassword.style.border = '1px solid #<PASSWORD>';
}
} catch (error) {
console.log(error);
errorSignUp.textContent = 'Login already exists.';
}
}
}
const chatController = new ChatController();
const chatApiService = new ChatApiService('https://jslabdb.datamola.com');
chatController.showUsers(2000);
chatController.showMessages(0, 10, {}, 2000);
const mainPage = document.getElementById('main');
const logInContainer = document.getElementById('log-in-container');
const signUpContainer = document.getElementById('sign-up-container');
const login = document.getElementById('login');
const password = document.getElementById('password');
const formToLogin = document.getElementById('formLogIn');
const formToSignUp = document.getElementById('formSignUp');
const error = document.getElementById('errorsLog');
const errorSignUp = document.getElementById('errors');
const buttonLogOut = document.getElementById('button-log-out');
const logo = document.getElementById('logo');
const buttonSignUp = document.getElementById('buttonSignUp');
const logInOut = document.getElementById('button-log-out');
const messagesBody = document.getElementById('messages');
const namePrivateChat = document.getElementById('namePrivateChat');
const buttonReturnToChat = document.getElementById('buttonReturnToChat');
const userList = document.getElementById('users-list');
const enterMessage = document.getElementById('formTextArea');
const buttonEnterMessage = document.getElementById('submitTextArea');
const textArea = document.getElementById('text-area-enter');
const textArea2 = document.getElementById('text-area-enter2');
const filterContainer = document.getElementById('filter-container');
const errorButton = document.getElementById('errorButton');
const errorPage = document.getElementById('errorContainer');
let currentUserPrivate;
let userNameHeader;
let result;
async function foo() {
const messages = document.querySelectorAll('.my-message-container');
const arr = [...messages];
let myMess;
const eventClick = event.target;
const container = eventClick.closest('.my-message-container');
if (headerPrivate.style.display === 'flex') {
const response = await chatApiService.getMessages(0, 1000, { isPersonal: true, personalToFrom: currentUserPrivate, author: userNameHeader }, chatController.token);
const res = await response;
myMess = [...JSON.parse(res).reverse()];
} else {
const response = await chatApiService.getMessages(0, 1000, { isPersonal: false, author: userNameHeader });
const res = await response;
myMess = [...JSON.parse(res).reverse()];
}
const index = arr.indexOf(container);
return myMess[index];
}
async function callBackMessageBody() {
const eventClick = event.target;
if (eventClick.className === 'my-message-text') {
const buttons = [...eventClick.closest('.my-message-body').children].find((el) => el.className === 'buttons-delete-edit');
buttons.style.visibility = 'visible';
}
if (eventClick.className === 'button-edit') {
const response = await foo();
textArea.style.display = 'none';
buttonEnterMessage.style.display = 'none';
textArea2.style.display = 'block';
textArea2.value = response.text;
result = response.id;
}
if (eventClick.className === 'button-delete') {
const container = eventClick.closest('#my-message');
eventClick.parentNode.style.display = 'none';
container.innerHTML += `<div class="button-confirm-delete">
<input id="button-confirm-delete" onchange="confirmDeleteMessage()" type="checkbox">
Delete
</div>`;
}
}
function scrollToEndPage() {
const arr = [...document.querySelectorAll('.message-container')];
if (arr.length > 0) {
const endPage = arr;
const size = endPage.length;
endPage[size - 1].scrollIntoView();
}
}
async function formFilter() {
event.preventDefault();
const userName = document.getElementById('filter-name');
const textMessage = document.getElementById('filter-text');
const dateMessage = document.getElementById('filter-date');
const filters = { author: userName.value, text: textMessage.value, dateFrom: dateMessage.value };
if (headerPrivate.style.display === 'flex') {
filters.isPersonal = true;
filters.personalToFrom = currentUserPrivate;
} else {
filters.isPersonal = false;
}
await chatController.showMessages(0, 100, filters, 2000);
showMore.style.display = 'none';
if (chatController._size === 0) {
chatController.messagesView.container.innerHTML = '<p class="nothing-to-found">Nothing to found.</p>';
}
userName.value = '';
textMessage.value = '';
dateMessage.value = '';
}
async function callBackPrivateMessages() {
const eventClick = event.target;
if (eventClick.tagName === 'svg' || eventClick.tagName === 'path') {
currentUserPrivate = eventClick.closest('.active-user').lastElementChild.textContent;
showMore.style.display = 'none';
headerPrivate.style.display = 'flex';
namePrivateChat.textContent = currentUserPrivate;
await chatController.showMessages(0, 1000, { isPersonal: true, personalToFrom: currentUserPrivate });
}
}
function callBackEditMess() {
if (event.which === 13 && !event.shiftKey) {
showMore.style.display = 'none';
textArea2.style.display = 'none';
textArea.style.display = 'block';
buttonEnterMessage.style.display = 'block';
headerPrivate.style.display === 'none'
? chatController.editMessage(result, { text: textArea2.value })
: chatController.editMessage(result, { text: textArea2.value, to: currentUserPrivate });
}
}
async function callBackShowMore() {
buttonIsHidden = false;
const res = await chatApiService.getMessages(0, 1000);
if (JSON.parse(res).length > 0) {
myTop += 10;
chatController.showMessages(0, myTop, {}, 1000);
if (JSON.parse(res).length - myTop <= 0) {
showMore.style.display = 'none';
myTop = 10;
buttonIsHidden = true;
}
}
}
function returnToChat() {
headerPrivate.style.display = 'none';
chatController.showMessages();
}
function addMessages() {
event.preventDefault();
if (event.which === 13 && !event.shiftKey) {
addMessagesButton();
}
}
function addMessagesButton() {
event.preventDefault();
headerPrivate.style.display === 'flex'
? chatController.addMessage({ text: textArea.value, author: userNameHeader, to: currentUserPrivate })
: chatController.addMessage({ text: textArea.value, author: userNameHeader });
textArea.value = '';
showMore.style.display = 'none';
}
async function confirmDeleteMessage() {
const response = await foo();
await chatController.removeMessage(response.id);
}
function clickButtonSignUp() {
logInContainer.style.display = 'none';
signUpContainer.style.display = 'flex';
buttonLogOut.style.visibility = 'hidden';
}
function toMainPage() {
logInContainer.style.display = 'none';
signUpContainer.style.display = 'none';
buttonLogOut.style.visibility = 'visible';
}
async function buttonLogOutIn() {
if (logInOut.textContent === 'Log out') {
event.preventDefault();
const response = await chatApiService.logout();
if (response.ok) {
chatController.setCurrentUser('');
document.getElementById('userNameId').innerText = '';
logInOut.textContent = 'Log in';
chatController.showMessages();
document.getElementById('input').style.visibility = 'hidden';
headerPrivate.style.display = 'none';
}
} else {
event.preventDefault();
logInContainer.style.display = 'flex';
}
}
function errorToHome() {
errorPage.style.display = 'none';
logo.style.display = 'flex';
buttonLogOut.style.display = 'block';
mainPage.style.display = 'flex';
showMore.style.display = 'flex';
document.getElementById('input').style.visibility = 'hidden';
logInOut.textContent = 'Log in';
}
textArea.addEventListener('keyup', addMessages);
enterMessage.addEventListener('submit', addMessagesButton);
textArea2.addEventListener('keyup', callBackEditMess);
userList.addEventListener('click', callBackPrivateMessages);
buttonReturnToChat.addEventListener('click', returnToChat);
formToLogin.addEventListener('submit', chatController.callBackFormLogIn);
formToSignUp.addEventListener('submit', chatController.callBackFormSignUp);
filterContainer.addEventListener('submit', formFilter);
buttonSignUp.addEventListener('click', clickButtonSignUp);
logInOut.addEventListener('click', buttonLogOutIn);
showMore.addEventListener('click', callBackShowMore);
messagesBody.addEventListener('click', callBackMessageBody);
<file_sep>let players = ['Computer','You'],
winningCombinations = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
const winContainer = document.getElementById('containerWin');
const winner = document.getElementById('win');
const resetButton = document.getElementById('resetButton');
const box = document.getElementById('box');
const fields = document.getElementsByClassName('field');
let arr = [];
let arrComp = [];
function isWinning(arr, player) {
for (let i = 0; i < winningCombinations.length; i++) {
if (arr.sort().join().includes((winningCombinations[i]).sort().join())) {
winContainer.style.visibility = 'visible';
winner.textContent = `${player} won!`;
}
}
}
function computer() {
if ([...fields].find(e => e.value === '')) {
let id = Math.floor(Math.random() * 10);
if (arr.indexOf(id) === -1 && id <= 8 && arrComp.indexOf(id) === -1) {
let field = document.getElementById(id.toString());
field.value = 'o';
arrComp.push(id);
if (arrComp.length >= 3) isWinning(arrComp, players[0]);
} else computer();
}else isWinning(arr,players[1]);
}
box.addEventListener('click', (event) => {
const target = event.target;
if(target.value === '') {
arr.push(Number(target.id));
if (target.className === 'field') {
target.value = 'x';
}
if (arr.length >= 3) isWinning(arr, players[1]);
computer();
}
});
resetButton.addEventListener('click',reset);
function reset() {
const fields = document.querySelectorAll('.field');
fields.forEach((field) => field.value = '');
arr.splice(0);
arrComp.splice(0);
winContainer.style.visibility = 'hidden';
}
<file_sep>function prices(prices) {
let sum = 0;
if (prices.length <= 3 * 10 ** 4 && prices.length >= 1) {
for (let i = 0; i < prices.length; i++) {
for (let j = 0; j < prices.length; j++) {
if (prices[i] < prices[j])
sum += prices[j] - prices[i];
i = j;
if(prices[i]>10**4 || prices[i]<0)
return 'incorrect value'
}
}
return sum;
}
else return 'incorrect array'
}
console.log(prices([7,1,5,3,6,4]))
console.log(prices([1,2,3,4,5]))
console.log(prices([7,6,4,3,1]))
console.log(prices([7,600000,4,3,1]))
console.log(prices([]))
| a4030423eb1f3dcbc13cea13550dbc5308a6d57e | [
"JavaScript"
] | 6 | JavaScript | YaroshevichVictoria/DataMolaJSCamping | 08ef7bc0ed685867315dc980798257d342ea5ace | e109b095907bf406f81fd8e06a49da30b7c9f702 |
refs/heads/master | <repo_name>cmacswan07/dd_tech_challenge<file_sep>/README.md
# dd_tech_challenge
Linked-List Demo

Demo project built with Express and Vue. Manages a linked list stored on Node back end via an Express API that Vue front end interacts with.
<file_sep>/server/index.js
const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const cors = require('cors')
const app = express()
const port = process.env.PORT || 5000
app.use(bodyParser.json())
app.use(cors())
app.use(express.static(path.join(__dirname, '../client/dist')))
/* Linked List Objects */
function Node(element) {
this.element = element
this.next = null
}
function LinkedList() {
this.head = null
this.size = 0
this.add = function(element) {
let current
let node = new Node(element)
if (this.head == null) {
this.head = node
} else {
let current = this.head
while (current.next) {
current = current.next
}
current.next = node
}
this.size++
}
this.insertAt = function(element, index) {
if (index > 0 && index > this.size) {
return console.log('Index larger than list size, use add method')
} else {
let node = new Node(element)
let current
let previous
current = this.head
if (index === 0) {
node.next = this.head
this.head = node
} else {
for (i = 0; i < index; i++) {
previous = current
current = current.next
}
previous.next = node
node.next = current
}
this.size++
}
}
this.editElement = function(newElement, index) {
let current = this.head
while (current != null) {
if (current.element.id === index) {
current.element.item = newElement
}
current = current.next
}
}
this.removeElement = function(element) {
let current = this.head
let previous = null
while (current != null) {
if (current.element.id === element) {
if (previous == null) {
this.head = current.next
} else {
previous.next = current.next
}
this.size--
}
previous = current
current = current.next
}
}
this.getElements = function() {
let current = this.head
let elementArray = []
while (current != null) {
elementArray.push(current.element)
current = current.next
}
return elementArray
}
this.clearElements = function () {
this.head = null
this.size = 0
}
}
let linkedList = new LinkedList()
let itemList = []
/* Routes */
app.get('/getItems', (req, res) => {
itemList = linkedList.getElements()
console.log(itemList)
res.send(itemList)
})
app.post('/addItem', (req, res) => {
linkedList.add(req.body)
itemList = linkedList.getElements()
res.send(req.body)
})
app.post('/removeItem', (req, res) => {
linkedList.removeElement(req.body.id)
itemList = linkedList.getElements()
res.send(itemList)
})
app.post('/editItem', (req, res) => {
linkedList.editElement(req.body.item, req.body.id)
itemList = linkedList.getElements()
res.send(itemList)
})
app.post('/clearItems', (req, res) => {
linkedList.clearElements()
itemList = linkedList.getElements()
res.send(itemList)
})
app.listen(port, () => {
console.log(`Server running on ${port}`)
}) | 0cb375433b71a5a8309c1d80eb0e1f3512fc66a8 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | cmacswan07/dd_tech_challenge | c3a7eef7a6721833080252b559ff855494c83a40 | 9aeff65def056ec4b4d938cf8f46173dc158ea88 |
refs/heads/master | <repo_name>chenrenxi/GitDemo1<file_sep>/main.cpp
#include <iostream>
using namespace std;
#include "Dog.h"
int add1(int a, int b)
{
return a+b;
}
int multiply(int a, int b)
{
return a*b;
}
int div(int a, int b)
{
return a/b;
}
//add by chenrenxi branch2
int pow(int a, int b)
{
return 0;
}
//add by chenrenxi branch2
int circle(int x, int y, int r)
{
}
//add by chenrenxi
float du()
{
}
//this is a demo of github
//cloned from the main
int main()
{
cout << "Hello world!" << endl;
int a = 1;
int b = 2;
int c = a + b;
cout << "c="<<c<<endl;
Dog d1, d2;
d1.bark();
d2.bark();
int d = add1(a, b);
int f = multiply(a, b);
cout<<"finished!"<<endl;
return 0;
}
//this a branch1
<file_sep>/readme.txt
This is a github demo.
add from chenrenxi
add line at 8:16
add line at 8:19
add line at 8:21
added by suncrx
hello
this is added from master
this is added from master 2
updated by master
<file_sep>/Dog.h
#ifndef DOG_H
#define DOG_H
#include <iostream>
#include <string>
using namespace std;
class Dog
{
public:
Dog();
virtual ~Dog();
string getName();
void setName(string sname);
void bark();
protected:
string name;
int color;
int birthday;
private:
};
#endif // DOG_H
<file_sep>/Dog.cpp
#include "Dog.h"
Dog::Dog()
{
//ctor
name = "<NAME>";
color = 6;
}
Dog::~Dog()
{
//dtor
}
string Dog::getName()
{
return name;
}
void Dog::setName(string sname)
{
name = sname;
}
void Dog::bark()
{
cout<<"I am "<<name<<endl;
cout << "color " << color << endl;
}
| ddebede2abe0c2d1610ccaee4cd88c887a4f2630 | [
"Text",
"C++"
] | 4 | C++ | chenrenxi/GitDemo1 | 7a44f6ad90b12562f8396eb5880f5980e5bf508f | b2aa4bafef47c6a66017b4431c9e61db46d55afe |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace NirDobovizki.MvvmMonkey.Advanced
{
internal class CommandMethodPropertyDescriptor : PropertyDescriptor
{
private Type _objectType;
private MethodInfo _methodInfo;
public CommandMethodPropertyDescriptor(Type objectType, MethodInfo methodInfo) : base(methodInfo.Name, new Attribute[0])
{
_objectType = objectType;
_methodInfo = methodInfo;
}
public override Type ComponentType
{
get
{
return _objectType;
}
}
public override bool IsReadOnly
{
get
{
return true;
}
}
public override Type PropertyType
{
get
{
return typeof(ICommand);
}
}
public override bool CanResetValue(object component)
{
return false;
}
public override object GetValue(object component)
{
if(_methodInfo.ReturnType == typeof(Task))
{
if (_methodInfo.GetParameters().Length == 0)
{
var d = (Func<Task>)_methodInfo.CreateDelegate(typeof(Func<Task>), component);
return new TaskDelegateCommand(_ => d());
}
else
{
var d = (Func<object, Task>)_methodInfo.CreateDelegate(typeof(Func<object, Task>), component);
return new TaskDelegateCommand(d);
}
}
else
{
if (_methodInfo.GetParameters().Length == 0)
{
var d = (Action)_methodInfo.CreateDelegate(typeof(Action), component);
return new SimpleDelegateCommand(_ => d());
}
else
{
var d = (Action<object>)_methodInfo.CreateDelegate(typeof(Action<object>), component);
return new SimpleDelegateCommand(d);
}
}
}
public override void ResetValue(object component)
{
throw new NotSupportedException();
}
public override void SetValue(object component, object value)
{
throw new NotSupportedException();
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
}
}
<file_sep># MvvmMonkey
MvvmMonkey is a low-overhead library that take a little bit of the boiler-plate (and pain) out of MVVM.
MvvmMonkey is not a framework, it's a collections of features you can pick and choose from,
it's primary design goal is to have have minimal effect on the application using it.
Currently there's just one version of this library targeting WPF 4.5 (MvvmMonkey.Wpf), if there's demand I'll
port the library to the other XAML platforms (probably just to "Universal Windows App").
Compnents in this library:
Method Binding
---
Adding the '[TypeDescriptionProvider(typeof(MethodBinding))]' attribute to you view model class
will add "fake" ICommand properties for each method that accepts zero or one parameters
The command method should either return void or Task, if you return task ICommand.CanExecute will
return false until the task is complete - disabling the button and preventing the user from
accedently clickign it again while waiting.
View Model:
[TypeDescriptionProvider(typeof(MethodBinding))]
class DemoSelectionViewModel : INotifyPropertyChanged
{
public void MethodBindingDemo()
{
Child = new MethodBindingViewModel();
}
}
View:
<Button Command="{Binding MethodBindingDemo}">
<TextBlock TextWrapping="Wrap" Text="Bind to method demo"/>
</Button>
Password Binding
---
Bind PasswordBox.Password to a secure string
View Model:
class PasswordViewModel
{
public SecureString Password { get; set; }
}
View:
<PasswordBox
monkey:PasswordBinding.IsPasswordBindingEnabled="True"
monkey:PasswordBinding.Password="{Binding Password}"/>
Enum Binding
---
Using an enum with a radio button group is extreamly annoying and error-prone if you use view model bool properties.
Luckly, with this converter you can bind multiple radio buttons to the same enum property
<UserControl.Resources>
<monkey:EnumValueIsCheckedConverter x:Key="EnumRadioConverter"/>
</UserControl.Resources>
<RadioButton GroupName="MyGrp" IsChecked="{Binding TheValue, Converter={StaticResource EnumRadioConverter}, ConverterParameter={x:Static model:AnEnum.First}}">First</RadioButton>
<RadioButton GroupName="MyGrp" IsChecked="{Binding TheValue, Converter={StaticResource EnumRadioConverter}, ConverterParameter={x:Static model:AnEnum.Second}}">Second</RadioButton>
<RadioButton GroupName="MyGrp" IsChecked="{Binding TheValue, Converter={StaticResource EnumRadioConverter}, ConverterParameter={x:Static model:AnEnum.Third}}">Third</RadioButton>
View Locator
---
The 'ViewLocator' control will automatically find the view for your view model
without any mapping (if your view model ends with "ViewModel" your view has the same name but ends with "View"
and they are both in the same assembly)
Also, if you set the ViewLocator.HasViews attached property on and ItemsControl (ListBox, etc.) it will add a data template
with a ViewLocator so you can just bind a list of view models to ItemSource and the views will show up inside the list
View Model:
[TypeDescriptionProvider(typeof(MethodBinding))]
class DemoSelectionViewModel : INotifyPropertyChanged
{
public void MethodBindingDemo()
{
Child = new MethodBindingViewModel();
}
}
View:
<mvvm:ViewLocator DataContext="{Binding Child}"/>
Notify Property Changed
---
I don't know a way to get rid of all the boiler plate of INotifyPropertyChanged but I can
write the OnPropertyChanged method - and, in the spirit of MvvmMonkey, you don't need to
change you class heirarcy to use it
private object _child;
public object Child
{
get { return _child; }
set
{
if(_child!=value)
{
_child = value;
PropertyChange.Notify(this, PropertyChanged);
}
}
}
Window Manager
---
One of the most anoying thing bout MVVM is that there isn't really a good way to open and close windows.
Either you break the View-View-Model seperation, hurt the system testebility or use an overkill messaging system.
The WindowManager addresses all of that, it has an interface like a simple light-weight system that doesn't really support testing
but has a replacable implementation so it cn suport anything.
By default WindowManager uses ViewLocator to show the view inside the window
To open a view model in another window:
WindowManager.OpenDialog(new WindowManagerChildViewModel());
or
WindowManager.OpenNonModal(new WindowManagerChildViewModel());
To close:
WindowManager.Close(this);
To replace the windows manager code for unit testing or diffrent windowing strategy:
WindowManager.SetImplementation(myWindowManager);
Licensing
---
MvvmMonkey is copyrighted by <NAME>, it uses the MIT license.
If you use this library I would love to know about it (but you are not required to tell me), also for any questions or suggestions you can contact me at <EMAIL><file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace NirDobovizki.MvvmMonkey.Advanced
{
public class TaskDelegateCommand : ICommand
{
private Func<object, Task> _target;
public TaskDelegateCommand(Func<object, Task> target)
{
_target = target;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return !InWork;
}
public async void Execute(object parameter)
{
if (InWork) return;
InWork = true;
try
{
await _target(parameter);
}
finally
{
InWork = false;
}
}
private bool _inWork;
private bool InWork
{
get { return _inWork; }
set
{
_inWork = value;
var eh = CanExecuteChanged;
if (eh != null) eh(this, EventArgs.Empty);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NirDobovizki.MvvmMonkey.Wpf.Demo.ViewModels
{
[TypeDescriptionProvider(typeof(MethodBinding))]
[DisplayName("Method Binding with Tasks")]
class MethodBindingTaskViewModel
{
public Task CallDelay()
{
return Task.Delay(2000);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace NirDobovizki.MvvmMonkey
{
public class ViewLocator : Decorator
{
private static Dictionary<Type, Type> _viewByViewModel = new Dictionary<Type, Type>();
public static DependencyProperty HasViewsProperty = DependencyProperty.RegisterAttached("HasViews", typeof(bool), typeof(ViewLocator), new PropertyMetadata(false, HasViewsChanged));
public static bool GetHasViews(ItemsControl element)
{
return (bool)element.GetValue(HasViewsProperty);
}
public static void SetHasViews(ItemsControl element, bool value)
{
element.SetValue(HasViewsProperty, value);
}
private static void HasViewsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(bool)e.NewValue) return;
var itemControl = d as ItemsControl;
if (d == null) return;
if (itemControl.ItemTemplate != null) return;
itemControl.ItemTemplate = new DataTemplate()
{
VisualTree = new FrameworkElementFactory(typeof(ViewLocator))
};
}
public ViewLocator()
{
DataContextChanged += OnDataContextChanged;
}
private void OnDataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
{
Child = null;
if (e.NewValue == null)
{
return;
}
Type viewModelType = e.NewValue.GetType();
Type viewType;
if(!_viewByViewModel.TryGetValue(viewModelType, out viewType))
{
var viewModelName = viewModelType.Name;
if (!viewModelName.EndsWith("ViewModel", StringComparison.Ordinal)) throw new InvalidOperationException("View model type name must contain ViewModel to use ViewLocator");
var viewName = viewModelName.Substring(0, viewModelName.Length - 5); // "ViewModel" -> "View"
viewType = viewModelType.Assembly.GetTypes().SingleOrDefault(x => string.CompareOrdinal(x.Name, viewName)==0);
if(viewType == null)
{
System.Diagnostics.Trace.WriteLine(string.Format("MvvmMonkey.ViewLocator: can't find view class {0} for view model {1}", viewName, e.NewValue.ToString()));
return;
}
_viewByViewModel.Add(viewModelType, viewType);
}
Child = (UIElement)Activator.CreateInstance(viewType);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace NirDobovizki.MvvmMonkey.Advanced
{
public class SimpleDelegateCommand : ICommand
{
private Action<object> _target;
public SimpleDelegateCommand(Action<object> target)
{
_target = target;
}
#pragma warning disable 0067 // the CanExecuteChanged event is never used
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_target(parameter);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NirDobovizki.MvvmMonkey.Wpf.Demo.ViewModels
{
[TypeDescriptionProvider(typeof(MethodBinding))]
[DisplayName("Method Binding")]
public class MethodBindingViewModel
{
public void Fire()
{
System.Windows.MessageBox.Show("yey");
}
}
}
| 37a3eeba6a77167984df7ce45e6e5c519835955f | [
"Markdown",
"C#"
] | 7 | C# | arielbh/MvvmMonkey | f7aad1d52cb4557352500f4c1c87194755e336d4 | 8a5f0a87bd8517709d84be13dc89b0a1387c39a8 |
refs/heads/master | <file_sep>package buslogicdemo.data;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
/**
* Data Object for Product.
* Each row represents a Product sold on PurchaseOrders to Customers.
*/
@Entity
@Table(name="product")
public class Product implements java.io.Serializable {
@Id
@Column(name="product_number")
public long getProductNumber() { return productNumber; }
public void setProductNumber(long prodNum) { this.productNumber = prodNum; }
private long productNumber;
@Column
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
private String name;
@Column
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
private BigDecimal price;
// Relationships
@OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.LAZY, mappedBy="product")
public Set<Lineitem> getLineitems() { return lineitems; }
public void setLineitems(Set<Lineitem> lineitems) { this.lineitems = lineitems; }
private Set<Lineitem> lineitems = new HashSet<Lineitem>();
private static final long serialVersionUID = 1L;
}
<file_sep>package buslogicdemo.util;
import java.math.BigDecimal;
import org.hibernate.Session;
import buslogicdemo.data.*;
public class DataLoader {
public static boolean initialDataLoaded = false;
public static void reloadData(Session session) {
dropData(session);
loadData(session);
}
public static void dropData(Session session) {
session.createQuery("delete from Lineitem").executeUpdate();
session.createQuery("delete from Purchaseorder").executeUpdate();
session.createQuery("delete from Product").executeUpdate();
session.createQuery("delete from Customer").executeUpdate();
session.createSQLQuery("ALTER TABLE PURCHASEORDER ALTER COLUMN order_number RESTART WITH 1").executeUpdate();
session.createSQLQuery("ALTER TABLE LINEITEM ALTER COLUMN lineitem_id RESTART WITH 1").executeUpdate();
}
public static void loadData(Session session) {
initialDataLoaded = true;
System.out.println("Loading sample data...");
// Create customers
Customer alpha = new Customer();
alpha.setName("Alpha and Sons");
alpha.setCreditLimit(new BigDecimal(1900));
session.save(alpha);
Customer bravo = new Customer();
bravo.setName("Bravo Hardware");
bravo.setCreditLimit(new BigDecimal(5000));
session.save(bravo);
Customer charlie = new Customer();
charlie.setName("Charlie's Construction");
charlie.setCreditLimit(new BigDecimal(1500));
session.save(charlie);
Customer delta = new Customer();
delta.setName("Delta Engineering");
delta.setCreditLimit(new BigDecimal(500));
session.save(delta);
// Create products
Product drill = new Product();
drill.setProductNumber(1);
drill.setName("Drill");
drill.setPrice(new BigDecimal(315));
session.save(drill);
Product hammer = new Product();
hammer.setProductNumber(2);
hammer.setName("Hammer");
hammer.setPrice(new BigDecimal(10));
session.save(hammer);
Product shovel = new Product();
shovel.setProductNumber(3);
shovel.setName("Shovel");
shovel.setPrice(new BigDecimal(25));
session.save(shovel);
// Create PurchaseOrders
Purchaseorder po1 = new Purchaseorder();
po1.setOrderNumber(1L);
po1.setPaid(false);
po1.setNotes("This is a small order");
po1.setCustomer(alpha);
session.save(po1);
Purchaseorder po2 = new Purchaseorder();
po2.setOrderNumber(2L);
po2.setPaid(true);
po2.setNotes("");
po2.setCustomer(bravo);
session.save(po2);
Purchaseorder po3 = new Purchaseorder();
po3.setOrderNumber(3L);
po3.setPaid(false);
po3.setNotes("Please rush this order");
po3.setCustomer(bravo);
session.save(po3);
Purchaseorder po4 = new Purchaseorder();
po4.setOrderNumber(4L);
po4.setPaid(false);
po4.setNotes("Deliver by overnight with signature required");
po4.setCustomer(charlie);
session.save(po4);
Purchaseorder po5 = new Purchaseorder();
po5.setOrderNumber(5L);
po5.setPaid(false);
po5.setNotes("");
po5.setCustomer(charlie);
session.save(po5);
Purchaseorder po6 = new Purchaseorder();
po6.setOrderNumber(6L);
po6.setPaid(false);
po6.setNotes("Pack with care - fragile merchandise");
po6.setCustomer(alpha);
session.save(po6);
Purchaseorder po7 = new Purchaseorder();
po7.setOrderNumber(7L);
po7.setPaid(false);
po7.setNotes("No Saturday delivery");
po7.setCustomer(delta);
session.save(po7);
// Create LineItems
Lineitem li = new Lineitem();
li.setLineitemId(1L);
li.setQtyOrdered(1);
li.setProduct(hammer);
li.setPurchaseorder(po1);
session.save(li);
li = new Lineitem();
li.setLineitemId(2L);
li.setQtyOrdered(2);
li.setProduct(hammer);
li.setPurchaseorder(po2);
session.save(li);
li = new Lineitem();
li.setLineitemId(3L);
li.setQtyOrdered(1);
li.setProduct(shovel);
li.setPurchaseorder(po2);
session.save(li);
li = new Lineitem();
li.setLineitemId(4L);
li.setQtyOrdered(3);
li.setProduct(drill);
li.setPurchaseorder(po2);
session.save(li);
li = new Lineitem();
li.setLineitemId(5L);
li.setQtyOrdered(1);
li.setProduct(hammer);
li.setPurchaseorder(po3);
session.save(li);
li = new Lineitem();
li.setLineitemId(6L);
li.setQtyOrdered(2);
li.setProduct(shovel);
li.setPurchaseorder(po3);
session.save(li);
li = new Lineitem();
li.setLineitemId(7L);
li.setQtyOrdered(1);
li.setProduct(hammer);
li.setPurchaseorder(po4);
session.save(li);
li = new Lineitem();
li.setLineitemId(8L);
li.setQtyOrdered(3);
li.setProduct(shovel);
li.setPurchaseorder(po4);
session.save(li);
li = new Lineitem();
li.setLineitemId(9L);
li.setQtyOrdered(1);
li.setProduct(hammer);
li.setPurchaseorder(po5);
session.save(li);
li = new Lineitem();
li.setLineitemId(10L);
li.setQtyOrdered(5);
li.setProduct(shovel);
li.setPurchaseorder(po5);
session.save(li);
li = new Lineitem();
li.setLineitemId(11L);
li.setQtyOrdered(2);
li.setProduct(shovel);
li.setPurchaseorder(po6);
session.save(li);
li = new Lineitem();
li.setLineitemId(12L);
li.setQtyOrdered(1);
li.setProduct(shovel);
li.setPurchaseorder(po1);
session.save(li);
li = new Lineitem();
li.setLineitemId(13L);
li.setQtyOrdered(3);
li.setProduct(hammer);
li.setPurchaseorder(po6);
session.save(li);
li = new Lineitem();
li.setLineitemId(14L);
li.setQtyOrdered(7);
li.setProduct(hammer);
li.setPurchaseorder(po7);
session.save(li);
}
}
<file_sep>/**
* Domain Objects (POJOs) for Bus Logic Demo (click for diagram).
*/
package buslogicdemo.data;
<file_sep>/**
* Business Logic Components for Bus Logic Demo.
*/
package buslogicdemo.businesslogic;
<file_sep>package buslogicdemo.data.manual;
import java.math.BigDecimal;
import java.util.List;
import java.util.Vector;
import buslogicdemo.data.*;
import buslogicdemo.util.HibernateFactory;
/**
* Business logic for the Product class. This class actually has no business logic per se,
* but it was felt that it needed a service object anyway for uniformity.
*/
public class SProduct {
private Product product;
protected SProduct(Product product) {
this.product = product;
}
/**
* Get a Product based on its primay key.
*/
public static SProduct getById(long id) {
Product product = (Product)HibernateFactory.session.load(Product.class, id);
SProduct result = new SProduct(product);
return result;
}
/**
* Get all Products, sorted by name.
*/
public static List<SProduct> getAll() {
@SuppressWarnings("unchecked")
List<Product> products = HibernateFactory.session.createQuery("from Product order by name").list();
List<SProduct> result = new Vector<SProduct>();
for (Product p : products)
result.add(new SProduct(p));
return result;
}
/**
* Internal method: get the underlying Hibernate bean.
* @return
*/
protected Product getBean() { return product; }
/**
* Get this Product's primary key.
*/
public long getProductNumber() { return product.getProductNumber(); }
/**
* Get this Product's name.
*/
public String getName() { return product.getName(); }
/**
* Get this Product's price.
*/
public BigDecimal getPrice() { return product.getPrice(); }
}
<file_sep>package buslogicdemo.data.manual;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import buslogicdemo.util.HibernateFactory;
import buslogicdemo.data.*;
/**
* Business logic layer for the Purchaseorder class.
*/
public class SPurchaseorder {
private Purchaseorder po;
protected SPurchaseorder(Purchaseorder po) {
this.po = po;
}
/**
* Get a Purchaseorder based on its primary key.
*/
public static SPurchaseorder getById(long id) {
Purchaseorder po = (Purchaseorder)HibernateFactory.session.load(Purchaseorder.class, id);
SPurchaseorder result = new SPurchaseorder(po);
return result;
}
/**
* Create a new Purchaseorder for the given Customer.
*/
public static SPurchaseorder create(SCustomer cust) {
Purchaseorder po = new Purchaseorder();
po.setCustomer(cust.getBean());
po.setPaid(false);
po.setAmountTotal(BigDecimal.ZERO);
SPurchaseorder result = new SPurchaseorder(po);
return result;
}
/**
* Persist any changes to this Purchaseorder.
*/
public void save() {
HibernateFactory.session.saveOrUpdate(po);
}
/**
* Delete this Purchaseorder. If it is not paid, this will reduce the customer's balance.
*/
public void delete() {
if ( ! po.getPaid())
getCustomer().updateBalance(getAmountTotal().negate());
po.getCustomer().getPurchaseorders().remove(po);
HibernateFactory.session.delete(po);
}
/**
* Internal method: get the underlying Hibernate bean.
*/
protected Purchaseorder getBean() { return po; }
/**
* Get this Purchaseorder's primary key.
*/
public Long getOrderNumber() { return po.getOrderNumber(); }
/**
* Get the total for this Purchaseorder, which is defined as the sum
* of all the Lineitems.
*/
public BigDecimal getAmountTotal() { return po.getAmountTotal(); }
/**
* Internal method: adjust the amountTotal by the given amount. If this Purchaseorder
* is not paid, this will affect the Customer's balance, with all expected ramifications.
* @param delta
*/
protected void updateAmountTotal(BigDecimal delta) {
po.setAmountTotal(po.getAmountTotal().add(delta));
if ( ! getPaid())
getCustomer().updateBalance(delta);
}
/**
* Whether this Purchaseorder is paid or not.
*/
public Boolean getPaid() { return po.getPaid(); }
/**
* Set the Paid attribute on this Purchaseorder. This will affect the Customer's balance,
* with the usual ramifications.
*/
public void setPaid(Boolean b) {
if (po.getPaid() && !b)
getCustomer().updateBalance(this.getAmountTotal());
else if (!getPaid() && b)
getCustomer().updateBalance(this.getAmountTotal().negate());
po.setPaid(b);
}
/**
* Notes for this order
*/
public String getNotes() { return po.getNotes(); }
public void setNotes(String notes) { po.setNotes(notes); }
/**
* Get the Customer who owns this Purchaseorder.
*/
public SCustomer getCustomer() { return new SCustomer(po.getCustomer()); }
/**
* Change the Customer who owns this Purchaseorder. If this Purchaseorder is not paid,
* this will decrease the old Customer's balance, and increase the new Customer's balance.
*/
public void setCustomer(SCustomer customer) {
// If it's the same customer, we're done
if (customer.getName().equals(this.getCustomer().getName()))
return;
if (!getPaid()) {
getCustomer().updateBalance(this.getAmountTotal().negate());
customer.updateBalance(this.getAmountTotal());
}
po.setCustomer(customer.getBean());
}
/**
* Get the Lineitems for this Purchaseorder as an unmodifiable collection.
*/
public Set<SLineitem> getLineitems() {
Set<SLineitem> result = new HashSet<SLineitem>();
for (Lineitem li : po.getLineitems())
result.add(new SLineitem(li));
return Collections.unmodifiableSet(result);
}
/**
* Add a Lineitem to this Purchaseorder. This will increase the totalAmount,
* which will in turn increase the Customer's balance if this Purchaseorder
* is not paid.
*/
public void addLineitem(SLineitem item) {
if ( ! po.getPaid())
getCustomer().updateBalance(this.getAmountTotal());
updateAmountTotal(item.getAmount());
po.getLineitems().add(item.getBean());
}
/**
* Remove a Lineitem from this Purchaseorder. This will decrease the totalAmount,
* which will in turn decrease the Customer's balance if this Purchaseorder
* is not paid.
*/
public void removeLineitem(SLineitem item) {
if ( ! po.getPaid())
getCustomer().updateBalance(this.getAmountTotal().negate());
updateAmountTotal(item.getAmount().negate());
po.getLineitems().remove(item.getBean());
}
}
<file_sep>BusLogicDemo
============
A simple JSP web app that demonstrate the use of ABL's transaction logic engine.<file_sep>package buslogicdemo.data.manual;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import buslogicdemo.util.HibernateFactory;
import buslogicdemo.data.*;
/**
* Business logic layer for the Customer class.
* This class is intended as a demonstration of implementing business "by hand", as opposed
* to using ABL's declarative business logic. As such, it is not a complete class -- it only contains
* those methods that are actually used by the demo application.
*/
public class SCustomer {
private Customer customer;
protected SCustomer(Customer cust) {
customer = cust;
}
/**
* Get the underlying Hibernate bean.
*/
protected Customer getBean() { return customer; }
/**
* Retrieve an instance by name.
* @param name The customer's primary key
* @return The customer service object
*/
public static SCustomer getByName(String name) {
Customer cust = (Customer)HibernateFactory.session.load(Customer.class, name);
SCustomer result = new SCustomer(cust);
return result;
}
/**
* Get all customers, ordered by name.
* @return An unmodifiable list of customer service objects.
*/
public static List<SCustomer> getAll() {
@SuppressWarnings("unchecked")
List<Customer> customers = HibernateFactory.session.createQuery("from Customer order by name").list();
List<SCustomer> result = new Vector<SCustomer>();
for (Customer c : customers) {
result.add(new SCustomer(c));
}
return Collections.unmodifiableList(result);
}
/**
* Persist any changes to this customer.
*/
public void save() {
HibernateFactory.session.saveOrUpdate(customer);
}
/**
* Get the customer's name
*/
public String getName() { return customer.getName(); }
/**
* Get the customer's credit limit.
*/
public BigDecimal getCreditLimit() { return customer.getCreditLimit(); }
/**
* Update the customer's credit limit. If the customer's balance is greater than
* this new credit limit, an exception will be thrown.
*/
public void setCreditLimit(BigDecimal cred) {
customer.setCreditLimit(cred);
checkCredit();
}
/**
* Get the customer's balance, which is calculated as the sum of the customer's
* unpaid Purchaseorders.
*/
public BigDecimal getBalance() { return customer.getBalance(); }
/**
* Internal method to change the value of the customer's balance and also check
* the credit limit. If the customer's new balance is greater than the credit limit,
* an exception will be thrown.
* @param delta The amount by which to adjust the balance - can be positive or negative.
*/
protected void updateBalance(BigDecimal delta) {
customer.setBalance(customer.getBalance().add(delta));
checkCredit();
}
/**
* Get the customer's purchase orders as an unmodifiable set of service objects.
*/
public Set<SPurchaseorder> getPurchaseorders() {
Set<SPurchaseorder> result = new HashSet<SPurchaseorder>();
for (Purchaseorder po : customer.getPurchaseorders())
result.add(new SPurchaseorder(po));
return Collections.unmodifiableSet(result);
}
/**
* Add a Purchaseorder to this customer. If the Purchaseorder is unpaid, this will
* adjust the customer's balance. If the new balance exceeds the credit limit, an
* exception will be thrown.
*/
public void addPurchaseorder(SPurchaseorder po) {
if ( ! po.getPaid())
updateBalance(po.getAmountTotal());
customer.getPurchaseorders().add(po.getBean());
}
/**
* Remove the given Purchaseorder from this customer. If the Purchaseorder is unpaid,
* this will adjust the customer's balance.
*/
public void removePurchaseorder(SPurchaseorder po) {
if ( ! po.getPaid())
updateBalance(po.getAmountTotal().negate());
customer.getPurchaseorders().remove(po.getBean());
}
/**
* Compare the customer's balance and credit limit; if the former is greater than
* the latter, throw an exception.
*/
private void checkCredit() {
if (customer.getBalance().doubleValue() > customer.getCreditLimit().doubleValue())
throw new RuntimeException("Constraint failed - balance > credit limit");
}
}
| 483034ab179a0655a75fb68fca4ac349bd145dd4 | [
"Markdown",
"Java"
] | 8 | Java | AutomatedBusinessLogic/BusLogicDemo | a64406c1465beffa00e643e27773244b778302c3 | f938879d5b4956c3f0c130dc7fb39978bdb7f37a |
refs/heads/master | <repo_name>jkilopu/Linux-Programming<file_sep>/terminal/listchars.c
/* listchars.c
* purpose: list individually all the chars seen on input
* output: char and ASCII code, one pair per line
* input: stdin, until the letter Q
* usage: ./listchar.c > log and type hello or ./listchars < listchars-test > log
* notes***: useful to show that buffer/editing exist
*
*/
#include <stdio.h>
int main(void)
{
int ch, n = 0;
while ((ch = getchar()) != 'Q') //if input is a document, != EOF
printf("char %3d is %c code %d\n", n++, ch, ch);
return 0;
}
/* result: see log
* 结论:
* 1. 键入时,输入被缓冲(按回车才刷新)
* 2. 回车的ASCII码应该是13,log中显示却是10
* */<file_sep>/commands/command_more/more02.c
/* more02.c - print the content of a file or information gradually
* usage: ./more02 filename or command | ./more02
* bugs: 1. we must press Enter after press q.
* what can be improved: 1. show pecentage of printed information
* 2.
*/
#include <stdio.h>
#include <stdlib.h>
#define PAGELEN 24
#define LINELEN 512
void do_more(FILE *fp);
int see_more(FILE *fp_tty);
int main(int argc, char *argv[])
{
char ch;
FILE *fp;
if (argc == 1) // if no argc, read from stdin for information and /dev/tty for commands, so that we can redirect
do_more(stdin);
else
while (--argc)
if ((fp = fopen(*++argv, "r")) != NULL) //read the file one by one
{
do_more(fp);
fclose(fp);
}
else
{
perror(*argv);
exit(EXIT_FAILURE);
}
return 0;
}
/*
* print the content of the file in lines
* */
void do_more(FILE *fp)
{
char line[LINELEN];
int num_of_lines = 0;
int reply;
FILE *fp_tty;
if ((fp_tty = fopen("/dev/tty", "r")) == NULL)
exit(EXIT_FAILURE);
while (fgets(line, LINELEN, fp)) // fgets() gets one line each time
{
if (num_of_lines == PAGELEN)
{
reply = see_more(fp_tty); //read command from tty
if (reply == 0)
break;
num_of_lines -= reply; // reset count
}
if (fputs(line, stdout) == EOF)
exit(EXIT_FAILURE);
num_of_lines++;
}
}
/*
* print message and wait for further command
* q means quit, space means yes, CR means one line
*/
int see_more(FILE *cmd)
{
int c;
printf("\033[7m more? \033[m");
while ((c = getc(cmd)) != EOF) //replace getchar() with getc() to read command
{
switch (c)
{
case ' ':
return PAGELEN;
case '\n':
return 1;
case 'q':
return 0;
default:
break;
}
}
}<file_sep>/process/sub_sort.c
/*
* sub_sort.c 输入文本(文件或键盘),储存在字符数组中,以行为单位排序(调用sort命令),再储存在字符数组中,输出到标准输出
* 知识点:pipe(in、out)、读入输入、write(已经搞错好多次了)
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <wait.h>
int main(int argc, char *argv[])
{
char buf[BUFSIZ];
/* 读入 */
if (argc == 2)
{
/* 从文件读入 */
int fd = open(argv[1], O_RDONLY);
if (fd == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
while (read(fd, buf, BUFSIZ) > 0)
;
}
else if (argc == 1)
{
/* 从标准输入读入 */
int i;
for (i = 0; i < BUFSIZ && (buf[i] = getchar()) != EOF; i++) // 似乎只能用这种方法
;
buf[i] = '\0';
}
else
{
perror("Wrong usage");
exit(EXIT_FAILURE);
}
/* 创建管道 */
int pipe_in[2], pipe_out[2];
if (pipe(pipe_in) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
if (pipe(pipe_out) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
/* fork */
pid_t new_pid;
if ((new_pid = fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
if (new_pid == 0)
{
close(pipe_in[0]);
close(pipe_out[1]);
/* 重定向 */
if (dup2(pipe_in[1], 1) == -1)
{
perror("dup2");
exit(EXIT_FAILURE);
}
close(pipe_in[1]);
if (dup2(pipe_out[0], 0) == -1)
{
perror("dup2");
exit(EXIT_FAILURE);
}
close(pipe_out[0]);
execlp("sort", "sort", NULL);
perror("execlp");
exit(EXIT_FAILURE);
}
else
{
close(pipe_in[1]);
close(pipe_out[0]);
/* 写入原始字符串 */
if (write(pipe_out[1], buf, strlen(buf)) != strlen(buf)) // write一定要写大小相当的呀!!!!!!!!
{
perror("write");
exit(EXIT_FAILURE);
}
close(pipe_out[1]);
wait(NULL);
/* 读取 */
while (read(pipe_in[0], buf, BUFSIZ) > 0)
;
close(pipe_in[0]);
/* 输出 */
printf("%s", buf);
}
return 0;
}<file_sep>/terminal/switch-echo.c
/* switch-echo.c - switch echo and non-echo mode */
#include <stdio.h>
#include <termio.h>
#include <stdlib.h>
int main(void)
{
char str[50];
int fd;
struct termios settings;
// get status
if (tcgetattr(0, &settings) == -1)
{
perror("tcgetattr");
exit(EXIT_FAILURE);
}
// examine and turn off echo
if (settings.c_lflag & ECHO) //检查用&与
settings.c_lflag &= ~ECHO; // 关闭用&(与)、~取反
if (tcsetattr(0, TCSANOW, &settings) == -1)
{
perror("tcgetattr");
exit(EXIT_FAILURE);
}
// test
fgets(str, 20, stdin);
fputs(str, stdout);
// turn on echo
settings.c_lflag |= ECHO; // 打开用|(或)
if (tcsetattr(0, TCSANOW, &settings) == -1)
{
perror("tcgetattr");
exit(EXIT_FAILURE);
}
// test
fgets(str, 20, stdin);
fputs(str, stdout);
return 0;
}<file_sep>/commands/command_ls/ls1.c
/* ls1.c
* purpose: list contents of directories
* action : use . else list files in args
* attention: 1. Although open, read can manipulate directory, but you have to figure out the kind of directory
* 2. readdir is not a systemcall
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
void do_ls(char dirname[]);
int main(int argc, char *argv[])
{
if (argc == 1)
do_ls(".");
else
while (--argc)
{
printf("%s:\n", *++argv);
do_ls(*argv);
}
return 0;
}
void do_ls(char dirname[])
/*
* list files in directory called dirname
*/
{
DIR *dir_ptr; /* rhe directory */
struct dirent *direntp; /* each entry */ //注意是指针啊!
if ((dir_ptr = opendir(dirname)) == NULL)
fprintf(stderr, "ls1: Can't open %s\n", dirname);
else
{
while ((direntp = readdir(dir_ptr)) != NULL)
printf("%s\n", direntp->d_name);
closedir(dir_ptr);
}
}<file_sep>/README.md
# Linux-Programming
There are implementations of some commands and homework in "Understanding Unix/Linux Programming" and "CSAPP"
---
## my_shell
A simple shell can only run commands with some arguments in PATH, version 0.2.
### Describtion
Accept a command, find a program in the path, and repeat the above work before receiving the exit command (and ignore the interrupt signal from the keyboard)
### Installation
``` bash
git clone https://github.com/jkilopu/Linux-Programming.git
cd ./Linux-Programming/process
gcc my_shell.c -o my_shell
./my_shell
```
try command like "ls -l" or "bc" etc.
### shortage
1. Do not support redirect.
2. Do not support pipe.
3. Do not support anything complex.
---
## mysnake&mymines
They are imitation of the classic games Mine and Snake.
I have moved them to other repos: [mymine](https://github.com/jkilopu/mymines), [mysnake](https://github.com/jkilopu/mysnake).
But their early version branches was left here.<file_sep>/Regular_expressiong/check_ip.c
/*
* check_ip.c
* 判断字符串是否符合ip地址规范(不考虑地址的范围)
*/
#include <regex.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char re[] = "^([0-9]{1,3}\.)([0-9]{1,3}\.){2}([0-9]{1,3})$";
char str[] = "192.168.3.11";
regex_t re_t;
/* 编译正则表达式 */
if (regcomp(&re_t, re, REG_EXTENDED | REG_NOSUB) != 0)
{
perror("regcomp");
exit(EXIT_FAILURE);
}
/* 匹配并判断*/
if (regexec(&re_t, str, 0, NULL, REG_NOSUB) == REG_NOMATCH) // 不需要传入nmatch和pmatch
printf("Not match\n");
else
printf("(%s) in format\n", str);
regfree(&re_t);
return 0;
}<file_sep>/commands/command_write/write02.c
/* write02.c -
* improvement: 1. support write through user name and each tty
* 2. add welcome message with date
* mistake: 1. fread()和read()均会自动偏移,我不知道...(没从write01中看出来)
* 2. fread()的返回值不是读取字节的大小,而是读取的个数
* 3. 判断条件总是搞来搞去,弄不清(或许在纸上画一下会好一些)
* 4. 括号打好啊!(=的优先级比==低!!!)
* 4. 很多时候还是没注意到细节啊!
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <utmp.h>
#include <time.h>
#define BUFSIZE 4096
void oops(char *s1, char *s2);
int main(int argc, char *argv[])
{
struct utmp info;
FILE *fp_utmp;
int fd_tty = 555;
int utsize = sizeof(struct utmp);
int is_found = 999; /* 记得初始化啊!!! */
char dev[16] = "/dev/", mesg[BUFSIZE];
// open utmp file
if ((fp_utmp = fopen(UTMP_FILE, "r")) == NULL)
oops("Can't open ", UTMP_FILE);
// check if command paraments are used correctly
if (argc != 2 && argc != 3)
{
fprintf(stderr, "usage: ./write02 user (terminal)\n");
exit(EXIT_FAILURE);
}
// find user
while ((fread(&info, utsize, 1, fp_utmp)) == 1) /* 这里必须先读*/
{
if (info.ut_type == USER_PROCESS && (is_found = strcmp(info.ut_user, argv[1])) == 0)
break;
/* 不要fseek()! */
}
// found the user?
if (is_found != 0)
{
fprintf(stderr, "%s is not logged in.\n", argv[1]);
exit(EXIT_FAILURE);
}
/* examine paraments */
if (argc == 2)
{
if ((fd_tty = open(strncat(dev, info.ut_line, 10), O_WRONLY) == -1))
{
perror(dev);
exit(EXIT_FAILURE);
}
}
else if (argc == 3)
{
// find terminal /* 这里必须先比较 */
while ((is_found = (strcmp(info.ut_line, argv[2]) != strcmp(info.ut_user, argv[1]))) != 0 && (fread(&info, utsize, 1, fp_utmp) == 1) || (info.ut_type != USER_PROCESS))
;
// found the terminal?
if (is_found == 0)
{
// open terminal
if (((fd_tty = open(strncat(dev, info.ut_line, 10), O_WRONLY)) == -1)) /* 括号写清楚阿啊啊啊啊啊啊啊啊啊啊!*/
oops("Can't open ", dev);
}
else
{
fprintf(stderr, "%s is not logged in on %s.\n", argv[1], argv[2]);
exit(EXIT_FAILURE);
}
}
// send messages
time_t send_time = time(NULL);
dprintf(fd_tty, "\nMessage from ... on ... at %s", ctime(&send_time)); /* welcome message*/
while (fgets(mesg, BUFSIZ, stdin) != NULL)
if (write(fd_tty, mesg, strlen(mesg)) == EOF)
break;
// close file
if (fclose(fp_utmp) == -1 || close(fd_tty) == -1)
oops("Can't close", "");
return 0;
}
// output the error intelligently
void oops(char *s1, char *s2)
{
fprintf(stderr, "Error: %s", s1);
perror(s2);
exit(EXIT_FAILURE);
}<file_sep>/commands/command_who/who01.c
/* who01.c -- basic implementation of who */
#include <stdio.h>
#include <stdlib.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#define SIZE 4096
void show_info(struct utmp *putmp);
char *transfer_time(int32_t timeval);
int main(void)
{
int fd, reclen = sizeof(struct utmp);
struct utmp information;
// 打开utmp文件
if ((fd = open(UTMP_FILE, O_RDONLY)) == -1)
{
perror(UTMP_FILE);
exit(EXIT_FAILURE);
}
// 读取、输出到屏幕
while (read(fd, &information, reclen) == reclen)
show_info(&information);
// 关闭文件
if (close(fd) == -1)
{
perror(UTMP_FILE);
exit(EXIT_FAILURE);
}
return 0;
}
void show_info(struct utmp *putmp)
{
if (putmp != NULL)
printf("%-10.10s %-10.10s %s", putmp->ut_user, putmp->ut_line, transfer_time(putmp->ut_time));
}
// 借助中间变量及升级,使ctime的参数类型符合
char *transfer_time(int32_t timeval)
{
time_t tmp = timeval;
return ctime(&tmp) + 4;
}<file_sep>/process/pipe.c
/* pipe管道测试 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <wait.h>
int main(void)
{
int fd_pipe[2];
pid_t new_pid;
char buf[BUFSIZ] = {0};
if(pipe(fd_pipe) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
if((new_pid = fork()) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
if(new_pid == 0)
{
close(fd_pipe[1]);
while(read(fd_pipe[0], buf, BUFSIZ) != 0)
printf("%s", buf);
}
else
{
close(fd_pipe[0]);
write(fd_pipe[1], "Hello, world!\n", 14);
wait(NULL);
}
return 0;
}<file_sep>/terminal/rotate.c
/* rotate.c: map a->b, b->ch, ... , z->a
* purpose: useful for showing tty modes
*/
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int ch;
while ((ch = getchar()) != EOF)
{
if (ch == 'z')
ch = 'a';
else if (islower(ch))
ch++;
putchar(ch);
}
return 0;
}<file_sep>/commands/command_more/more01.c
/* more01.c - print the content of a file gradually
* usage: ./more01 filename
* bugs: 1. we must press Enter after press q.
* 2. when use redirect(重定向), the see_more goes goes wrong,
* becaue we get "ch" from stdin instead of tty.
*/
#include <stdio.h>
#include <stdlib.h>
#define PAGELEN 24
#define LINELEN 512
void do_more(FILE *fp);
int see_more(void);
int main(int argc, char *argv[])
{
char ch;
FILE *fp;
if (argc == 1) // if no argc, read from stdin, so that we can redirect
do_more(stdin);
else
while (--argc)
if ((fp = fopen(*++argv, "r")) != NULL) //read the file one by one
{
do_more(fp);
fclose(fp);
}
else
{
perror(*argv);
exit(EXIT_FAILURE);
}
return 0;
}
/*
* read PAGELEN lines, then call see_more() for further instruction
*/
void do_more(FILE *fp)
{
char line[LINELEN];
int num_of_lines = 0;
int reply;
while (fgets(line, LINELEN, fp)) // fgets() gets one line each time
{
if (num_of_lines == PAGELEN)
{
reply = see_more();
if (reply == 0)
break;
num_of_lines -= reply; // reset count
}
if (fputs(line, stdout) == EOF)
exit(EXIT_FAILURE);
num_of_lines++;
}
}
/*
* print message and wait for further command
* q means quit, space means yes, CR means one line
*/
int see_more(void)
{
int ch;
printf("\033[7m more? \033[m"); /* reverse on a vt100 */ //no need '\n
while ((ch = getchar()) != EOF)
{
if (ch == ' ')
return PAGELEN;
if (ch == '\n')
return 1;
if (ch == 'q')
return 0;
}
}<file_sep>/terminal/test1.c
#include <stdio.h>
#define PRAISE "HHHHHHHHH"
int main()
{
char name[40];
scanf("%s", name);
printf("Hello, %s, %s", name, PRAISE);
return 0;
}<file_sep>/fopen/fopen-with-mode-a.c
/* fopen-with-mode-a.c
* utility: check if fopen uses O_APPEND
* result: text
* conclusion: yes, it uses O_APPEND
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *fp_1, *fp_2;
int i;
char mesg_1[] = "I am Isaac.\n";
char mesg_2[] = "This is Norman.\n";
// open file
if ((fp_1 = fopen("text", "a")) == NULL)
{
perror("text");
exit(EXIT_FAILURE);
}
if ((fp_2 = fopen("text", "a")) == NULL)
{
perror("text");
exit(EXIT_FAILURE);
}
// write string to file alternately(交替的)
for (i = 0; i < 3; i++)
{
if ((fwrite(mesg_1, strlen(mesg_1), 1, fp_1)) != 1) // the size writen(strlen(mesg_1)) needs to be exact.
{
perror(mesg_1);
exit(EXIT_FAILURE);
}
if ((fwrite(mesg_2, strlen(mesg_2), 1, fp_2)) != 1)
{
perror(mesg_2);
exit(EXIT_FAILURE);
}
}
// close file
fclose(fp_1);
fclose(fp_2);
return 0;
}<file_sep>/process/my_shell.c
/*
* my_shell.c --version 0.2
* 功能: 接受一条命令,并在PATH中寻找程序,在收到exit命令前重复上述工作(且能忽略键盘发出的中断信号)
*
* strsep()总结:
* 1. 传入的必须是指向字符串的指针char*,不能是数组名char[]。
* 2. 被分割数组会被修改(分隔符处被换为'\0'),而传入的指针会指向到分隔符的下一位
* 3. ***传二级指针的原因:要修改指针的指向,且要判断是否指向NULL
* 4. 注意分隔符可以有多个(分隔符连在一起的情况比较特殊)
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <signal.h>
#include <string.h>
#define MAX_LENGTH 20
void execute(char **argv);
char **to_argv(char src[], char seps[]);
int count_argv(char src[]);
int main(void)
{
char argbuf[MAX_LENGTH];
char **argv;
char seps[] = " ", exit_str[] = "exit\n";
/* 从标准输入读入字符串,并根据其判断是否退出*/
while (fgets(argbuf, MAX_LENGTH, stdin) && strcmp(argbuf, exit_str) != 0)
{
argbuf[strlen(argbuf) - 1] = '\0';
/* 转换为参数列表 */
argv = to_argv(argbuf, seps);
/* 执行程序 */
execute(argv);
}
return 0;
}
/* 执行参数列表中的程序(带命令行参数) */
void execute(char **argv)
{
pid_t new_pid;
int exit_status; // 子进程退出时的状态
new_pid = fork();
/* 根据pid判断子、父进程 */
switch (new_pid)
{
case -1:
perror("fork failed");
exit(EXIT_FAILURE);
break;
case 0:
execvp(argv[0], argv);
perror("execvp failed");
exit(EXIT_FAILURE);
default:
/* 忽略来自键盘的中断信号 */
signal(SIGINT, SIG_IGN);
/* 等待子进程并获取子进程信号 */
while (wait(&exit_status) != new_pid)
;
free(argv);
}
}
/* 分隔原始字符串并返回参数列表(最后需要free) */
char **to_argv(char src[], char seps[])
{
int i = 0, j = 0, num;
char **argv = NULL, *p = src;
/* 计算参数个数以便分配空间 */
num = count_argv(src);
argv = (char **)malloc((num + 1) * sizeof(char *));
/* 分解参数 */
for (j = 0; j < num; j++)
{
argv[j] = strsep(&p, seps); // 新知识:strsep的使用
// printf("%d %s\n", j, argv[j]);
}
argv[j] = NULL;
return argv;
}
/* 计算参数的个数 */
int count_argv(char src[])
{
int i = 0, cnt = 1;
while (src[i] != '\0')
if (src[i++] == ' ')
cnt++;
return cnt;
}<file_sep>/process/fork_and_write.c
/* 习题:父进程和子进程拥有相同的且指向位置的文件描述符,文件中会有几条记录? */
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(void)
{
int fd, pid;
char msg1[] = "Test 1 2 3 ..\n";
char msg2[] = "Hello, hello\n";
if((fd = creat("testfile", 0644)) == -1)
{
perror("create fail");
return 0;
}
if(write(fd, msg1, strlen(msg1)) == -1)
{
perror("write fail");
return 0;
}
if((pid = fork()) == -1)
{
perror("write fail");
return 0;
}
if(write(fd, msg2, strlen(msg2)) == -1)
{
perror("write fail");
return 0;
}
else
{
printf("%d\n", fd); // 看一看文件描述符是否相同
}
close(fd);
return 1;
}
/* 答案:三条。
* 因为父进程和子进程的文件描述符相同,任意一个进程write后偏移,另一个进程的write受前一个进程影响
*/<file_sep>/commands/command_who/who02.c
/* who02.c - who with buffered reads
* - surpresses empty records
* - formats time nicely
* - buffers input(using utmplib)
* - alternative: show host
* - attention: 尤其注意如何通过各个函数的返回值进行沟通
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#include <utmp.h>
#define SHOWHOST
int utmp_open(char *filename);
struct utmp *utmp_next(void);
int utmp_reload(void);
void utmp_close(void);
void show_info(struct utmp *putmp);
char *transfer_time(int32_t timeval);
int main(void)
{
struct utmp *utbufp; /* holds pointer to next rec */
if (utmp_open(UTMP_FILE) == -1)
{
perror(UTMP_FILE);
exit(EXIT_FAILURE);
}
while ((utbufp = utmp_next()) != ((struct utmp *)NULL))
show_info(utbufp);
utmp_close();
return 0;
}
// show_info没有更改
void show_info(struct utmp *putmp)
{
if (putmp != NULL)
{
// 只输出登陆的用户
if (putmp->ut_type == USER_PROCESS)
// 对齐,其中-10.10意思为左对齐,限制字符10个,不足10个补空格
printf("%-10.10s %-10.10s %s", putmp->ut_user, putmp->ut_line, transfer_time(putmp->ut_time));
}
}
// transfer_time没有更改
char* transfer_time(int32_t timeval)
{
time_t tmp = timeval;
return ctime(&tmp) + 4;
}<file_sep>/commands/command_who/utmplib.c
/* utmplib.c - functions to buffer reads from utmp file
*
* functions are
* utmp_open(filename) - open file
* returns -1 on error
* utmp_next() - return pointer to next struct
* return NULL on EOF
* utmp_close() - close file
*
* reads NRECS per read and then doles them out from the buffer
* 尤其注意如何通过各个函数的返回值进行沟通
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <utmp.h>
#define NRECS 16
#define NULLUT ((struct utmp *)NULL)
#define UTSIZE (sizeof(struct utmp))
// 使用静态全局变量的好处是,在主程序中函数的参数减少,封装更彻底
static char utmpbuf[NRECS * UTSIZE];
static int num_recs, cur_rec;
static int fd_utmp = -1;
int utmp_open(char *filename);
struct utmp *utmp_next(void);
static int utmp_reload(void);
void utmp_close(void);
// 五大过程,四大函数:打开、读入、指向、重填、关闭
int utmp_open(char *filename)
{
fd_utmp = open(filename, O_RDONLY);
cur_rec = num_recs = 0;
return fd_utmp;
}
struct utmp *utmp_next(void)
{
struct utmp *recp;
if (fd_utmp == -1)
return NULLUT;
/* 核心所在:
1. 缓冲区未满时什么也不做
2. 缓冲区满时,重新装填。若再无信息,则返回NULLUT,终止
*/
if (cur_rec == num_recs && utmp_reload() == 0)
return NULLUT;
recp = (struct utmp *)&utmpbuf[cur_rec * UTSIZE];
cur_rec++;
return recp;
}
static int utmp_reload(void)
{
int amt_read;
amt_read = read(fd_utmp, utmpbuf, NRECS * UTSIZE); // 读入的字节数
num_recs = amt_read / UTSIZE;
cur_rec = 0;
return num_recs;
}
void utmp_close(void)
{
if (fd_utmp != -1)
if (close(fd_utmp) == -1)
{
perror(UTMP_FILE);
exit(EXIT_FAILURE);
}
}<file_sep>/commands/command_write/write01.c
/* write0.c
*
* purpose: send messages to another terminal
* method: open the other terminal for output then
* copy from stdin to that terminal
* shows: a terminal is just a file supporting regular I/O
* usage: ./write0 ttyname(/dev/pts/NUMBER)
* 如果该终端的w权限关闭,必须用sudo
* 总结:(很重要)
* 1. 终端一般为tty,pts为虚拟终端。一个tty下可以有很多个pts(虚拟终端)
* 2. 要向一个终端发送信息,必须拥有该终端的w权限。(eg:默认tty的拥有者为root,zhongming没有tty的w权限,发送消息时显示permission denied)
* 3. 要在一个终端中收到消息,必须拥有该终端的r权限。(eg:默认tty的拥有者为root,zhongming没有tty的r权限,在该终端下登陆后无法收到消息)
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define BUFSIZE 4096
int main(int argc, char *argv[])
{
int fd;
char buf[BUFSIZE];
/* check args */
if (argc != 2)
{
fprintf(stderr, "usage: ./write0 ttyname\n");
exit(EXIT_FAILURE);
}
/* open device */
if ((fd = open(argv[1], O_WRONLY)) == -1)
{
perror(argv[1]);
exit(EXIT_FAILURE);
}
/* loop until EOF on input */
while (fgets(buf, BUFSIZE, stdin) != NULL)
if (write(fd, buf, strlen(buf)) == EOF)
break;
close(fd);
return 0;
}<file_sep>/Regular_expressiong/extract_substring.c
/*
* extract_substring.c
* 功能:取出源字符串中的第一个字串
* 缺陷:无法判断'.'连续的情况
*/
#include <regex.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void extract_substring(char *dest, const char src[], int start, int end);
int main(void)
{
char re[] = "([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_.-]+\.[a-zA-Z0-9])"; // 判断是否可能为一个e-mail
char str[] = "<EMAIL>"; // 源字符串
char e_mail[strlen(str) + 1], login_name[strlen(str) + 1], website_name[strlen(str) + 1]; // 储存各种属性
regex_t re_t;
const size_t nmatch = 3; // 比substr的个数多1
regmatch_t pmatch[3]; // 与nmatch保持一致
/* 编译 */
if (regcomp(&re_t, re, REG_EXTENDED) != 0)
{
perror("regcomp");
exit(EXIT_FAILURE);
}
/* 匹配、分配 */
if (regexec(&re_t, str, nmatch, pmatch, 0) == REG_NOMATCH)
{
perror("No match");
exit(EXIT_FAILURE);
}
else /* 拷贝至相应空间 */
{
extract_substring(e_mail, &str, pmatch[0].rm_so, pmatch[0].rm_eo);
extract_substring(login_name, &str, pmatch[1].rm_so, pmatch[1].rm_eo);
extract_substring(website_name, &str, pmatch[2].rm_so, pmatch[2].rm_eo);
}
/* 输出 */
printf("e-mail: %s, login_name: %s, website_name: %s\n", e_mail, login_name, website_name);
/* 记得free */
regfree(&re_t);
return 0;
}
void extract_substring(char *dest, const char *src, int start, int end)
{
strncpy(dest, &src[start], end - start); // 拷贝src中位置从[start,end)的元素
dest[end - start] = '\0'; // 必须手动添加'\0'
}<file_sep>/terminal/show_screen_size.c
/* show_screen_size.c - an application of ioctl.h
* purpose: show the size of screen in row and col or in pixel
* TIOCGWINSZ: 函数代码?
*/
#include <stdio.h>
#include <sys/ioctl.h>
void print_screen_dimensions(void);
int main(void)
{
print_screen_dimensions();
return 0;
}
void print_screen_dimensions(void)
{
struct winsize wbuf;
//长宽、像素
if (ioctl(0, TIOCGWINSZ, &wbuf) != -1) // 为啥填写0?
{
printf("%d rows x %d cols\n", wbuf.ws_row, wbuf.ws_col);
printf("%d wide x %d tall\n", wbuf.ws_xpixel, wbuf.ws_ypixel); // 为啥是0,0?
}
}<file_sep>/commands/command_cp/cp1.c
/* cp1.c - uses read and write with tunable buffer size
* usage: ./cp1 src dest
* attention: oops()
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFSIZE 4096
#define COPYMODE 0644
void oops(char *s1, char *s2);
int main(int argc, char *argv[])
{
int in_fd, out_fd;
int n_chars;
char buf[BUFSIZE];
// check if the format is right
if (argc != 3)
{
fprintf(stderr, "usage: ./cp1 sourcefile targetfile\n");
exit(EXIT_FAILURE);
}
// open input and output file
if ((in_fd = open(argv[1], O_RDONLY)) == -1)
oops("Can't open ", argv[1]);
// open output file with open() instead of creat() to solute many different situations and set mode.
if ((out_fd = open(argv[2], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
oops("Can't open ", argv[2]);
// write
while ((n_chars = read(in_fd, buf, BUFSIZE)) > 0) /* pay attention to the chars read */
if (write(out_fd, buf, n_chars) != n_chars)
oops("Write error to ", argv[2]);
// check if read is successful
if (n_chars == -1)
oops("Read error from ", argv[1]);
// close both file
if (close(in_fd) == -1 || close(out_fd) == -1)
{
fprintf(stderr, "Error closing files");
exit(EXIT_FAILURE);
}
return 0;
}
// output the error intelligently
void oops(char *s1, char *s2)
{
fprintf(stderr, "Error: %s", s1);
perror(s2);
exit(EXIT_FAILURE);
} | 4fea89cd2dd5dde42984c1a900e30bd1904439e3 | [
"Markdown",
"C"
] | 22 | C | jkilopu/Linux-Programming | 2ff16b3beb2ddc70342e6eeb18adfa7f80b012a4 | 04aaf9c9aa71d283bc7bb7a0576cdb1e621b38e9 |
refs/heads/master | <file_sep><?php
namespace SqsPhpBundle\Worker;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use SqsPhpBundle\Queue\Queue;
use Aws\Sqs\SqsClient;
class Worker implements ContainerAwareInterface {
use ContainerAwareTrait;
const SERVICE_NAME = 0;
const SERVICE_METHOD = 1;
private $sqs_client;
private $queue;
protected $max_retries = 2;
protected $retries = 0;
public function __construct(SqsClient $an_sqs_client) {
$this->sqs_client = $an_sqs_client;
}
//Short poll is the default behavior where a weighted random set of machines
// is sampled on a ReceiveMessage call. This means only the messages on the
// sampled machines are returned. If the number of messages in the queue
// is small (less than 1000), it is likely you will get fewer messages
// than you requested per ReceiveMessage call. If the number of messages
// in the queue is extremely small, you might not receive any messages in
// a particular ReceiveMessage response; in which case you should repeat the request.
//http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.Sqs.SqsClient.html#_receiveMessage
public function start(Queue $a_queue) {
$this->queue = $a_queue;
while ($this->retries <= $this->max_retries) {
$this->fetchMessage();
}
return;
}
private function fetchMessage() {
$result = $this->sqs_client->receiveMessage(array(
'QueueUrl' => $this->queue->url(),
));
if (!$result->hasKey('Messages')) {
sleep(1);
++$this->retries;
return;
}
$all_messages = $result->get('Messages');
foreach ($all_messages as $message) {
try {
$this->runWorker($message);
} catch (\Exception $e) {
echo $e;
continue;
}
// Delete message from queue if no error appeared
$this->deleteMessage($message['ReceiptHandle']);
}
}
private function runWorker($message) {
$callable = ($this->isService()) ? $this->getServiceCallable() : $this->queue->worker();
call_user_func(
$callable, $this->unserializeMessage($message['Body'])
);
}
private function isService() {
return $this->container->has(
$this->queue->worker()[self::SERVICE_NAME]
);
}
private function getServiceCallable() {
$service = $this->container->get(
$this->queue->worker()[self::SERVICE_NAME]
);
return array(
$service,
$this->queue->worker()[self::SERVICE_METHOD]
);
}
protected function unserializeMessage($a_message) {
return json_decode($a_message, true);
}
private function deleteMessage($a_message_receipt_handle) {
$this->sqs_client->deleteMessage(array(
'QueueUrl' => $this->queue->url(),
'ReceiptHandle' => $a_message_receipt_handle
));
}
}
| 47d1fc6162024f9b95a944d89f7de5a446a783c0 | [
"PHP"
] | 1 | PHP | slvrookie/sqs-php-bundle | f1e512a0999413155f5947af5cdc2c96349daf09 | c092e98394406f290e48e5e6816ae98c04aa745e |
refs/heads/master | <file_sep>// 计算出一个字符串共有多少个单词组成
function countWords (str) {
return str.split(" ").length;
}
console.log(countWords('Good morning, I love JavaScript.'));<file_sep>// 判断一个字符串是否为回文串
function palindrome(str){
resstr = str.split("").reverse().join("");
if (str === resstr) {
return true;
} else {
return false;
}
}
console.log(palindrome('hello'));
console.log(palindrome('abcba')); | 2f21a902b44768ae59309ffc59b4a2b648266b0d | [
"JavaScript"
] | 2 | JavaScript | CircleXiao/js-func | 46093cac0518f3c7e5dad1658a64db0bf7f8a960 | f6ffb3ac7b6aa8ef80873aacee143c86a87f349f |
refs/heads/main | <file_sep>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class ClasePrincipal {
public static void main(String[] args) {
try {
FileReader fr=new FileReader("T:\\ficheros\\notasAlumnos.csv");
BufferedReader br=new BufferedReader(fr);
String linea=br.readLine();
HashMap<String, ArrayList <Asignatura>> mapa_notas=new HashMap();
while(linea!=null)
{
String[] datos=linea.split(",");
String nombre=datos[0];
String asignatura=datos[1];
String nota=datos[2];
Asignatura a=new Asignatura(asignatura, Integer.parseInt(nota));
if(mapa_notas.containsKey(nombre))
{
mapa_notas.get(nombre).add(a);
}
else
{
ArrayList<Asignatura> lista=new ArrayList();
lista.add(a);
mapa_notas.put(nombre, lista);
}
linea=br.readLine();
}
System.out.println();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 475e98060ac281c619904986b726854239088aed | [
"Java"
] | 1 | Java | webfuhrer/RellenoHashMapAlumnos | 92eb9837f0d6372e8d75a3811389662c6f9a38e8 | 49ecf1317ef554beb9b6c3ccefb3bf1e3953bc90 |
refs/heads/master | <repo_name>MOTIV-Protocol/academy-ios-public<file_sep>/webapp/Extensions.swift
//
// Extensions.swift
// webapp
//
// Created by <NAME> on 2018. 7. 10..
// Copyright © 2018년 INSOMENIA. All rights reserved.
//
import UIKit
extension Array {
func partition(by chunkSize: Int) -> [[Element]] {
return stride(from: 0, to: self.count, by: chunkSize).map {
Array(self[$0..<Swift.min($0 + chunkSize, self.count)])
}
}
}
<file_sep>/webapp/BaseIcon.swift
import Foundation
import UIKit
import CoreText
import Dispatch
open class BaseIcon {
open static let instance = BaseIcon()
fileprivate var customFontLoaded = false
fileprivate let load_queue = DispatchQueue(label: "com.insomenia.font.load.queue", attributes: [])
fileprivate var fontsMap :[String: IconFont] = [:]
fileprivate init() {
}
open func addCustomFont(_ prefix: String, fontFileName: String, fontName: String, fontIconMap: [String: String]) {
fontsMap[prefix] = CustomIconFont(fontFileName: fontFileName, fontName: fontName, fontMap: fontIconMap)
}
open func loadAllAsync() {
self.load_queue.async(execute: {
self.loadAllSync()
})
}
open func loadAllSync() {
for font in fontsMap.values {
font.loadFontIfNecessary()
}
}
open func getNSMutableAttributedString(_ iconName: String, fontSize: CGFloat) -> NSMutableAttributedString? {
for fontPrefix in fontsMap.keys {
if iconName.hasPrefix(fontPrefix) {
let iconFont = fontsMap[fontPrefix]!
if let iconValue = iconFont.getIconValue(iconName) {
let iconUnicodeValue = iconValue.substring(to: iconValue.index(iconValue.startIndex, offsetBy: 1))
if let uiFont = iconFont.getUIFont(fontSize) {
let attrs = [NSAttributedStringKey.font : uiFont, NSAttributedStringKey.foregroundColor : UIColor.white]
return NSMutableAttributedString(string:iconUnicodeValue, attributes:attrs)
}
}
}
}
return nil
}
open func getUIImage(_ iconName: String, iconSize: CGFloat, iconColour: UIColor = UIColor.black, imageSize: CGSize) -> UIImage {
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.left
style.baseWritingDirection = NSWritingDirection.leftToRight
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0.0);
let attString = getNSMutableAttributedString(iconName, fontSize: iconSize)
if attString != nil {
attString?.addAttributes([NSAttributedStringKey.foregroundColor: iconColour, NSAttributedStringKey.paragraphStyle: style], range: NSMakeRange(0, attString!.length))
// get the target bounding rect in order to center the icon within the UIImage:
let ctx = NSStringDrawingContext()
let boundingRect = attString!.boundingRect(with: CGSize(width: iconSize, height: iconSize), options: NSStringDrawingOptions.usesDeviceMetrics, context: ctx)
attString!.draw(in: CGRect(x: (imageSize.width/2.0) - boundingRect.size.width/2.0, y: (imageSize.height/2.0) - boundingRect.size.height/2.0, width: imageSize.width, height: imageSize.height))
var iconImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// if(iconImage!.responds(to: #selector(UIImage.withRenderingMode(_:)(_:)))){
// iconImage = iconImage!.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
// }
return iconImage!
} else {
return UIImage()
}
}
}
private class CustomIconFont: IconFont {
fileprivate let fontFileName: String
fileprivate let fontName: String
fileprivate let fontMap: [String: String]
fileprivate var fontLoadedAttempted = false
fileprivate var fontLoadedSucceed = false
init(fontFileName: String, fontName: String, fontMap: [String: String]) {
self.fontFileName = fontFileName
self.fontName = fontName
self.fontMap = fontMap
}
func loadFontIfNecessary() {
if (!self.fontLoadedAttempted) {
self.fontLoadedAttempted = true
self.fontLoadedSucceed = loadFontFromFile(self.fontFileName, forClass: BaseIcon.self, isCustom: true)
}
}
func getUIFont(_ fontSize: CGFloat) -> UIFont? {
self.loadFontIfNecessary()
if (self.fontLoadedSucceed) {
return UIFont(name: self.fontName, size: fontSize)
} else {
return nil
}
}
func getIconValue(_ iconName: String) -> String? {
return self.fontMap[iconName]
}
}
private func loadFontFromFile(_ fontFileName: String, forClass: AnyClass, isCustom: Bool) -> Bool{
let bundle = Bundle(for: forClass)
var fontURL: URL?
_ = bundle.bundleIdentifier
fontURL = bundle.url(forResource: fontFileName, withExtension: "ttf")
if fontURL != nil {
let data = try! Data(contentsOf: fontURL!)
let provider = CGDataProvider(data: data as CFData)
let font = CGFont(provider!)
if (!CTFontManagerRegisterGraphicsFont(font!, nil)) {
NSLog("Failed to load font \(fontFileName)");
return false
} else {
return true
}
} else {
NSLog("Failed to load font \(fontFileName) because the file \(fontFileName) is not available");
return false
}
}
private protocol IconFont {
func loadFontIfNecessary()
func getUIFont(_ fontSize: CGFloat) -> UIFont?
func getIconValue(_ iconName: String) -> String?
}
<file_sep>/webapp/Utils.swift
//
// Utils.swift
// webapp
//
// Created by <NAME> on 2018. 7. 6..
// Copyright © 2018년 INSOMENIA. All rights reserved.
//
import UIKit
class Utils: NSObject {
static func openSettings() {
if let settingsUrl = URL(string:UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(settingsUrl)
}
}
static func setUserValue(_ key: String, _ value: String?) {
UserDefaults.standard.set(value, forKey: key)
}
static func getUserValue(_ key: String) -> String? {
return UserDefaults.standard.value(forKey: key) as? String
}
}
<file_sep>/webapp/ViewController.swift
import UIKit
import Firebase
import WebKit
import Foundation
import Alamofire
let REFRESH_TIMEOUT_THRESHOLD = 5
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
var webView: WKWebView!
var progressBar: UIProgressView!
let barColor = UIColor(string: "#3D0135")
var team_id: String? = nil
var shortLink: URL? = nil
private var background_start_date = Date()
override var preferredStatusBarStyle: UIStatusBarStyle {
if #available(iOS 13.0, *){
return .darkContent
}else{
return .default
}
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forName: .UIApplicationDidEnterBackground, object: nil, queue: nil) { [weak self] n in
self?.background_start_date = Date()
}
NotificationCenter.default.addObserver(forName: .UIApplicationWillEnterForeground, object: nil, queue: nil) { [weak self] n in
guard let backgroundStartDate = self?.background_start_date else { return }
let currentDate = Date()
let components: DateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: backgroundStartDate, to: currentDate)
if (components.minute! >= REFRESH_TIMEOUT_THRESHOLD){
self?.webView.load(URLRequest(url: URL(string: "\(Constant.baseURL)?platform=ios")!));
}
}
let config = WKWebViewConfiguration()
config.userContentController = {
$0.add(self, name: "callbackHandler")
$0.add(self, name: "registerSessionId")
return $0
}(WKUserContentController())
progressBar = UIProgressView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 3))
progressBar.backgroundColor = .black
progressBar.progressTintColor = .green
progressBar.trackTintColor = .black
self.view.addSubview(progressBar)
let menuHeight: CGFloat = 0
webView = WKWebView(frame: CGRect(x: 0, y: 20, width: self.view.frame.width, height: self.view.frame.height - menuHeight - 20), configuration: config)
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) //
print(" \(self.view.frame.width) \(self.view.frame.height)")
let urlRequest = URLRequest(url: URL(string: "\(Constant.baseURL)?platform=ios")!);
webView.navigationDelegate = self
webView.uiDelegate = self
webView.load(urlRequest);
webView.scrollView.bounces = false
webView.scrollView.backgroundColor = .white
self.view.addSubview(webView)
// let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
// if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) {
// statusBar.backgroundColor = UIColor.white
// }
}
func showToast(message : String) {
let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 200, height: 80))
toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastLabel.textColor = UIColor.white
toastLabel.textAlignment = .center;
toastLabel.font = UIFont(name: "Montserrat-Light", size: 9.0)
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
self.view.addSubview(toastLabel)
UIView.animate(withDuration: 4.0, delay: 0.5, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == "estimatedProgress") { // listen to changes and updated view
progressBar.isHidden = webView.estimatedProgress == 1
progressBar.setProgress(Float(webView.estimatedProgress), animated: true)
}
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name {
case "callbackHandler":
guard let userId = message.body as? String, let token = Utils.getUserValue("token") else { return }
Utils.setUserValue("userId", userId)
let url = "\(Constant.baseURL)/users/\(userId)/token?token=\(token)&device_type=ios&session_id=\(Utils.getUserValue("sessionId")!)"
DispatchQueue.global().async {
Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default).response { d in
}
}
case "registerSessionId":
guard let sessionId = message.body as? String else { return }
Utils.setUserValue("sessionId", sessionId)
default:
()
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard webView == self.webView else {
decisionHandler(.allow)
return
}
let app:UIApplication = UIApplication.shared
let url:URL = navigationAction.request.url!
print("webview open \(url)")
if (url.scheme != "http" && url.scheme != "https" && url.scheme != "about" && url.scheme != "javascript") {
print("webview open scheme \(String(describing: url.scheme))")
app.openURL(url)
decisionHandler(.cancel)
return
} else if url.host == "itunes.apple.com" {
print("url is itunes")
app.openURL(url)
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil {
webView.load(navigationAction.request)
}
return nil
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String,
initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let alertController = UIAlertController(title: message, message: nil,
preferredStyle: UIAlertControllerStyle.alert);
alertController.addAction(UIAlertAction(title: "확인", style: UIAlertActionStyle.cancel) {
_ in completionHandler()}
);
self.present(alertController, animated: true, completion: {});
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "네", style: .default, handler: { (action) in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: "아니오", style: .default, handler: { (action) in
completionHandler(false)
}))
present(alertController, animated: true) {
}
}
override var prefersStatusBarHidden : Bool {
return false
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(code: Int) {
self.init(red:(code >> 16) & 0xff, green:(code >> 8) & 0xff, blue:code & 0xff)
}
convenience init(string: String) {
let hex = string.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (1, 1, 1, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
<file_sep>/webapp/VideoController.swift
import UIKit
import Foundation
class VideoController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let imageView = UIImageView.init(image: UIImage)
// self.view.addSubview()
}
}
<file_sep>/webapp/webapp-Bridging-Header.h
//
// webapp-Bridging-Header.h
// webapp
//
// Created by james on 2016. 4. 28..
// Copyright © 2016년 INSOMENIA. All rights reserved.
//
#ifndef webapp_Bridging_Header_h
#define webapp_Bridging_Header_h
#endif /* webapp_Bridging_Header_h */
<file_sep>/Podfile
use_frameworks!
target 'webapp' do
pod 'Firebase/Core', '5.3'
pod 'Firebase/Messaging'
pod 'Alamofire', '~> 4.7'
end
<file_sep>/webapp/Constant.swift
//
// Constant.swift
// webapp
//
// Created by <NAME> on 2018. 7. 6..
// Copyright © 2018년 INSOMENIA. All rights reserved.
//
import UIKit
class Constant: NSObject {
static let baseURL = "https://"
}
enum UBEESErrors: Error {
case DeviceDisconnected, DeviceTooCloset, CannotFoundDevice, AnotherUserDevice, UnknownError
}
| 45175723ea43d51a5717bf97da71b1fb06889efd | [
"Swift",
"C",
"Ruby"
] | 8 | Swift | MOTIV-Protocol/academy-ios-public | d29d9dfb2d5b3e2dc990da67c1d2e8a66c3f3bea | 8c7612e7322e398ff81426e70714f638ef1e1ea4 |
refs/heads/master | <file_sep># geo-app
Homework #3 (Geo App)
<file_sep>//
// SettingsViewController.swift
// Geo-App
//
// Created by <NAME> on 5/18/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var distanceUnitsLbl: UILabel!
@IBOutlet weak var bearingUnitsLbl: UILabel!
@IBOutlet weak var bearingSettingPicker: UIPickerView!
@IBOutlet weak var distanceSettingPicker: UIPickerView!
var distances = ["Kilometers", "Miles"]
var bearings = ["Degrees", "Mils"]
override func viewDidLoad() {
super.viewDidLoad()
distanceSettingPicker.delegate = self
distanceSettingPicker.dataSource = self
bearingSettingPicker.delegate = self
bearingSettingPicker.dataSource = self
let tapDistance = UITapGestureRecognizer(target: self, action: #selector(SettingsViewController.distanceClick))
distanceUnitsLbl.isUserInteractionEnabled = true
distanceUnitsLbl.addGestureRecognizer(tapDistance)
let tapBearing = UITapGestureRecognizer(target: self, action: #selector(SettingsViewController.bearingClick))
bearingUnitsLbl.isUserInteractionEnabled = true
bearingUnitsLbl.addGestureRecognizer(tapBearing)
bearingSettingPicker.isHidden = true
distanceSettingPicker.isHidden = true
}
func distanceClick(sender:UITapGestureRecognizer) {
distanceSettingPicker.isHidden = false
bearingSettingPicker.isHidden = true
}
func bearingClick(sender:UITapGestureRecognizer) {
distanceSettingPicker.isHidden = true
bearingSettingPicker.isHidden = false
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if (pickerView == distanceSettingPicker) {
return distances[row]
} else {
return bearings[row]
}
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (pickerView == distanceSettingPicker) {
distanceUnitsLbl.text = distances[row]
distanceSettingPicker.isHidden = true
} else {
bearingUnitsLbl.text = bearings[row]
bearingSettingPicker.isHidden = true
}
}
@IBAction func saveBtnClicked(_ sender: Any) {
//TODO This should persist the updated settings to the other view
}
}
<file_sep>//
// ViewController.swift
// Geo-App
//
// Created by <NAME> on 5/17/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var distanceText: UILabel!
@IBOutlet weak var bearingText: UILabel!
@IBOutlet weak var latitudeP1: UITextField!
@IBOutlet weak var longitudeP1: UITextField!
@IBOutlet weak var latitudeP2: UITextField!
@IBOutlet weak var longitudeP2: UITextField!
var distancePkrViewData = ["Kilometers", "Meters"]
var bearingPkrViewData = ["Degrees", "Mils"]
override func viewDidLoad() {
super.viewDidLoad()
// Dismiss keyboard when tapping outside oftext fields
let detectTouch = UITapGestureRecognizer(target: self, action:
#selector(self.dismissKeyboard))
self.view.addGestureRecognizer(detectTouch)
}
func dismissKeyboard() {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func clearAction(_ sender: UIButton) {
latitudeP1.text = ""
longitudeP1.text = ""
latitudeP2.text = ""
longitudeP2.text = ""
distanceText.text = "Distance:"
bearingText.text = "Bearing:"
}
@IBAction func calculateAction(_ sender: UIButton) {
let la1 = Double(latitudeP1.text!) ?? 0
let la2 = Double(latitudeP2.text!) ?? 0
let lo1 = Double(longitudeP1.text!) ?? 0
let lo2 = Double(longitudeP2.text!) ?? 0
let distance = haversineDinstance(la1: la1, lo1: lo1, la2:la2, lo2: lo2) / 1000
let bearing = getBearing(la1: la1, lo1: lo1, la2:la2, lo2: lo2)
let divisor = pow(10.0, Double(2))
let roundedDistance = (distance * divisor).rounded() / divisor
let roundedBearing = (bearing * divisor).rounded() / divisor
distanceText.text = "Distance: \(roundedDistance) kilometers."
bearingText.text = "Bearing: \(roundedBearing) degrees."
}
func haversineDinstance(la1: Double, lo1: Double, la2: Double, lo2: Double, radius: Double = 6367444.7) -> Double {
let haversin = { (angle: Double) -> Double in
return (1 - cos(angle))/2
}
let ahaversin = { (angle: Double) -> Double in
return 2*asin(sqrt(angle))
}
// Converts from degrees to radians
let dToR = { (angle: Double) -> Double in
return (angle / 360) * 2 * Double.pi
}
let lat1 = dToR(la1)
let lon1 = dToR(lo1)
let lat2 = dToR(la2)
let lon2 = dToR(lo2)
return radius * ahaversin(haversin(lat2 - lat1) + cos(lat1) * cos(lat2) * haversin(lon2 - lon1))
}
func radians(n: Double) -> Double{
return n * (Double.pi / 180);
}
func degrees(n: Double) -> Double{
return n * (180 / Double.pi);
}
func logC(val:Double,forBase base:Double) -> Double {
return log(val)/log(base);
}
func getBearing(la1: Double, lo1:Double, la2: Double, lo2: Double) -> Double{
var s_LAT: Double , s_LON: Double, e_LAT: Double, e_LON: Double, d_LONG: Double, d_PHI: Double;
s_LAT = la1;
s_LON = lo1;
e_LAT = la2;
e_LON = lo2;
d_LONG = e_LON - s_LON;
d_PHI = logC(val: tan(e_LAT/2.0+Double.pi/4.0)/tan(s_LAT/2.0+Double.pi/4.0),forBase :M_E);
if (abs(d_LONG) > Double.pi){
if(d_LONG>0.0){ d_LONG = -(2.0 * Double.pi - d_LONG); }
else { d_LONG = (2.0 * Double.pi - d_LONG); }
}
return degrees(n: atan2(d_LONG, d_PHI)+360.0).truncatingRemainder(dividingBy: 360.0);
}
}
| 3deeaea2cbcf66e655325b7769f4a87d9fd2b2b3 | [
"Markdown",
"Swift"
] | 3 | Markdown | newelld416/geo-app | e7024855b057e774a0ba4d8650098ddf2289da8b | b25a31acf7d2f9a5bc9a2d37f659541bd1be45f0 |
refs/heads/master | <file_sep># MerkleMint
A solution to minting non-fungible tokens for items in a) huge data sets or b) data sets with huge items.
Sorry I haven't made a good readme yet. The tests are pretty self explanatory though.
<file_sep>import { keccak256, bufferToHex } from "ethereumjs-util";
import { MerkleTree } from "./merkleTree";
export class MerkleMint {
private _elements: any;
public tree: any;
constructor(elements: string[]) {
this._elements = elements
this.tree = new MerkleTree(elements)
}
getTree() {
return this.tree
}
getElements() {
return this._elements
}
getElement(x: any) {
return this._elements[x]
}
getTotalElements() {
return this._elements.length
}
getRoot() {
return this.tree.getHexRoot()
}
getProofByIndex(index: any) {
if (index > this._elements.length) {
throw new Error("Index out of bounds for Elements")
}
return this.tree.getHexProof(this._elements[index])
}
getProof(el: any) {
if (this._elements.includes(el)) return this.tree.getHexProof(el)
}
getLeafByIndex(index: any) {
if (index > this._elements.length) {
throw new Error("Index out of bounds for Elements")
}
return bufferToHex(keccak256(this._elements[index]))
}
getLeaf(el: any) {
if (!this._elements.includes(el)) {
throw new Error("Element not found in tree")
}
return bufferToHex(keccak256(el))
}
keccak256(item: any) {
return keccak256(item)
}
bufferToHex(x: any) {
return bufferToHex(x)
}
}
<file_sep>import { expect } from "chai";
import { Signer } from "@ethersproject/abstract-signer";
import { ethers } from "hardhat";
import { MerkleMintCore } from "../../typechain/MerkleMintCore";
export function MerkleMintCoreBehavior(token: MerkleMintCore, TokenName: string, TokenSymbol: string): void{
it("Should deploy a MerkleMintCore", async function () {
expect(await token.name()).to.equal(TokenName);
});
it("Should mint a token with uri data", async function () {
const signers: Signer[] = await ethers.getSigners();
const tokenURI = "First Token";
expect(await token.mint((await signers[0].getAddress()), tokenURI)).to.emit(token, "Transfer");
expect(await token.tokenURI(0)).to.be.equal(tokenURI);
})
};
<file_sep>import { expect } from "chai";
import { Signer } from "@ethersproject/abstract-signer";
import { ethers, waffle } from "hardhat";
import { utils } from "ethers";
const { deployContract } = waffle;
import { MerkleMintCore } from "../typechain/MerkleMintCore";
import { MerkleMintController } from "../typechain/MerkleMintController";
import MerkleMintCoreArtifact from "../artifacts/contracts/MerkleMintCore.sol/MerkleMintCore.json";
import MMControllerArtifact from "../artifacts/contracts/MerkleMintController.sol/MerkleMintController.json";
import { MerkleMint } from "./utils/index";
// const constants = {
// ZERO_ADDRESS: "0x0000000000000000000000000000000000000000",
// ZERO_BYTES32: "0x0000000000000000000000000000000000000000000000000000000000000000",
// MAX_UINT256: ethers.BigNumber.from("2").pow(ethers.BigNumber.from("256")).sub(ethers.BigNumber.from("1")),
// MAX_INT256: ethers.BigNumber.from("2").pow(ethers.BigNumber.from("255")).sub(ethers.BigNumber.from("1")),
// MIN_INT256: ethers.BigNumber.from("2").pow(ethers.BigNumber.from("255")).mul(ethers.BigNumber.from("-1")),
// };
describe("MerkleMintCore", function () {
let token: MerkleMintCore;
let mmController: MerkleMintController;
let signers: Signer[];
const TokenName = "TestToken";
const TokenSymbol = "TT";
// Elements for merkle tree
const elements = ["love", "anger", "hunger", "shibe"]
// TODO: Add Types too Merkle Helper
// Create merkletree
const merkleMint = new MerkleMint(elements)
// Series data
const series = 0;
const seriesName = "First Series";
const ipfsHash = merkleMint.keccak256(seriesName);
before(async function () {
// Get Role
const minterRole = utils.keccak256(utils.toUtf8Bytes("MINTER_ROLE"))
// Get signers
signers = await ethers.getSigners();
// Array of Permissioned Addresses
const users = [(await signers[0].getAddress())];
// Deploy Token
token = await deployContract(signers[0], MerkleMintCoreArtifact, [TokenName, TokenSymbol, users]) as MerkleMintCore;
// Deploy mmController
mmController = await deployContract(signers[0], MMControllerArtifact, [token.address, users, users]) as MerkleMintController;
// Give mmController permissions on Token
await token.grantRole(minterRole, mmController.address);
});
describe("TokenCore", async function () {
it("Should deploy a Token", async function () {
expect(await token.name()).to.equal(TokenName);
});
it("Should mint a token with uri data", async function () {
const signers: Signer[] = await ethers.getSigners();
const tokenURI = "First Token";
expect(await token.mint((await signers[0].getAddress()), tokenURI)).to.emit(token, "Transfer");
expect(await token.tokenURI(0)).to.be.equal(tokenURI);
})
})
describe("MerkleMint", async function () {
it("Should add a series", async function () {
await expect(mmController.addSerie(merkleMint.getRoot(),
seriesName,
ipfsHash,
merkleMint.getTotalElements())).to.emit(mmController, "SerieAdded");
})
it("Should mint a merkleMint token", async function () {
const recepient = await signers[0].getAddress();
const leaf = merkleMint.getLeafByIndex(0);
const proof = merkleMint.getProofByIndex(0);
const tokenURI = merkleMint.getElement(0);
// const tokenURI
await expect(mmController.mintAsset(
recepient,
tokenURI,
leaf,
proof,
series
)).to.emit(mmController, "MerkleMinted");
})
})
it("can add additional metadata", async () => {
const newHash = merkleMint.keccak256("The second Metadata");
await expect(mmController.addIpfsRefToSerie(newHash, series)).to.emit(mmController, "MetadataAdded")
})
});
<file_sep>const {MerkleTree} = require('./merkleTree')
const {keccak256, bufferToHex} = require('ethereumjs-util')
const elements = ['love', 'happiness', 'ethereum']
const merkleTree = new MerkleTree(elements)
const root = merkleTree.getHexRoot()
const numElements = elements.length;
const proof = merkleTree.getHexProof(elements[0])
const leaf = bufferToHex(keccak256(elements[0]))
const validWord = 'love'
module.exports = {
validWord,
root,
leaf,
proof,
numElements
}
| bf45e8f7a6355473c719c734b025156c216fbbeb | [
"Markdown",
"TypeScript"
] | 5 | Markdown | crazyrabbitLTC/MerkleMint | eb4dcfd333bec677fec6d7e6a8b2c4e6571db956 | 32bfe8c73a9dc304784ada69ebea61c45b5a90d8 |
refs/heads/master | <repo_name>CrisRuedaP/AirBnB_clone_v3<file_sep>/api/v1/app.py
#!/usr/bin/python3
"""
app file for the api
"""
from os import getenv
from flask import Flask, jsonify
from flask import Blueprint
from models import storage
from api.v1.views import app_views
from flask_cors import CORS
app = Flask(__name__)
app.register_blueprint(app_views)
cors = CORS(app, resources={r"/*": {"origins": "0.0.0.0"}})
app.config['CORS_HEADERS'] = 'Content-Type'
@app.teardown_appcontext
def teardown_appcontext(self):
storage.close()
@app.errorhandler(404)
def not_found(error):
"""Returns a JSON-formatted 404 status code response"""
return jsonify({'error': 'Not found'}), 404
if __name__ == "__main__":
"""Docstring"""
HBNB_API_HOST = getenv('HBNB_API_HOST', '0.0.0.0')
HBNB_API_PORT = getenv('HBNB_API_PORT', '5000')
app.run(host=HBNB_API_HOST,
port=HBNB_API_PORT,
threaded=True, debug=True)
| 0b5ac76120090af351cf02c6eb71a295df33e9ac | [
"Python"
] | 1 | Python | CrisRuedaP/AirBnB_clone_v3 | ce8e174183d902b86ee0ae8aca7b0a93c8fcd783 | d047972898f98db089469ff701317c6c9c0f750a |
refs/heads/master | <repo_name>UlisesCabrera/UlisesCabrera.github.io<file_sep>/public/src/js/app.js
angular.module('2016-Portfolio',['HomePageModule', 'ngRoute','FullStackModule','FrontEndModule','AboutMeModule','MicroserviceModule'])
.config(function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl:'./partials/fullstack.html',
controller: 'FullStackController'
})
.when('/frontEnd', {
templateUrl:'./partials/frontEnd.html',
controller: 'FrontEndController'
})
.when('/microservice', {
templateUrl:'./partials/microservice.html',
controller: 'MicroserviceController'
})
.when('/aboutMe', {
templateUrl:'./partials/aboutMe.html',
controller: 'AboutMeController'
})
.otherwise({
redirectTo: "/"
});
});<file_sep>/public/src/js/fullStack/services/fullStack.service.js
/*global angular*/
angular.module("FullStackModule")
.factory('fullStackFactory',[function() {
var projectsFactory = {
projects :[
{
name: "Pinterest Clone",
description:"It’s Pinterest clone app, built with the MEAN stack. It let you login with your Twitter account, link images to the app and see a Pinterest-style wall of all the images (with masonry.js). It also detects if an image is broken and gets replaced by a placeholder image.",
image: {"background-image" : "url(' images/fullStackProjects/pinterest-clone-app-project.jpg')"},
source: 'https://github.com/UlisesCabrera/pinterest-clone-fcc',
live: 'https://pin-yours.herokuapp.com/',
userStories:[
'As an unauthenticated user, I can login with Twitter.',
'As an authenticated user, I can link to images.',
'As an authenticated user, I can delete images that I\'ve linked to.',
'As an authenticated user, I can see a Pinterest-style wall of all the images I\'ve linked to.',
'As an unauthenticated user, I can browse other users\' walls of images.',
'As an authenticated user, if I upload an image that is broken, it will be replaced by a placeholder image.'
],
school: 'freeCodeCamp',
date: 'April 2016'
},
{
name: "Manage a Book Trading App",
description:"It's an app that allows you to catalogue your books online (just the image and name, not the actual book since it's not a real app), see all of the books the users own, request to borrow other users'books and easily manage books and request from your dashboard. Built with the MEAN Stack using passport.js to support user authentication.",
image: {"background-image" : "url(' images/fullStackProjects/book-trading-app-project.jpg')"},
source: 'https://github.com/UlisesCabrera/book-trading-club',
live: 'https://book-trading-clb.herokuapp.com/',
userStories:['I can update my settings to store my full name, city, and state.',
'I can view all books posted by every user.',
'I can add a new book.',
'I can propose a trade and wait for the other user to accept the trade.'],
school: 'freeCodeCamp',
date: 'April 2016'
},
{
name: "Chart the Stock Market App",
description:"It's an app built to track market stocks, it uses socket.io to sync all clients connected built with the MEAN stack. It lets the user add, remove and update stocks from the chart, any changes to the chart is view on every client connected. The data is coming from the Quandl financial API and the chart is built with the highchart library.",
image: {"background-image" : "url(' images/fullStackProjects/stock-watcher-project.jpg')"},
source: 'https://github.com/UlisesCabrera/the-stock-market-charts',
live: 'https://stock-w.herokuapp.com',
userStories:['I can view a graph displaying the recent trend lines for each added stock.',
'I can add new stocks by their symbol name.',
'I can remove stocks.',
'I can see changes in real-time when any other user adds or removes a stock.'],
school: 'freeCodeCamp',
date: 'February 2016'
},
{
name: "Nightlife Coordination App",
description: "It's an app to help users find the local bars using their current location or by searching on the map, it lets them add themselves to a list of 'People going' and they can also remove themselves from the list. Keeping track of how many people are going to each bar will help the users decide where they want to go tonight. The app was built with the MEAN stack with the combination of the Yelp API to get the all the info for the local bars and using Google maps to display the location of each bar.",
image: {"background-image" : "url(' images/fullStackProjects/night-life-coord-project.jpg')"},
source: 'https://github.com/UlisesCabrera/nightlife-coordinator',
live: 'https://d-night-life.herokuapp.com/',
userStories:['As an unauthenticated user, I can view all bars in my area.',
'As an authenticated user, I can add myself to a bar to indicate I am going there tonight.',
'As an authenticated user, I can remove myself from a bar if I no longer want to go there.',
'As an unauthenticated user, when I login I should not have to search again.'],
school: 'freeCodeCamp',
date: 'February 2016'
},
{
name: "Voting App",
description: "A dynamic app made with the MEAN (MongoDB, Express, Angular and Node) stack, using passport.js to handle the authentication process with local and social media accounts (Facebook, LinkedIn, Google+, Twitter and GitHub). Mongoose was used to abstract the methods that interact with the MongoDB database and create schemas for the documents. Each poll created can be shared to Facebook, Twitter and Google+ and the results are presented using Chart.js.",
image: {"background-image" : "url(' images/fullStackProjects/poll-app-project.jpg')"},
source: 'https://github.com/UlisesCabrera/voting-app',
live: 'https://poll-sation.herokuapp.com/',
userStories:['As an authenticated user, I can keep my polls and come back later to access them.',
'As an authenticated user, I can share my polls with my friends.',
'As an authenticated user, I can see the aggregate results of my polls.',
'As an authenticated user, I can delete polls that I decide I don\'t want anymore.',
'As an authenticated user, I can create a poll with any number of possible items.',
'As an unauthenticated or authenticated user, I can see and vote on everyone\'s polls.',
'As an unauthenticated or authenticated user, I can see the results of polls in chart form. (This could be implemented using Chart.js or Google Charts.)',
'As an authenticated user, if I don\'t like the options on a poll, I can create a new option.'],
school: 'freeCodeCamp',
date: 'December 2015'
}
]};
return projectsFactory;
}]);<file_sep>/README.md
### <NAME> - 2016 Portfolio
## www.ulisescabrera.com<file_sep>/public/src/js/homePage/controllers/homePage.controller.js
angular.module("HomePageModule")
.controller("HomePageController",["$scope", "$location", function($scope, $location){
// determine current location
$scope.current = function() {
var location;
switch ($location.path()) {
case '/':
location = 'fullStack';
break;
case '/frontEnd':
location = 'frontEnd';
break;
case '/post':
location = 'post';
break;
case '/microservice':
location = 'microservice';
break;
case '/aboutMe':
location = 'aboutMe';
break;
default:
location = 'fullStack';
}
return location;
};
}]);<file_sep>/public/src/js/fullStack/controllers/fullStack.controller.js
angular.module("FullStackModule")
.controller("FullStackController",["$scope",'fullStackFactory', function($scope, fullStackFactory){
// getting projects from the factory
$scope.projects = fullStackFactory.projects;
}]);<file_sep>/public/src/js/microservice/microservice.module.js
angular.module("MicroserviceModule",[]);<file_sep>/public/src/js/frontEnd/frontEnd.module.js
angular.module("FrontEndModule",[]);<file_sep>/server.js
var path = require('path');
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, 'public/')));
app.get('/src', function(req,res,next){
res.sendFile(path.join(__dirname,'public/src/index.html'));
});
app.get('/dist', function(req,res,next){
res.sendFile(path.join(__dirname,'public/dist/index.html'));
});
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log('listening');
});<file_sep>/public/src/js/microservice/services/microservice.service.js
angular.module("MicroserviceModule")
.factory('microserviceFactory',[function() {
var projectsFactory = {
projects :[
{
name: "Timestamp",
description: "A microservice where the user can pass a string as a parameter, and it will check to see whether that string contains either a unix timestamp or a natural language date (example: January 1, 2016). And if it does, it returns both the Unix timestamp and the natural language form of that date. If it does not contain a date or Unix timestamp, it returns null for those properties.",
image: {"background" : "linear-gradient(rgba(0, 0, 0, 0.45), rgba(255,110,64, 0.45)), url(' images/microservices/timestamp-ms.jpg') no-repeat"},
source: 'https://github.com/UlisesCabrera/timestamp-ms-uc',
live: 'https://timestamp-ms-uc.herokuapp.com/',
userStories:[],
school: 'freeCodeCamp',
date: 'January 2016'
},
{
name: "Request Header Parser",
description: "A microservice where the user can get the their IP address, language and operating system information",
image: {"background" : "linear-gradient(rgba(0, 0, 0, 0.45), rgba(255,110,64, 0.45)), url(' images/microservices/request-header-parser-ms.jpg') no-repeat"},
source: 'https://github.com/UlisesCabrera/request-header-parser-ms',
live: 'https://request-header-parser-uc-ms.herokuapp.com/',
userStories:[],
school: 'freeCodeCamp',
date: 'January 2016'
},
{
name: "URL Shortener Microservice",
description: "A microservice where the user can pass a URL as a parameter and it will receive a shortened URL in the JSON response, If it pass an invalid URL that doesn't follow the valid http://www.example.com format, the JSON response will contain an error instead. And when the user visits that shortened URL, it will redirect it to the original link.",
image: {"background" : "linear-gradient(rgba(0, 0, 0, 0.45), rgba(255,110,64, 0.45)), url(' images/microservices/url-shortener-ms.jpg') no-repeat"},
source: 'https://github.com/UlisesCabrera/URL-Shortener-Microservice',
live: 'https://url-sh.herokuapp.com/',
userStories:[],
school: 'freeCodeCamp',
date: 'January 2016'
},
{
name: "Image Search Abstraction Layer",
description: "A microservice where the user can get the image URLs, alt text and page urls for a set of images relating to a given search string, It can also paginate through the responses by adding a ?offset=2 parameter to the URL and can get a list of the most recently submitted search strings.",
image: {"background" : "linear-gradient(rgba(0, 0, 0, 0.45), rgba(255,110,64, 0.45)), url(' images/microservices/image-search-abstraction-layer-ms.jpg') no-repeat"},
source: 'https://github.com/UlisesCabrera/Image-Search-Abstraction-Layer',
live: 'https://img-search-layer.herokuapp.com/',
userStories:[],
school: 'freeCodeCamp',
date: 'January 2016'
},
{
name: "File Metadata",
description: "A microservice where the users can submit a FormData object that includes a file upload and when they submit something, it will receive the file size in bytes.",
image: {"background" : "linear-gradient(rgba(0, 0, 0, 0.45), rgba(255,110,64, 0.45)), url(' images/microservices/file-metadata-ms.jpg') no-repeat"},
source: 'https://github.com/UlisesCabrera/File-Metadata-Microservice',
live: 'https://file-metadata-ms.herokuapp.com/',
userStories:[],
school: 'freeCodeCamp',
date: 'January 2016'
}
]};
return projectsFactory;
}]);<file_sep>/public/src/js/aboutMe/aboutMe.module.js
angular.module("AboutMeModule",['chart.js']);<file_sep>/public/src/js/microservice/controllers/microservice.controller.js
angular.module("MicroserviceModule")
.controller("MicroserviceController",["$scope",'microserviceFactory', function($scope, microserviceFactory){
// getting projects from the factory
$scope.projects = microserviceFactory.projects;
}]); | 7396ed2370edc5d448462a3d01f32f5e3d5efef6 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | UlisesCabrera/UlisesCabrera.github.io | ce2e930ccbe4410f316d06fd14c4b58ff13f4654 | a00610a4f0b755f0abb89c84aecc7bac120cebb0 |
refs/heads/master | <file_sep># Usage
We love seeing forks of Today I Learned in production! Here's a basic guide for
customizing your version of the site.
### Style
Feel free to get creative! The layout, colors, fonts, assets, and meta tags
we've chosen should only serve as a starting point.
### Attribution
Please link to Hashrocket somewhere on the main page! Today I Learned is an
open-source project, and support from the community helps inspire continued
development.
Here's an example of an easy way to link to us:
```elixir
# lib/your_app/templates/layout/app.html.eex
Today I Learned is an open-source project by <a href="https://hashrocket.com">Hashrocket</a>.
Check out the <a href="https://github.com/hashrocket/tilex">source code</a> to make your own!
```
### Forks in Production
Have you deployed TIL to production? Please open a pull request or contact
<EMAIL> to be recognized. Here are a few examples:
- https://til.energizedwork.com/
- https://til.brianemory.com/
- https://selleo.com/til
- https://til.simplebet.io
Thank you to everybody who has forked and contributed.
<file_sep>### Steps to reproduce
1.
### Expected behavior
Tell us what should happen
### Actual behavior
Tell us what happens instead
### System configuration
**Operating System**:
**Browser**:
<file_sep># CONTRIBUTING
Bug reports and pull requests are welcome on GitHub at
https://github.com/hashrocket/tilex.
### Issues
To open a new issue, visit our [Github Issues page][issues].
### Pull Requests
To open a pull request, please follow these steps:
1. [Fork][fork] it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Make some changes with accompanying tests
4. Ensure the entire test suite passes (`mix test`)
5. Stage the relevant changes (`git add --patch`)
6. Commit your changes (`git commit -m 'Add some feature'`)
7. Push to the branch (`git push origin my-new-feature`)
8. Create a new Pull Request 🎉
All pull requests are checked for style using the Elixir autoformatter and
[Credo][credo]. Run both to confirm that your code will pass:
```
$ mix format
$ mix credo
```
Adding a database migration? Ensure it can be rolled back with this command:
```
$ mix ecto.twiki
```
[credo]: https://github.com/rrrene/credo
[fork]: https://help.github.com/articles/fork-a-repo/
[issues]: https://github.com/hashrocket/tilex/issues
<file_sep>export function uploadImage(file, onSuccess, onError) {
const { imgurApiKey } = window.Tilex.clientConfig;
if (!imgurApiKey) {
onError({ showAlert: false });
throw new Error(
'Imgur API Key is not set. Please update your environment variables.'
);
}
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.imgur.com/3/image', true);
xhr.setRequestHeader('Authorization', `Client-id ${imgurApiKey}`);
xhr.onload = () => {
const parsedResponse = JSON.parse(xhr.response);
if (xhr.status > 201 || parsedResponse.data.error) {
onError();
return;
}
const url = parsedResponse.data.link;
onSuccess(url);
};
xhr.onerror = onError;
const fd = new FormData();
fd.append('image', file);
xhr.send(fd);
}
<file_sep>export APPSIGNAL_APP_ENV=
export APPSIGNAL_APP_NAME=
export APPSIGNAL_PUSH_API_KEY=
export BASIC_AUTH_PASSWORD=
export BASIC_AUTH_USERNAME=
export CANONICAL_DOMAIN=https://example.com
export DATE_DISPLAY_TZ=America/Chicago
export DEFAULT_TWITTER_HANDLE=
export ENABLE_BASIC_AUTH=
export GOOGLE_CLIENT_ID=
export GOOGLE_CLIENT_SECRET=
export GUEST_AUTHOR_ALLOWLIST=
export HOSTED_DOMAIN=
export IMGUR_CLIENT_ID=
export ORGANIZATION_NAME=
export slack_post_endpoint=
export twitter_access_token=
export twitter_access_token_secret=
export twitter_consumer_key=
export twitter_consumer_secret=
<file_sep># Tilex - Today I Learned in Elixir
[](https://github.com/hashrocket/tilex/actions/workflows/ci.yml)
> Today I Learned is an open-source project by the team at
> [Hashrocket][hashrocket] that catalogues the sharing & accumulation of
> knowledge as it happens day-to-day. Posts have a 200-word limit, and posting
> is open to any Rocketeer as well as select friends of the team. We hope you
> enjoy learning along with us.
This site was open-sourced in as a window into our development process, as well as
to allow people to experiment with the site on their own and contribute to the
project.
We originally implemented Tilex as [_hr-til_][hr-til], a Ruby on Rails app.
For updates, follow us on [Twitter][twitter] and subscribe to our monthly
[newsletter][newsletter].
### Installation
If you are creating your own version of the site, [fork][fork] the repository
and clone your fork:
```shell
$ git clone https://github.com/<your_github>/tilex
$ cd tilex
```
Then, install [Erlang][erlang], [Elixir][elixir], Node, and PostgreSQL.
[asdf][asdf] can do this in a single command:
```shell
$ asdf install
```
From here, we recommend using `make`:
```shell
$ make
$ make setup server
```
To do everything by hand, source your environment variables, install
dependencies, and start the server:
```shell
$ cp .env{.example,}
$ source .env
$ mix deps.get
$ mix ecto.setup
$ npm install --prefix assets
$ mix phx.server
```
Want to start with an empty database? Skip the seeds by running `mix ecto.create && mix
ecto.migrate` in place of `mix ecto.setup`.
Now you can visit http://localhost:4000 from your browser.
To serve the application at a different port, include the `PORT` environment
variable when starting the server:
```shell
$ PORT=4444 mix phx.server
```
### Authentication
Authentication is managed by Ueberauth and Google. See the [ueberauth_google
README][ueberauth_google] and [Google Oauth 2 docs][oauth_google] for
instructions. To allow users from a domain and/or comma-separated allowlist,
set those configurations in your environment:
```shell
# .env
export GOOGLE_CLIENT_ID="your-key.apps.googleusercontent.com"
export GOOGLE_CLIENT_SECRET="yoursecret"
export HOSTED_DOMAIN="your-domain.com"
export GUEST_AUTHOR_ALLOWLIST="<EMAIL>, <EMAIL>"
```
Once set, visit http://localhost:4000/admin and log in with an email address
from your permitted domain.
Tilex creates a new user on the first authentication, and then finds that same
user on subsequent authentications.
### Testing
Wallaby relies on [ChromeDriver][chromedriver]; install it via your method of
choice. Then, run tests with:
```shell
$ make test
```
or:
```shell
$ mix test
```
### Deployment
Hashrocket's Tilex is deployed to Heroku. These are Hashrocket's deployed
instances:
- Staging: https://tilex-staging.herokuapp.com
- Production: https://til.hashrocket.com
This project contains Mix tasks to deploy our instances; use as follows:
```shell
$ mix deploy <environment>
```
### Contributing
Please see [CONTRIBUTING](CONTRIBUTING.md) for more information. Thank you to
all of our [contributors][contrib].
### Code of Conduct
This project is intended to be a safe, welcoming space for collaboration, and
contributors are expected to adhere to the [Contributor Covenant][cc] code of
conduct. Please see [CODE OF CONDUCT](CODE_OF_CONDUCT.md) for more information.
### Usage
We love seeing forks of Today I Learned in production! Please consult
[USAGE](USAGE.md) for guidelines on appropriate styling and attribution.
### License
Tilex is released under the [MIT License][mit].opensource.org/licenses/MIT). Please
see [LICENSE](LICENSE.md) for more information.
---
### About
[][hashrocket]
Tilex is supported by the team at [Hashrocket, a multidisciplinary design and
development consultancy][hashrocket] If you'd like to [work with us][hire-us]
or [join our team][join-us], don't hesitate to get in touch.
[asdf]: https://github.com/asdf-vm/asdf
[cc]: http://contributor-covenant.org
[chromedriver]: https://sites.google.com/a/chromium.org/chromedriver/
[contrib]: https://github.com/hashrocket/tilex/graphs/contributors
[elixir]: https://elixir-lang.org/
[erlang]: https://www.erlang.org/
[fork]: https://help.github.com/articles/fork-a-repo/
[hashrocket]: https://hashrocket.com/
[hire-us]: https://hashrocket.com/contact-us/hire-us
[hr-til]: https://github.com/hashrocket/hr-til
[join-us]: https://hashrocket.com/contact-us/jobs
[mit]: http://www.opensource.org/licenses/MIT
[newsletter]: https://www.getrevue.co/profile/til
[oauth_google]: https://developers.google.com/identity/protocols/OAuth2WebServer
[twitter]: https://twitter.com/hashrockettil
[ueberauth_google]: https://github.com/ueberauth/ueberauth_google
<file_sep>--
-- PostgreSQL database dump
--
-- Dumped from database version 15.1
-- Dumped by pg_dump version 15.1
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- Name: channels; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.channels (
id bigint NOT NULL,
name character varying(255) NOT NULL,
twitter_hashtag character varying(255) NOT NULL,
inserted_at timestamp(0) without time zone NOT NULL,
updated_at timestamp(0) without time zone NOT NULL
);
--
-- Name: channels_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.channels_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: channels_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.channels_id_seq OWNED BY public.channels.id;
--
-- Name: developers; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.developers (
id bigint NOT NULL,
email character varying NOT NULL,
username character varying NOT NULL,
inserted_at timestamp(0) without time zone NOT NULL,
updated_at timestamp(0) without time zone NOT NULL,
twitter_handle character varying(255),
admin boolean DEFAULT false,
editor character varying(255) DEFAULT 'Text Field'::character varying
);
--
-- Name: developers_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.developers_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: developers_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.developers_id_seq OWNED BY public.developers.id;
--
-- Name: posts; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.posts (
id bigint NOT NULL,
title character varying NOT NULL,
body text NOT NULL,
inserted_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
channel_id integer NOT NULL,
slug character varying(255) NOT NULL,
likes integer DEFAULT 1 NOT NULL,
max_likes integer DEFAULT 1 NOT NULL,
published_at timestamp with time zone DEFAULT now() NOT NULL,
developer_id bigint,
tweeted_at timestamp with time zone,
CONSTRAINT likes_must_be_greater_than_zero CHECK ((likes > 0)),
CONSTRAINT max_likes_must_be_greater_than_zero CHECK ((max_likes > 0))
);
--
-- Name: posts_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.posts_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: posts_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.posts_id_seq OWNED BY public.posts.id;
--
-- Name: requests; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.requests (
page text NOT NULL,
request_time timestamp with time zone DEFAULT now()
);
--
-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.schema_migrations (
version bigint NOT NULL,
inserted_at timestamp(0) without time zone
);
--
-- Name: channels id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.channels ALTER COLUMN id SET DEFAULT nextval('public.channels_id_seq'::regclass);
--
-- Name: developers id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.developers ALTER COLUMN id SET DEFAULT nextval('public.developers_id_seq'::regclass);
--
-- Name: posts id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.posts ALTER COLUMN id SET DEFAULT nextval('public.posts_id_seq'::regclass);
--
-- Name: channels channels_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.channels
ADD CONSTRAINT channels_pkey PRIMARY KEY (id);
--
-- Name: developers developers_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.developers
ADD CONSTRAINT developers_pkey PRIMARY KEY (id);
--
-- Name: posts posts_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.posts
ADD CONSTRAINT posts_pkey PRIMARY KEY (id);
--
-- Name: schema_migrations schema_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.schema_migrations
ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (version);
--
-- Name: channels_name_index; Type: INDEX; Schema: public; Owner: -
--
CREATE UNIQUE INDEX channels_name_index ON public.channels USING btree (name);
--
-- Name: index_requests_on_request_time_in_app_tz; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX index_requests_on_request_time_in_app_tz ON public.requests USING btree (timezone('america/chicago'::text, request_time));
--
-- Name: posts_channel_id_index; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX posts_channel_id_index ON public.posts USING btree (channel_id);
--
-- Name: posts_developer_id_index; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX posts_developer_id_index ON public.posts USING btree (developer_id);
--
-- Name: posts_slug_index; Type: INDEX; Schema: public; Owner: -
--
CREATE UNIQUE INDEX posts_slug_index ON public.posts USING btree (slug);
--
-- Name: requests_page_index; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX requests_page_index ON public.requests USING btree (page);
--
-- Name: requests_request_time_index; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX requests_request_time_index ON public.requests USING btree (request_time);
--
-- Name: posts posts_channel_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.posts
ADD CONSTRAINT posts_channel_id_fkey FOREIGN KEY (channel_id) REFERENCES public.channels(id) ON DELETE CASCADE;
--
-- Name: posts posts_developer_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.posts
ADD CONSTRAINT posts_developer_id_fkey FOREIGN KEY (developer_id) REFERENCES public.developers(id) ON DELETE CASCADE;
--
-- PostgreSQL database dump complete
--
INSERT INTO public."schema_migrations" (version) VALUES (20161118221207);
INSERT INTO public."schema_migrations" (version) VALUES (20161228153637);
INSERT INTO public."schema_migrations" (version) VALUES (20161228161102);
INSERT INTO public."schema_migrations" (version) VALUES (20161229180247);
INSERT INTO public."schema_migrations" (version) VALUES (20170106200911);
INSERT INTO public."schema_migrations" (version) VALUES (20170120203217);
INSERT INTO public."schema_migrations" (version) VALUES (20170317204314);
INSERT INTO public."schema_migrations" (version) VALUES (20170317205716);
INSERT INTO public."schema_migrations" (version) VALUES (20170317210210);
INSERT INTO public."schema_migrations" (version) VALUES (20170317210552);
INSERT INTO public."schema_migrations" (version) VALUES (20170317210749);
INSERT INTO public."schema_migrations" (version) VALUES (20170317214042);
INSERT INTO public."schema_migrations" (version) VALUES (20170319161606);
INSERT INTO public."schema_migrations" (version) VALUES (20170518173833);
INSERT INTO public."schema_migrations" (version) VALUES (20170518183105);
INSERT INTO public."schema_migrations" (version) VALUES (20170601120632);
INSERT INTO public."schema_migrations" (version) VALUES (20170602200233);
INSERT INTO public."schema_migrations" (version) VALUES (20170726192554);
INSERT INTO public."schema_migrations" (version) VALUES (20170823194255);
INSERT INTO public."schema_migrations" (version) VALUES (20171208181757);
INSERT INTO public."schema_migrations" (version) VALUES (20180908171609);
INSERT INTO public."schema_migrations" (version) VALUES (20190827182708);
INSERT INTO public."schema_migrations" (version) VALUES (20200518184142);
INSERT INTO public."schema_migrations" (version) VALUES (20220425135720);
INSERT INTO public."schema_migrations" (version) VALUES (20220429184256);
<file_sep>import $ from 'jquery';
import 'jquery.cookie';
$(function(){
var csrf = document.querySelector('meta[name=csrf-token]').content;
function LikeButton(el) {
this.id = el.id;
this.$el = $(el);
this.$count = this.$el.find('.post__like-count')
this.$el.on("click", $.proxy(this.toggle, this));
this.updateClass();
};
LikeButton.prototype.toggle = function(e) {
e.preventDefault();
this.isLiked() ? this.unlike() : this.like();
};
LikeButton.prototype.like = function() {
var lb = this;
$.ajax({
type: "POST",
url: "/posts/" + lb.id + "/like.json",
data: {},
success: function(result) {
$.cookie(lb.likeSlug(), 'liked', { path: '/', expires: 3600 });
lb.updateText(result);
lb.updateClass();
},
headers: {
"X-CSRF-TOKEN": csrf
}
});
};
LikeButton.prototype.unlike = function() {
var lb = this;
$.ajax({
type: "POST",
url: "/posts/" + lb.id + "/unlike.json",
data: {},
success: function(result){
$.removeCookie(lb.likeSlug(), { path: '/', expires: 3600 });
lb.updateText(result);
lb.updateClass();
},
headers: {
"X-CSRF-TOKEN": csrf
}
});
};
LikeButton.prototype.updateClass = function() {
this.$el.toggleClass('liked', this.isLiked());
}
LikeButton.prototype.updateText = function(result) {
this.$count.text(result.likes);
};
LikeButton.prototype.isLiked = function() {
return !!$.cookie(this.likeSlug());
};
LikeButton.prototype.likeSlug = function() {
return 'liked -' + this.id;
};
$('.js-like-action').each(function() {
new LikeButton(this);
});
$('header').attr('data-likes-loaded', 'true')
});
<file_sep>import {Socket} from "phoenix"
export default class TextConversion {
constructor(properties) {
this.convertedTextCallback = properties.convertedTextCallback
this.socket = new Socket("/socket")
this.channel = this.socket.channel("text_converter", {})
}
init() {
this.socket.connect()
this.channel.join()
this.observeChannelResponse()
}
convert(text, format) {
let conversionObject = {}
conversionObject[format] = text
this.channel.push("convert", conversionObject)
}
observeChannelResponse() {
this.channel.on("converted", payload => {
this.convertedTextCallback(payload.html);
})
}
}
<file_sep>#!make
include .env
.PHONY: help console outdated setup server test update
.env:
cp .env.example .env
help: ## Shows this help.
@grep ": \#" ${MAKEFILE_LIST} | column -t -s ':' | sort
console: ## Opens the App console.
iex -S mix
outdated: ## Shows outdated packages.
mix hex.outdated
setup: ## Setup the App.
mix local.hex --force
mix setup
mix gettext.extract --merge --no-fuzzy
server: ## Start the App server.
npm install --prefix assets/
mix phx.server
test: ## Run the test suite.
mix format
mix credo
echo "chromedriver => `chromedriver --version`"
echo "chrome => `/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version`"
rm -f screenshots/*
mkdir -p screenshots/
mix test --trace
update: ## Update dependencies.
mix deps.update --all
<file_sep>import TextConversion from './text_conversion';
import autosize from 'autosize';
import CodeMirror from 'codemirror';
import 'codemirror-mode-elixir';
import 'codemirror/keymap/vim';
import 'codemirror/mode/gfm/gfm';
import 'codemirror/mode/ruby/ruby';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/go/go';
import 'codemirror/mode/elm/elm';
import 'codemirror/mode/erlang/erlang';
import 'codemirror/mode/css/css';
import 'codemirror/mode/sass/sass';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/dracula.css';
import { uploadImage } from './image_uploader.js';
export default class PostForm {
constructor(props) {
this.$postBodyInput = props.postBodyInput;
this.$postBodyPreview = props.postBodyPreview;
this.$wordCountContainer = props.wordCountContainer;
this.$bodyWordLimitContainer = props.bodyWordLimitContainer;
this.bodyWordLimit = props.bodyWordLimit;
this.$titleInput = props.titleInput;
this.$titleCharacterLimitContainer = props.titleCharacterLimitContainer;
this.titleCharacterLimit = props.titleCharacterLimit;
this.$previewTitleContainer = props.previewTitleContainer;
this.loadingIndicator = props.loadingIndicator;
this.textConversion = this.textConversion();
}
init() {
if (!this.$postBodyInput.length) return;
const { editor } = window.Tilex.clientConfig;
this.textConversion.init();
this.setInitialPreview();
this.observePostBodyInputChange();
this.observeTitleInputChange();
this.observeImagePaste();
autosize(this.$postBodyInput);
const useCodeMirror = /Code Editor|Vim/.test(editor);
if (useCodeMirror) {
const defaultOptions = {
lineNumbers: true,
theme: 'dracula',
tabSize: 2,
mode: 'gfm',
insertSoftTab: true,
smartIndent: false,
lineWrapping: true,
};
const options =
editor === 'Vim'
? { ...defaultOptions, keyMap: 'vim' }
: defaultOptions;
const textarea = this.$postBodyInput.get(0);
const codeMirror = CodeMirror.fromTextArea(textarea, options);
// const that = this;
codeMirror.on('changes', instance => {
const value = instance.getValue();
this.$postBodyInput.val(value).trigger('change');
});
codeMirror.on('paste', (instance, ev) => {
const handleImageUploadSuccess = url => {
instance.replaceSelection(this.urlToMarkdownImage(url));
this.hideLoadingIndicator();
};
this.handleEditorPaste(
ev,
handleImageUploadSuccess,
this.handleImageUploadError
);
});
}
}
setInitialPreview() {
this.textConversion.convert(this.$postBodyInput.text(), 'markdown');
this.updateWordCount();
this.updateWordLimit();
this.updateTitleLimit();
this.updatePreviewTitle();
}
wordCount() {
return this.$postBodyInput
.val()
.split(/\s+|\n/)
.filter(Boolean).length;
}
updateWordCount() {
this.$wordCountContainer.html(this.wordCount());
}
updateWordLimit() {
this.renderCountMessage(
this.$bodyWordLimitContainer,
this.bodyWordLimit - this.wordCount(),
'word'
);
}
updateTitleLimit() {
this.renderCountMessage(
this.$titleCharacterLimitContainer,
this.titleCharacterLimit - this.$titleInput.val().length,
'character'
);
}
updatePreviewTitle() {
this.$previewTitleContainer.text(this.$titleInput.val());
}
renderCountMessage($el, amount, noun) {
var plural = amount === 1 ? '' : 's';
$el
.toggleClass('negative', amount < 0)
.text(amount + ' ' + noun + plural + ' available');
}
handleEditorPaste = (ev, onSuccess, onError) => {
const clipboard = ev.clipboardData
? ev.clipboardData
: ev.originalEvent.clipboardData;
const files = clipboard.files;
const file = files.length > 0 ? files[0] : null;
const isImage = file && !!file.type.match('image');
if (isImage) {
this.showLoadingIndicator();
uploadImage(file, onSuccess, onError);
}
};
showLoadingIndicator() {
this.loadingIndicator.style.display = 'flex';
}
hideLoadingIndicator() {
this.loadingIndicator.style.display = 'none';
}
handleImageUploadError = ({ showAlert = true }) => {
if (showAlert) alert(`Failed to upload image to Imgur`);
this.hideLoadingIndicator();
};
handlePostBodyPreview = html => {
Prism.highlightAll(this.$postBodyPreview.html(html));
};
handlePostBodyChanged = ({ target: { value } }) => {
this.updateWordCount();
this.updateWordLimit();
this.textConversion.convert(value, 'markdown');
};
observeImagePaste() {
this.$postBodyInput.on('paste', ev => {
const handleImageUploadSuccess = url => {
this.hideLoadingIndicator();
this.replaceSelection(ev.target, this.urlToMarkdownImage(url));
this.handlePostBodyChanged(ev);
};
this.handleEditorPaste(
ev,
handleImageUploadSuccess,
this.handleImageUploadError
);
});
}
observePostBodyInputChange() {
this.$postBodyInput.on('keyup', this.handlePostBodyChanged);
this.$postBodyInput.on('change', this.handlePostBodyChanged);
}
observeTitleInputChange() {
this.$titleInput.on('input', e => {
this.updateTitleLimit();
this.updatePreviewTitle();
});
}
urlToMarkdownImage(url) {
return ``;
}
replaceSelection(field, myValue) {
if (field.selectionStart || field.selectionStart == '0') {
var startPos = field.selectionStart;
var endPos = field.selectionEnd;
field.value =
field.value.substring(0, startPos) +
myValue +
field.value.substring(endPos, field.value.length);
} else {
field.value += myValue;
}
}
textConversion() {
return new TextConversion({
convertedTextCallback: this.handlePostBodyPreview,
});
}
}
| 8e91daf5141b98e43e2f535d81f47720b3df1783 | [
"SQL",
"Markdown",
"JavaScript",
"Makefile",
"Shell"
] | 11 | Markdown | hashrocket/tilex | 96c205582af81ca26f0d7f557215aca68b84425e | 9a3b98a1f41e9f42b12ea93ace647bf0de1d544f |
refs/heads/master | <repo_name>Ricochn/douyu<file_sep>/README.md
"一个带界面的斗鱼爬虫"
<file_sep>/get_danmu.py
import socket
import re
#房间号
id = 4015880
mslist=[]
#主进程flag,用来统一退出
ison = True
#斗鱼报文格式,参看官方手册
def sendmsg(sock,msgstr) :
msg=msgstr.encode('utf-8')
data_length= len(msg)+8
code=689
msgHead=int.to_bytes(data_length,4,'little')\
+int.to_bytes(data_length,4,'little')+int.to_bytes(code,4,'little')
sock.send(msgHead)
sent=0
while sent<len(msg):
tn= sock.send(msg[sent:])
sent= sent + tn
def get_daunmu(roomid):
#基本操作
send_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dammu_host_name = 'openbarrage.douyutv.com'
dammu_host = socket.gethostbyname(dammu_host_name)
send_sock.connect((dammu_host, 8601))
#发送登陆信息,参看手册
msg = "type@=loginreq/username@=visitor114834/password@=<PASSWORD>6/roomid@=%d/\x00"%roomid
sendmsg(send_sock, msg)
BUFSIZE = 1024
data = send_sock.recv(BUFSIZE)
#print(data)
data = send_sock.recv(BUFSIZE)
#print(data)
print(">>>登陆信息已发送")
#发送加入组信息
msg = "type@=joingroup/rid@=%d/gid@=-9999/\x00"%roomid
sendmsg(send_sock, msg)
data = send_sock.recv(BUFSIZE)
#print(data)
print(">>>所在组已发送")
print("\n\n弹幕开始啦:\r\n")
#前期工作完成,开始接收弹幕
while ison:
data = send_sock.recv(BUFSIZE)
text = re.findall(b"/txt@=.+?/", data)
if len(text)!=0:
#print(text[0][6:][:-1].decode("utf-8"))
try:
mslist.append(text[0][6:][:-1].decode("utf-8"))
except:
pass
if __name__ == "__main__":
get_daunmu(id)<file_sep>/gui.pyw
import tkinter
import get_danmu
import threading
def back_get_msg():
print("back_get_msg bdgin")
get_danmu.get_daunmu(int(entry_room_id.get()))
def change():
lenth = len(get_danmu.mslist)
text_danmu.insert(tkinter.END, "change begin")
while get_danmu.ison:
if len(get_danmu.mslist) > lenth:
try:
text_danmu.insert(tkinter.END, get_danmu.mslist[-1]+"\n")
lenth = len(get_danmu.mslist)
text_danmu.focus_force()
except:
pass
def submit_event():
print("启动线程")
thread1=threading.Thread(target=back_get_msg)
thread2=threading.Thread(target=change)
thread1.start()
thread2.start()
def closeWindow():
get_danmu.ison = False
top.destroy()
#顶层窗口
top = tkinter.Tk()
top.geometry('500x300')
top.protocol('WM_DELETE_WINDOW', closeWindow)
label_room_id = tkinter.Label(top, text="输入房间号:")
entry_room_id = tkinter.Entry(top, background="#aaaaff")
button_submit = tkinter.Button(top, text="提交查看弹幕", command=submit_event)
text_danmu = tkinter.Text(top)
label_room_id.pack()
entry_room_id.pack()
button_submit.pack()
text_danmu.pack()
tkinter.mainloop() | 21372ffc4d360ac9c5cf1bc829aca90fae88a372 | [
"Markdown",
"Python"
] | 3 | Markdown | Ricochn/douyu | ae86a410061cf8684131489656fab52e005aabcc | cc8d1f1065b33769d970dc1f5e0a0be84977b82c |
refs/heads/main | <file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Calculator : MonoBehaviour
{
public int Number1;
public int Number2;
public Text Result;
public InputField Input1;
public InputField Input2;
public void InputNumbers()
{
Number1 = int.Parse(Input1.text);
Number2 = int.Parse(Input2.text);
}
public void Calculate()
{
var result = Number1 + Number2;
Result.text = result.ToString();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class StatementButton : MonoBehaviour
{
bool aButton = true;
public void SwitchAnswer(){
if(aButton)
{
GetComponent<Text>().text = "falsch";
aButton = false;
}
else {
GetComponent<Text>().text = "wahr";
aButton = true;
}
}
}
| cf0f1ba05a3745a0c7bf3c33ae877e61ec00537e | [
"C#"
] | 2 | C# | 4ahmnm2021-G3-G4/Speedprogramming001-inner | 8501ce713556624d86adf8a5c5fc83b1f95d0790 | 16f8e5905ce466b71e83a51e68f81f517bf22542 |
refs/heads/main | <repo_name>mimi0523/yt-concate<file_sep>/yt_concate/settings.py
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv('API_KEY')
| 466e125369cfaa66ba3ebfcae1c11d85b87b8438 | [
"Python"
] | 1 | Python | mimi0523/yt-concate | 8f211a92a3f5e977a21e3fc26e7853e2c6bf58c2 | 70e3912e840de0a0f23319ffd2e06b2c64879f75 |
refs/heads/master | <repo_name>klyuevv7/shop_json<file_sep>/src/main/java/org/example/service/searchofcriterians/SearchOfCriterionLastName.java
package org.example.service.searchofcriterians;
import org.example.controller.ServiceControllerOperations;
import org.example.model.Consumer;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class SearchOfCriterionLastName implements SearchOfCriterion {
private final ServiceControllerOperations searchController;
public SearchOfCriterionLastName(ServiceControllerOperations searchController) {
this.searchController = searchController;
}
public String findConsumerBySurname(String lastName) throws Exception {
List<Consumer> listConsumers = searchController.findConsumerBySurname(lastName);
List<JSONObject> jsonObjectList = new ArrayList<>();
for(Consumer consumer : listConsumers)
jsonObjectList.add(consumer.toJSONObject());
return jsonObjectList.toString();
}
@Override
public String result(JSONObject jsonObject) throws Exception {
return findConsumerBySurname(jsonObject.getString("lastName"));
}
}
<file_sep>/src/main/java/org/example/controller/StatController.java
package org.example.controller;
import org.example.model.Buy;
import org.example.model.Consumer;
import org.example.model.Product;
import java.sql.ResultSet;
import java.util.*;
public class StatController implements StatControllerOperations {
DaoOperations daoOperations;
public StatController(DaoOperations daoOperations) {
this.daoOperations = daoOperations;
}
@Override
public List<Consumer> findAllConsumers() throws Exception {
ResultSet resultSet = daoOperations.findAllConsumer();
List<Consumer> listConsumer = new ArrayList<>();
while (resultSet.next())
listConsumer.add(new Consumer(resultSet.getLong(1),
resultSet.getString(2),
resultSet.getString(3)));
return listConsumer;
}
@Override
public List<Product> findAllProducts() throws Exception {
ResultSet resultSet = daoOperations.findAllProduct();
List<Product> listProduct = new ArrayList<>();
while (resultSet.next())
listProduct.add(new Product(resultSet.getLong(1),
resultSet.getString(2),
resultSet.getInt(3)));
return listProduct;
}
@Override
public List<Buy> findAllBuy() throws Exception {
ResultSet resultSet = daoOperations.findAllBuy();
List<Buy> listAllBuy = new ArrayList<>();
while (resultSet.next())
listAllBuy.add(new Buy(resultSet.getLong(1),
resultSet.getLong(2),
resultSet.getLong(3),
resultSet.getDate(4)));
return listAllBuy;
}
/**
* На вход передаётся интервал дат сбора статистики. Результат операции -
* статистика по покупателям за период из двух дат, включительно, без выходных
* @param startDate - Начальная дата
* @param endDate - Конечная дата
* @return Возвращает статистику по покупателям за период из двух дат, включительно, без выходных
*/
@Override
public Map<Long, Map<Long,Long>> statConsumerByPeriod(Date startDate, Date endDate) throws Exception {
List<Buy> listAllBuy = findAllBuy();
List<Product> listProduct = findAllProducts();
// Создание списка покупок попадающих в период из двух дат, включительно, без выходных
List<Buy> listAllBuyForPeriodWithoutWeekend = new ArrayList<>();
for (Buy buy : listAllBuy){
Date dateOfBuy = buy.getDate();
if((dateOfBuy.after(startDate) || dateOfBuy.equals(startDate))
&& (dateOfBuy.before(endDate) || dateOfBuy.equals(endDate))){
Calendar c = Calendar.getInstance();
c.setTime(dateOfBuy);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if((dayOfWeek != 1) && (dayOfWeek != 7)){
listAllBuyForPeriodWithoutWeekend.add(buy);
}
}
}
// Создание множества: ключ - идентификатор покупателя, значение - множество,
// где ключ идентификатор товара, значение - количество покупок данного товара
Map<Long, Map<Long,Long>> mapConsumerIdAndProductId = new HashMap<>();
Map<Long,Long> mapProductIdAndCount = null;
for (Buy buy: listAllBuyForPeriodWithoutWeekend) {
if(mapConsumerIdAndProductId.containsKey(buy.getConsumerId())){
if(mapConsumerIdAndProductId.get(buy.getConsumerId()).containsKey(buy.getProductId())) {
Long count =
mapConsumerIdAndProductId.get(buy.getConsumerId()).get(buy.getProductId()) + 1;
mapConsumerIdAndProductId.get(buy.getConsumerId()).put(buy.getProductId(),count);
} else {
mapConsumerIdAndProductId.get(buy.getConsumerId()).put(buy.getProductId(),1L);
}
} else {
mapProductIdAndCount = new HashMap<>();
mapProductIdAndCount.put(buy.getProductId(),1L);
mapConsumerIdAndProductId.put(buy.getConsumerId(),mapProductIdAndCount);
}
}
// Создание множества: ключ - идентификатор покупателя, значение - множество,
// где ключ идентификатор товара, значение - стоимость покупок данного товара
Map<Long,Map<Long,Long>> mapConsumerIdAndProductExpenses = new HashMap<>();
Map<Long,Long> mapProductIdAndExpenses = null;
for (Map.Entry<Long,Map<Long,Long>> item : mapConsumerIdAndProductId.entrySet()) {
mapProductIdAndExpenses = new HashMap<>();
for (Product product: listProduct)
if (item.getValue().containsKey(product.getId())) {
long count = item.getValue().get(product.getId());
long expenses = product.getPrice() * count;
mapProductIdAndExpenses.put(product.getId(), expenses);
}
mapConsumerIdAndProductExpenses.put(item.getKey(),mapProductIdAndExpenses);
}
return mapConsumerIdAndProductExpenses;
}
}
<file_sep>/readme.txt
Создать базу данных с именем db_shop с логином postgres и паролем postgres. Восстановить базу данных с дампа backupDB
Программа использует для подключения следующие данные: DB_URL = "jdbc:postgresql://localhost:5432/db_shop"; USER = "postgres"; PASS = "<PASSWORD>";
Пример запуска программы: java -jar shop.jar search Input_sr.json output.json
<file_sep>/src/main/java/org/example/service/JsonStatService.java
package org.example.service;
import org.example.controller.StatControllerOperations;
import org.example.model.Consumer;
import org.example.model.Product;
import org.example.service.forStatService.Purchases;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.lang.String.format;
public class JsonStatService implements RequestService {
StatControllerOperations statController;
public JsonStatService(StatControllerOperations statController) {
this.statController = statController;
}
@Override
public String result(String request) throws Exception {
JSONObject jsonRequest = null;
String stringstartDate = null;
String stringendDate = null;
try {
jsonRequest = new JSONObject(request);
stringstartDate = jsonRequest.getString("startDate");
stringendDate = jsonRequest.getString("endDate");
} catch (Exception e){
return "{\"type\":\"error\",\"message\":\"Ошибка получения периода дат\"}";
}
Date startDate = null;
Date endDate = null;
try{
startDate = new SimpleDateFormat("yyyy-MM-dd").parse(stringstartDate);
endDate = new SimpleDateFormat("yyyy-MM-dd").parse(stringendDate);
}catch(Exception e){
throw new Exception("Не верно задан период дат");
}
long milliseconds = endDate.getTime() - startDate.getTime();
int days = (int) (milliseconds / (24 * 60 * 60 * 1000));
int weekendDay = 0;
Calendar c = Calendar.getInstance();
for (int day = 0; day < days; day++){
c.setTime(new Date (startDate.getTime() + (long)day * 24 * 60 * 60 * 1000));
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if((dayOfWeek == 1) || (dayOfWeek == 7)) weekendDay++;
}
days -= weekendDay;
if(days < 0) days = 0;
List<Consumer> listConsumer = null;
List<Product> listProduct = null;
Map<Long, Map<Long, Long>> mapConsumerIdAndProductExpenses = null;
listConsumer = statController.findAllConsumers();
listProduct =statController.findAllProducts();
// Создание множества: ключ - идентификатор покупателя, значение - множество,
// где ключ идентификатор товара, значение - стоимость покупок данного товара
mapConsumerIdAndProductExpenses
= statController.statConsumerByPeriod(startDate, endDate);
StringBuilder result = new StringBuilder("{\"type\":\"stat\",\"totalDays\":" +
days + ",\"customers\":[");
long totalExpensesAllConsumer = 0;
for (Map.Entry<Long,Map<Long,Long>> itemByConsumerId : mapConsumerIdAndProductExpenses.entrySet()) {
String consumerSurname = null;
String consumerName = null;
for (Consumer consumer : listConsumer){
if(itemByConsumerId.getKey().equals(consumer.getId())){
consumerName = consumer.getName();
consumerSurname = consumer.getSurname(); break;
}
}
result.append("{\"name\":\"").
append(consumerSurname).append(" ").
append(consumerName).append(",\"purchases\":[");
Map<Long,Long> mapProductExpenses = mapConsumerIdAndProductExpenses.get(itemByConsumerId.getKey());
long totalExpenses = 0;
for (Map.Entry<Long,Long> itemByProductId : mapProductExpenses.entrySet()){
String productName = null;
for (Product product : listProduct){
if(product.getId() == itemByProductId.getKey()){
productName = product.getName(); break;
}
}
long expenses = itemByProductId.getValue();
result.append(new Purchases(productName, expenses).toJSONObject()).append(",");
totalExpenses = totalExpenses + expenses;
}
int endChar = result.length();
result.delete(endChar-1, endChar);
totalExpensesAllConsumer = totalExpensesAllConsumer + totalExpenses;
result.append("],\"totalExpenses\":").append(totalExpenses).append("},");
}
if(!mapConsumerIdAndProductExpenses.isEmpty()){
int endChar = result.length();
result.delete(endChar-1, endChar);
}
result.append("],\"totalExpenses\":").append(totalExpensesAllConsumer).append(",");
double totalConsumer = mapConsumerIdAndProductExpenses.entrySet().size();
double avgExpenses = 0;
if (totalConsumer != 0) avgExpenses = totalExpensesAllConsumer / totalConsumer;
String stringFormatedAvgExpenses = format("%.2f", avgExpenses);
result.append("\"avgExpenses\":").append(stringFormatedAvgExpenses).append("}");
return result.toString();
}
}
<file_sep>/README.md
Создать базу данных с именем db_shop с логином postgres и паролем postgres.
Восстановить базу данных с дампа backupDB
Программа использует для подключения следующие данные:
DB_URL = "jdbc:postgresql://localhost:5432/db_shop";
USER = "postgres";
PASS = "<PASSWORD>";
Пример запуска программы:
java -jar shop.jar search Input_sr.json output.json
<file_sep>/src/main/java/org/example/service/searchofcriterians/SearchOfCriterionExpenses.java
package org.example.service.searchofcriterians;
import org.example.controller.ServiceControllerOperations;
import org.example.model.Consumer;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class SearchOfCriterionExpenses implements SearchOfCriterion{
private final ServiceControllerOperations searchController;
public SearchOfCriterionExpenses(ServiceControllerOperations searchController) {
this.searchController = searchController;
}
public String findConsumerByIntervalExpensesAllBuy(int minExpensesAllBuy, int maxExpensesAllBuy)
throws Exception {
List<Consumer> listConsumers =
searchController.findConsumerByIntervalExpensesAllBuy(minExpensesAllBuy, maxExpensesAllBuy);
List<JSONObject> jsonObjectList = new ArrayList<>();
for(Consumer consumer : listConsumers)
jsonObjectList.add(consumer.toJSONObject());
return jsonObjectList.toString();
}
@Override
public String result(JSONObject jsonObject) throws Exception {
return findConsumerByIntervalExpensesAllBuy(jsonObject.getInt("minExpenses"),
jsonObject.getInt("maxExpenses"));
}
}
<file_sep>/src/main/java/org/example/dao/DaoShop.java
package org.example.dao;
import org.example.controller.DaoOperations;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Получает значения из таблиц базы данных
*/
public class DaoShop implements DaoOperations {
private final Connection connection;
/**
* @param connection - соединение с базой данных
*/
public DaoShop(Connection connection) {
this.connection = connection;
}
@Override
public ResultSet findConsumerBySurname(String surName) throws Exception {
try {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(
"SELECT * FROM public.consumer where surname = '"+ surName + "'");
return result;
} catch (Exception e) {
throw new Exception("Ошибка получения данных из таблицы покупателей в БД");
}
}
@Override
public ResultSet findBuyByProduct(String productName) throws Exception {
ResultSet result = null;
try {
Statement statement = connection.createStatement();
result = statement.executeQuery(
"SELECT id FROM public.product where name = '"+ productName + "'");
} catch (Exception e) {
throw new Exception("Ошибка получения данных из таблицы товаров в БД");
}
try {
Statement statement = connection.createStatement();
long productId = 0;
if (result.next()) productId = result.getLong(1);
result = statement.executeQuery(
"SELECT * FROM public.buy where product = '"+ productId + "'");
return result;
} catch (Exception e) {
throw new Exception("Ошибка получения данных из таблицы покупок в БД");
}
}
@Override
public ResultSet findConsumersById(long id) throws Exception {
try {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(
"SELECT * FROM public.consumer where id = '"+ id + "'");
return result;
} catch (Exception e) {
throw new Exception("Ошибка получения данных из таблицы покупателей в БД");
}
}
@Override
public ResultSet findAllBuy() throws Exception {
try {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(
"SELECT * FROM public.buy");
return result;
} catch (Exception e) {
throw new Exception("Ошибка получения данных из таблицы покупок в БД");
}
}
@Override
public ResultSet findAllProduct() throws Exception {
try {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(
"SELECT * FROM public.product");
return result;
} catch (Exception e) {
throw new Exception("Ошибка получения данных из таблицы товаров в БД");
}
}
@Override
public ResultSet findAllConsumer() throws Exception {
try {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(
"SELECT * FROM public.consumer");
return result;
} catch (Exception e) {
throw new Exception("Ошибка получения данных из таблицы покупателей в БД");
}
}
public static void main(String[] args) throws Exception {
ResultSet resultSet = new DaoShop(new JDBCPostgreSQL().connection()).findConsumerBySurname("Иванов");
}
}
<file_sep>/src/main/java/org/example/model/Consumer.java
package org.example.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.json.JSONObject;
public class Consumer {
@JsonIgnore
private long id;
@JsonProperty("firstName")
private String name;
@JsonProperty("lastName")
private String surname;
public Consumer(){
}
public Consumer(long id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
@Override
public String toString() {
return "Consumer[ID:" + id + ", Name: " + name + ", Surname: " + surname + "]";
}
public JSONObject toJSONObject(){
JSONObject objects = new JSONObject();
objects.put("lastName", getSurname());
objects.put("firstName", getName());
return objects;
}
}
<file_sep>/src/main/java/org/example/service/JsonSearchService.java
package org.example.service;
import org.example.controller.ServiceControllerOperations;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonSearchService implements RequestService {
ServiceControllerOperations searchController;
public JsonSearchService(ServiceControllerOperations searchController) {
this.searchController = searchController;
}
@Override
public String result(String request) throws Exception {
JSONObject jsonRequest = null;
JSONArray criterias = null;
try {
jsonRequest = new JSONObject(request);
criterias = jsonRequest.getJSONArray("criterias");
} catch (Exception e){
return "{\"type\":\"error\",\"message\":\"Ошибка получения критериев поиска\"}";
}
// Список всех критериев поиска (могут повторяться)
List<String> listCriterias = new ArrayList<>();
// Набор всех критериев поиска с результатами поиска
Map<String, String> mapCriteriasAndResult = new HashMap<>();
SelectCriterion selectCriterion = new SelectCriterion(searchController);
for (Object object : criterias) {
String criterion = object.toString();
listCriterias.add(criterion);
// Если критерий поиска уже был, то искать результат не нужно, он есть в данном наборе
if(mapCriteriasAndResult.containsKey(criterion)) continue;
JSONObject jsonObject = ((JSONObject) object);
String result = null;
boolean keyCriterionFinded = false;
for (String keyCriterion : selectCriterion.getCriterion().keySet()){
if(jsonObject.has(keyCriterion)) {
keyCriterionFinded = true;
result = selectCriterion.getCriterion().get(keyCriterion).result(jsonObject);
}
}
if(!keyCriterionFinded){
return "{\"type\":\"error\",\"message\":\"Ключ не поддерживается " +
"в критерии поиска: " + criterion +"\"}";
}
mapCriteriasAndResult.put(criterion,result);
}
StringBuilder result = new StringBuilder("{\"type\":\"search\",\"results\":[");
for (String criterion : listCriterias){
result.append("{\"criteria\":");
result.append(criterion);
result.append(",\"results\":");
result.append(mapCriteriasAndResult.get(criterion));
result.append("},");
}
int endChar = result.length();
result.delete(endChar-1, endChar);
result.append("]}");
return result.toString();
}
}
<file_sep>/src/main/java/org/example/controller/StatControllerOperations.java
package org.example.controller;
import org.example.model.Buy;
import org.example.model.Consumer;
import org.example.model.Product;
import java.util.Date;
import java.util.List;
import java.util.Map;
public interface StatControllerOperations {
List<Consumer> findAllConsumers() throws Exception;
List<Product> findAllProducts() throws Exception;
List<Buy> findAllBuy() throws Exception;
Map<Long, Map<Long,Long>> statConsumerByPeriod(Date startDate, Date endDate)
throws Exception;
}
<file_sep>/src/main/java/org/example/service/searchofcriterians/SearchOfCriterion.java
package org.example.service.searchofcriterians;
import org.json.JSONObject;
public interface SearchOfCriterion {
String result(JSONObject jsonObject) throws Exception;
}
<file_sep>/src/main/java/org/example/dao/JDBCPostgreSQL.java
package org.example.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* В этой программе проверяется правильность конфигурирования
* базы данных и драйвера JDBC, выполняется соединение с базой данных
*/
public class JDBCPostgreSQL {
static final String DB_URL = "jdbc:postgresql://localhost:5432/db_shop";
static final String USER = "postgres";
static final String PASS = "<PASSWORD>";
/**
* @return Возвращает соединение с базой данных
* или null, если соединение с БД не установлено.
*/
public Connection connection() throws Exception {
// System.out.println("Testing connection to PostgreSQL JDBC");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
throw new Exception("PostgreSQL JDBC Driver is not found. Include it in your library path");
// System.out.println("PostgreSQL JDBC Driver is not found. Include it in your library path");
// e.printStackTrace();
// return null;
}
// System.out.println("PostgreSQL JDBC Driver successfully connected");
Connection connection = null;
try {
connection = DriverManager
.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
throw new Exception("Connection to DB failed");
// System.out.println("Connection Failed");
// e.printStackTrace();
// return null;
}
if (connection != null) {
// System.out.println("You successfully connected to database now");
} else {
throw new Exception("Failed to make connection to database");
// System.out.println("Failed to make connection to database");
}
return connection;
}
}
| 75954a6c71296bb657e6981888c90c399c0c4d82 | [
"Markdown",
"Java",
"Text"
] | 12 | Java | klyuevv7/shop_json | 59524ab4a7f76c6364e6608d550f274478d530d0 | abd2b78a841e8a06ef8c3e0e7f4c7253fd2f4920 |
refs/heads/master | <repo_name>MayarLotfy/mnist_mc<file_sep>/plot_error.py
"""Plot training/validation error."""
import cPickle as pickle
import gzip
import matplotlib.pyplot as plt
import seaborn as sns
# Unpickle training info
filename = './output/mnist_mc_dropout_info.pkl.gz'
f = gzip.open(filename, 'rb')
data = pickle.load(f)
f.close()
# Get accuracy
TA = data['training accuracy']
VA = data['validation accuracy']
# Compute error as %
TE = [(1. - ta) * 100 for ta in TA]
VE = [(1. - va) * 100 for va in VA]
# Plot training and validation errors
plt.switch_backend('Agg')
plt.plot(VE, c='r', lw=1.5)
plt.plot(TE, c='g', lw=1.5)
plt.legend(['validation', 'training'], fontsize=20)
plt.ylim(-1, 10)
plt.xlabel('epoch', size=20)
plt.ylabel('error (%)', size=20)
plt.tight_layout()
plt.savefig('./output/errors.eps', format='eps', dpi=100)
plt.savefig('./output/errors.jpg', format='jpg', dpi=100)
plt.close()<file_sep>/mnist_mc_dropout.pbs
#!/bin/bash
#PBS -q gpu
#PBS -l walltime=3:00:00
cd ~
cd mnist-mc-dropout
module load cuda/7.5
THEANO_FLAGS='mode=FAST_RUN,device=gpu,floatX=float32' python mnist_mc_dropout.py<file_sep>/README.md
# mnist-mc-dropout
# Description
Writing Python (Lasagne + Theano library) code for respresenting model uncertainty in deep learning. Based on the following:
* 2016: [Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning](https://arxiv.org/abs/1506.02142), [Dropout as a Bayesian Approximation: Appendix](https://arxiv.org/abs/1506.02157)
Training takes about less than 3 hours (for 3000 epochs) minutes with GPU; thanks [National Supercomputing Centre (NSCC) Singapore](http://www.nscc.sg)!
The main implementation is in ```mnist_mc_dropout.py``` which uses helper functions from ```helpers.py```, and of course the dataset ```mnist.pkl.gz```. For plotting training/validation errors see ```plot_error.py```. All the outputs are saved/pickled in the ```output``` folder.
Run/theano settings: ```THEANO_FLAGS='mode=FAST_RUN, device=gpu, floatX=float32' python mnist_mc_dropout.py```
# (Some) Results:
## Training details...
<img src="./output/errors.jpg">
## Interesting cases...
<img src="./output/index_8.jpg" height="200" width="400"> <img src="./output/index_15.jpg" height="200" width="400">
<img src="./output/index_18.jpg" height="200" width="400"> <img src="./output/index_20.jpg" height="200" width="400">
<img src="./output/index_35.jpg" height="200" width="400"> <img src="./output/index_36.jpg" height="200" width="400">
<img src="./output/index_62.jpg" height="200" width="400"> <img src="./output/index_65.jpg" height="200" width="400">
<img src="./output/index_73.jpg" height="200" width="400"> <img src="./output/index_78.jpg" height="200" width="400">
<img src="./output/index_92.jpg" height="200" width="400"> <img src="./output/index_95.jpg" height="200" width="400"><file_sep>/uncertainty.py
"""Visualize uncertainty."""
import collections
import pickle
import gzip
import lasagne as nn
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import theano
import theano.tensor as T
from helpers import load_mnist_data
from mnist_mc_dropout import neural_network, functions
def main(idx, net, data, target, test_function, T=100):
sample = [test_function([data[idx]])[0] for _ in range(T)]
print ("\n\nIndex = {}.".format(idx))
print( np.array(sample))
model_answer = collections.Counter(sample).most_common(1)
print( "Model answer = {}.".format(model_answer))
print ("Correct answer = {}.".format(target[idx]))
height = [sample.count(i) / float(T) for i in range(10)]
left = [i for i in range(10)]
tick_label = [str(i) for i in range(10)]
plt.switch_backend('Agg')
plt.subplot(1, 2, 1)
plt.bar(left=left, height=height, align='center', tick_label=tick_label)
plt.tick_params(axis='y', which='major', labelsize=15)
plt.tick_params(axis='x', which='major', labelsize=20)
plt.subplot(1, 2, 2)
plt.imshow(data[idx].reshape(28,28))
plt.title('{}\n'.format(y_test[idx]), size=22)
plt.axis('off')
plt.savefig('./output/index_{}.eps'.format(idx),format='eps')
plt.savefig('./output/index_{}.jpg'.format(idx),format='jpg')
plt.close()
if __name__ == '__main__':
X_train, y_train, X_val, y_val, X_test, y_test = load_mnist_data()
net = neural_network()
weights = pickle.load(gzip.open('./output/mnist_mc_dropout_weights.pkl.gz', 'rb'))
nn.layers.set_all_param_values(net, weights)
training_function, validation_function, test_function = functions(net)
for idx in range(100):
main(idx, net, X_test, y_test, test_function)<file_sep>/mnist_mc_dropout.py
"""MNIST MC Dropout Model."""
import pickle
import datetime as dt
import gzip
import lasagne as nn
import numpy as np
import os
import sys
import theano
import theano.tensor as T
import time
TITLE = 'mnist_mc_dropout'
OUTPUT_FILE = './output/{}.txt'.format(TITLE)
# Helper functions
from helpers import report, load_mnist_data, generate_batches
def neural_network():
network = nn.layers.InputLayer(shape=(None, 1, 28, 28))
network = nn.layers.DropoutLayer(incoming=network, p=.5, rescale=True)
network = nn.layers.Conv2DLayer(incoming=network, num_filters=32,
filter_size=(5, 5), stride=1, nonlinearity=nn.nonlinearities.rectify)
network = nn.layers.DropoutLayer(incoming=network, p=.5, rescale=True)
network = nn.layers.MaxPool2DLayer(incoming=network, pool_size=(2, 2))
network = nn.layers.DropoutLayer(incoming=network, p=.5, rescale=True)
network = nn.layers.Conv2DLayer(incoming=network, num_filters=32,
filter_size=(5, 5), stride=1, nonlinearity=nn.nonlinearities.rectify)
network = nn.layers.DropoutLayer(incoming=network, p=.5, rescale=True)
network = nn.layers.MaxPool2DLayer(incoming=network, pool_size=(2, 2))
network = nn.layers.DropoutLayer(incoming=network, p=.5, rescale=True)
network = nn.layers.DenseLayer(incoming=network, num_units=500,
nonlinearity=nn.nonlinearities.rectify)
network = nn.layers.DropoutLayer(incoming=network, p=.5, rescale=True)
network = nn.layers.DenseLayer(incoming=network, num_units=10,
nonlinearity=nn.nonlinearities.softmax)
return network
def functions(network):
# Symbolic variables
X = T.tensor4()
Y = T.ivector()
# Non-deterministic training
parameters = nn.layers.get_all_params(layer=network, trainable=True)
output = nn.layers.get_output(layer_or_layers=network, inputs=X,
deterministic=False)
prediction = output.argmax(-1)
loss = T.mean(nn.objectives.categorical_crossentropy(
predictions=output, targets=Y))
accuracy = T.mean(T.eq(prediction, Y))
gradient = T.grad(cost=loss, wrt=parameters)
update = nn.updates.nesterov_momentum(loss_or_grads=gradient,
params=parameters, learning_rate=0.001, momentum=0.9)
training_function = theano.function(
inputs=[X, Y], outputs=[loss, accuracy], updates=update)
# Non-deterministic testing
test_function = theano.function(
inputs=[X], outputs=prediction)
# Deterministic validation
det_output = nn.layers.get_output(layer_or_layers=network, inputs=X,
deterministic=True)
det_prediction = det_output.argmax(-1)
det_loss = T.mean(nn.objectives.categorical_crossentropy(
predictions=det_output, targets=Y))
det_accuracy = T.mean(T.eq(det_prediction, Y))
validation_function = theano.function(
inputs=[X, Y], outputs=[det_loss, det_accuracy])
return training_function, validation_function, test_function
if __name__ == '__main__':
# Record to file instead of printing statements
report('\n\nStarted: {}.'.format(dt.datetime.now()), OUTPUT_FILE)
# Obtain data
X_train, y_train, X_val, y_val, X_test, y_test = load_mnist_data()
report('Data OK.', OUTPUT_FILE)
# Get network
network = neural_network()
report('Network OK.', OUTPUT_FILE)
report('{} parameters'.format(nn.layers.count_params(network)),OUTPUT_FILE)
# Get functions
training_function, validation_function, test_function = functions(network)
report('Functions OK.', OUTPUT_FILE)
# Start training
TL, TA, VL, VA = [], [], [], []
epochs = 3000
batch_size = 500
t_batches = (len(X_train) + (len(X_train) % batch_size)) // batch_size
v_batches = (len(X_val) + (len(X_val) % batch_size)) // batch_size
report('Training...', OUTPUT_FILE)
header = ['Epoch', 'TL', 'TA', 'VL', 'VA', 'Time']
report('{:<10}{:<20}{:<20}{:<20}{:<20}{:<20}'.format(*header), OUTPUT_FILE)
for e in range(epochs):
start_time = time.time()
tl, ta, vl, va = 0., 0., 0., 0.
# Training round
for batch in generate_batches(X_train, y_train, batch_size):
data, targets = batch
l, a = training_function(data, targets)
tl += l
ta += a
tl /= t_batches
ta /= t_batches
TL.append(tl)
TA.append(ta)
# Validation round
for batch in generate_batches(X_val, y_val, batch_size):
data, targets = batch
l, a = validation_function(data, targets)
vl += l
va += a
vl /= v_batches
va /= v_batches
VL.append(vl)
VA.append(va)
row = [e + 1, tl, ta, vl, va, time.time() - start_time]
report('{:<10}{:<20}{:<20}{:<20}{:<20}{:<20}'.format(*row), OUTPUT_FILE)
report('Finished training.', OUTPUT_FILE)
# Save training information
f = gzip.open('./output/{}_info.pkl.gz'.format(TITLE), 'wb')
info = {
'training loss':TL,
'training accuracy':TA,
'validation loss':VL,
'validation accuracy':VA
}
pickle.dump(info, f)
f.close()
report('Saved training info.', OUTPUT_FILE)
# Check model's accuracy on test data
test_loss, test_acc = validation_function(X_test, y_test)
report('Loss on test data: {}'.format(test_loss), OUTPUT_FILE)
report('Accuracy on test data: {}%'.format(test_acc * 100), OUTPUT_FILE)
# Save weights
weights = nn.layers.get_all_params(network)
weights = [np.array(w.get_value()) for w in weights]
f = gzip.open('./output/{}_weights.pkl.gz'.format(TITLE), 'wb')
pickle.dump(weights, f)
f.close()
report('Saved weights.', OUTPUT_FILE)
# Done
report('Completed: {}.'.format(dt.datetime.now()), OUTPUT_FILE) | ca33e71ccd6c05a78889f989be34f4f85931c31e | [
"Markdown",
"Python",
"Shell"
] | 5 | Python | MayarLotfy/mnist_mc | b4b51dda5dcec1800d0d84f9ecfdf914ca99e625 | e35fe30c3fc9a5b64638b93a1c5cecb0d69e1546 |
refs/heads/master | <repo_name>seoyeonny/spring_7<file_sep>/src/main/java/com/fin/s6/JsonController.java
package com.fin.s6;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fin.schedule.ScheduleDTO;
@RestController
public class JsonController {
@RequestMapping(value="/json01")
public String json01(){
return "{\"num\":999}";
}
@RequestMapping(value="/json02")
public Map<String, Object> json02(){
Map<String, Object>map = new HashMap<String, Object>();
map.put("num", 1);
map.put("name","김구라");
return map;
}
@RequestMapping(value="/json03")
public ScheduleDTO json03(){
return null;
}
}
<file_sep>/src/main/java/com/fin/member/MemberService.java
package com.fin.member;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
@Service
public class MemberService {
@Inject
private MemberDAO memberDAO;
public MemberDTO login(MemberDTO memberDTO)throws Exception{
return memberDAO.login(memberDTO);
}
public String nicknameCheck(String nickname)throws Exception{
return memberDAO.nicknameCheck(nickname);
}
}
<file_sep>/src/main/java/com/fin/interceptor/AuthorInterceptor.java
package com.fin.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.fin.member.MemberDTO;
public class AuthorInterceptor extends HandlerInterceptorAdapter{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession();
Object obj=session.getAttribute("member");
boolean check=true;
if(obj == null){
response.sendRedirect(request.getSession().getServletContext().getContextPath());
check=false;
}
// TODO Auto-generated method stub
return check;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
super.postHandle(request, response, handler, modelAndView);
}
}
| 82ed4cfacd8b93d4644028cc1f47ad5deedc7c79 | [
"Java"
] | 3 | Java | seoyeonny/spring_7 | ccd30f1b0296c6ed66eb7767ebd0df59b6633e8b | c5d589f5b6e66326d5d11bb9de0457d86db5b8fc |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using whos_bad.Models;
namespace whos_bad.Controllers
{
public class ComportamentosController : Controller
{
private whosBadDBEntities db = new whosBadDBEntities();
// GET: Comportamentos
public ActionResult Index()
{
var comportamento = db.Comportamento.Include(c => c.Humor).Include(c => c.Sentimento).Include(c => c.Usuario);
return View(comportamento.ToList());
}
// GET: Comportamentos/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Comportamento comportamento = db.Comportamento.Find(id);
if (comportamento == null)
{
return HttpNotFound();
}
return View(comportamento);
}
// GET: Comportamentos/Create
public ActionResult Create()
{
ViewBag.FKHumorId = new SelectList(db.Humor, "HumorId", "Nome");
ViewBag.FKSentimentoId = new SelectList(db.Sentimento, "SentimentoId", "Nome");
ViewBag.FKUserId = new SelectList(db.Usuario, "UserId", "Nome");
return View();
}
[Route("Comportamentos/Cadastrar")]
public ActionResult Cadastrar()
{
int idUsuario = int.Parse(Session["idUsu"].ToString());
//return RedirectToAction("Edit", idUsuario);
return RedirectToRoute(new { controller = "Comportamentos", action = "Create", id = idUsuario });
}
// POST: Comportamentos/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ComportamentoId,NomeDoComportamento,FKSentimentoId,IntensidadeDoSentimento,FKHumorId,FKUserId")] Comportamento comportamento)
{
if (ModelState.IsValid)
{
db.Comportamento.Add(comportamento);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FKHumorId = new SelectList(db.Humor, "HumorId", "Nome", comportamento.FKHumorId);
ViewBag.FKSentimentoId = new SelectList(db.Sentimento, "SentimentoId", "Nome", comportamento.FKSentimentoId);
ViewBag.FKUserId = new SelectList(db.Usuario, "UserId", "Nome", comportamento.FKUserId);
return View(comportamento);
}
// GET: Comportamentos/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Comportamento comportamento = db.Comportamento.Find(id);
if (comportamento == null)
{
return HttpNotFound();
}
ViewBag.FKHumorId = new SelectList(db.Humor, "HumorId", "Nome", comportamento.FKHumorId);
ViewBag.FKSentimentoId = new SelectList(db.Sentimento, "SentimentoId", "Nome", comportamento.FKSentimentoId);
ViewBag.FKUserId = new SelectList(db.Usuario, "UserId", "Nome", comportamento.FKUserId);
return View(comportamento);
}
// POST: Comportamentos/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ComportamentoId,NomeDoComportamento,FKSentimentoId,IntensidadeDoSentimento,FKHumorId,FKUserId")] Comportamento comportamento)
{
if (ModelState.IsValid)
{
db.Entry(comportamento).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FKHumorId = new SelectList(db.Humor, "HumorId", "Nome", comportamento.FKHumorId);
ViewBag.FKSentimentoId = new SelectList(db.Sentimento, "SentimentoId", "Nome", comportamento.FKSentimentoId);
ViewBag.FKUserId = new SelectList(db.Usuario, "UserId", "Nome", comportamento.FKUserId);
return View(comportamento);
}
// GET: Comportamentos/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Comportamento comportamento = db.Comportamento.Find(id);
if (comportamento == null)
{
return HttpNotFound();
}
return View(comportamento);
}
// POST: Comportamentos/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Comportamento comportamento = db.Comportamento.Find(id);
db.Comportamento.Remove(comportamento);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using whos_bad.Models;
namespace whos_bad.Controllers
{
public class RegistrosController : Controller
{
private whosBadDBEntities db = new whosBadDBEntities();
// GET: Registros
public ActionResult Index()
{
var registro = db.Registro.Include(r => r.Usuario);
return View(registro.ToList());
}
// GET: Registros/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Registro registro = db.Registro.Find(id);
if (registro == null)
{
return HttpNotFound();
}
return View(registro);
}
// GET: Registros/Create
public ActionResult Create()
{
ViewBag.FKUserId = new SelectList(db.Usuario, "UserId", "Nome");
ViewBag.FKSentimentoId = new SelectList(db.Humor, "HumorId", "Nome");
ViewBag.FKHumorId = new SelectList(db.Sentimento, "SentimentoId", "Nome");
return View();
}
// POST: Registros/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RegistroId,Contexto,Atitude,FKSentimentoId,FKHumorId,Data,Pensamento,FKUserId")] Registro registro)
{
if (ModelState.IsValid)
{
db.Registro.Add(registro);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FKUserId = new SelectList(db.Usuario, "UserId", "Nome", registro.FKUserId);
ViewBag.FKSentimentoId = new SelectList(db.Humor, "HumorId", "Nome");
ViewBag.FKHumorId = new SelectList(db.Sentimento, "SentimentoId", "Nome");
return View(registro);
}
// GET: Registros/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Registro registro = db.Registro.Find(id);
if (registro == null)
{
return HttpNotFound();
}
ViewBag.FKUserId = new SelectList(db.Usuario, "UserId", "Nome", registro.FKUserId);
ViewBag.FKSentimentoId = new SelectList(db.Humor, "HumorId", "Nome", registro.FKHumorId);
ViewBag.FKHumorId = new SelectList(db.Sentimento, "SentimentoId", "Nome", registro.FKSentimentoId);
return View(registro);
}
// POST: Registros/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "RegistroId,Contexto,Atitude,FKSentimentoId,FKHumorId,Data,Pensamento,FKUserId")] Registro registro)
{
if (ModelState.IsValid)
{
db.Entry(registro).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FKUserId = new SelectList(db.Usuario, "UserId", "Nome", registro.FKUserId);
ViewBag.FKSentimentoId = new SelectList(db.Humor, "HumorId", "Nome", registro.FKHumorId);
ViewBag.FKHumorId = new SelectList(db.Sentimento, "SentimentoId", "Nome", registro.FKSentimentoId);
return View(registro);
}
// GET: Registros/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Registro registro = db.Registro.Find(id);
if (registro == null)
{
return HttpNotFound();
}
return View(registro);
}
// POST: Registros/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Registro registro = db.Registro.Find(id);
db.Registro.Remove(registro);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep># whos-bad
Repositório para desenvolvimento do trabalho da disciplina de laboratório de desenvolvimento de sistemas, onde será criado um software de terapia cognitiva comportamental.
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using whos_bad.Models;
namespace whos_bad.Controllers
{
public class FeedbacksController : Controller
{
private whosBadDBEntities db = new whosBadDBEntities();
// GET: Feedbacks
public ActionResult Index()
{
var feedback = db.Feedback.Include(f => f.Registro);
return View(feedback.ToList());
}
// GET: Feedbacks/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Feedback feedback = db.Feedback.Find(id);
if (feedback == null)
{
return HttpNotFound();
}
return View(feedback);
}
// GET: Feedbacks/Create
public ActionResult Create()
{
return View();
}
// POST: Feedbacks/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "FeedbackId,Texto,Data,FKRegistroId")] Feedback feedback)
{
if (ModelState.IsValid)
{
db.Feedback.Add(feedback);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FKRegistroId = new SelectList(db.Registro, "RegistroId", "Contexto", feedback.FKRegistroId);
return View(feedback);
}
// GET: Feedbacks/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Feedback feedback = db.Feedback.Find(id);
if (feedback == null)
{
return HttpNotFound();
}
ViewBag.FKRegistroId = new SelectList(db.Registro, "RegistroId", "Contexto", feedback.FKRegistroId);
return View(feedback);
}
// POST: Feedbacks/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "FeedbackId,Texto,Data,FKRegistroId")] Feedback feedback)
{
if (ModelState.IsValid)
{
db.Entry(feedback).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FKRegistroId = new SelectList(db.Registro, "RegistroId", "Contexto", feedback.FKRegistroId);
return View(feedback);
}
// GET: Feedbacks/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Feedback feedback = db.Feedback.Find(id);
if (feedback == null)
{
return HttpNotFound();
}
return View(feedback);
}
// POST: Feedbacks/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Feedback feedback = db.Feedback.Find(id);
db.Feedback.Remove(feedback);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using whos_bad.Models;
namespace whos_bad.Controllers
{
public class VisualizaRegistrosController : Controller
{
private whosBadDBEntities db = new whosBadDBEntities();
// GET: VisualizaRegistros
public ActionResult Index()
{
var registro = db.Usuario.Where(e => e.Perfil == "Paciente").ToList();
return View(registro.ToList());
}
public ActionResult Feedbacks(int? id)
{
Session["FKRegistroId"] = id;
return RedirectToAction("Create", "Feedbacks");
}
// GET: VisualizaRegistros/Details/5
public ActionResult registros(int? id)
{
var registro = db.Registro.Where(e => e.FKUserId == id).ToList();
return View(registro.ToList());
}
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Registro registro = db.Registro.Find(id);
if (registro == null)
{
return HttpNotFound();
}
return View(registro);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using whos_bad.Models;
namespace whos_bad.Controllers
{
public class LoginController : Controller
{
private whosBadDBEntities db = new whosBadDBEntities();
// GET: Login
public ActionResult Autenticar()
{
return View();
}
[HttpPost]
public ActionResult Autenticar(string login, string senha)
{
try
{
Usuario usu = db.Usuario.Where(e => e.NomeDeUsuario == login).First();
string senhaUsu = usu.Senha.Split(' ')[0];
if (senhaUsu == senha)
{
Session["idUsu"] = usu.UserId;
Session["NomeUsu"] = usu.Nome;
Session["perfil"] = usu.Perfil;
Session["erro"] = "";
return RedirectToAction("Index", "Home");
}
else
{
Session["erro"] = "Usuário e/ou senha digitados são inválidos.";
return View();
}
}
catch
{
Session["idUsu"] = null;
Session["NomeUsu"] = null;
Session["perfil"] = null;
Session["erro"] = "O usuário informado não existe";
return View();
}
}
public ActionResult Cadastrar()
{
return View();
}
[Route("Login/Logout")]
public ActionResult Logout()
{
Session["idUsu"] = null;
Session["NomeUsu"] = null;
Session["perfil"] = null;
Session["erro"] = null;
return RedirectToAction("Index", "Home");
}
}
} | 41694b485913d0e94ab2a39ca60c57f72ab89aa0 | [
"Markdown",
"C#"
] | 6 | C# | felipesena/whos-bad | 676d10a593063b5d0ab4ca1fa778a945ca8df8b6 | 53c128bde7d0eba6257aa5c263e1677fe1808002 |
refs/heads/master | <file_sep>function clc(info, tab) {
chrome.tabs.create({url:`https://www.seslisozluk.net/${info.selectionText}-nedir-ne-demek/`});
}
var contexts = ["selection"];
for (var i = 0; i < contexts.length; i++) {
var context = contexts[i];
var title = chrome.i18n.getMessage("conTitle");
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
"onclick": clc});
}
<file_sep># chrome-seslisozluk
Select a word then open context menu to search with Seslisözlük.
Have a good time!..
| 946b1f849e49d530e4621872d04859f42583fd04 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | atahabaki/chrome-seslisozluk | b0031effe05c3b725b20e5cebd8d2476c107fed7 | a71be256941423eb7818eb4c759d242b4564b7b2 |
refs/heads/master | <repo_name>ExiledNarwal28/Cpp_TP_Divers<file_sep>/royf_TP4_final/TP4/Source.cpp
// Auteur : <NAME>
// Programme : TP4, programme d'utilisation de la librairie STL
// Date de début : 12 décembre 2015
// Date de fin : 12 décembre 2015
#include <iostream>
#include <vector>
#include <deque>
#include <algorithm>
using namespace std;
void remplirVecteur(vector<int> &); // numero 1, fonction qui place des elements (lu au clavier) dans un vecteur
// numero 2, voir foncteur augmenterNoteFoncteur
// numero 3, voir lambda transfertDequeLambda
void transformerDeque(deque<int> &); // numero 4, fonction qui "inverse" les elements d'un deque et qui les place en ordre decroissant
template <typename T> void affichage(T); // affichage de vecteur ou de deque
void ieMenu(); // image ecran
class augmenterNoteFoncteur // class foncteur, augmente la valeur d'un element de vecteur avec une valeur entree au clavier
{
public :
void operator() (vector<int> &recuVecteur) // reception d'un vecteur par reference
{
int pos, // position de l'element a changer
plus; // nombre a ajouter a l'element
if (!recuVecteur.empty()) // si le vecteur n'est pas vide...
{
cout << "Pre-affichage du vecteur : "; affichage(recuVecteur);
cout << endl << endl << "Quelle est la position dans la liste de la note a augmenter ? "; cin >> pos; // on entre la position de l'element
cout << "La position " << pos << " : " << recuVecteur[pos - 1]; // on l'affiche
cout << endl << endl << "De combien voulez-vous l'augmenter ? "; cin >> plus; // on entre le nombre a ajouter
recuVecteur[pos - 1] += plus; // l'addition
cout << endl << "Post-affichage du vecteur : "; affichage(recuVecteur);
}
else
cout << "Le vecteur est vide, operation impossible.";
}
};
int main()
{
vector<int> notesVecteur; // vecteur des notes
deque<int> notesDeque; // deque des notes
int choixMenu = 5;
auto transfertDequeLambda = [](vector<int> recuVecteur, deque<int> &recuDeque) // lambda qui transfert certaines valeur d'un vecteur a un deque, le vecteur est par valeur, le deque par reference
{
if (!recuVecteur.empty()) // si le vecteur n'est pas vide...
{
cout << "Pre-affichage du vecteur : "; affichage(recuVecteur);
cout << endl << "Pre-affichage du deque : "; affichage(recuDeque);
for (auto i = recuVecteur.begin(); i != recuVecteur.end(); ++i) // tout au long du vecteur...
{
if (*i >= 60 && *i <= 80 && !(*i % 2)) // si l'element est entre 60 et 80, et qu'il est pair...
{
recuDeque.push_back(*i); // on le place dans le deque
}
}
cout << endl << endl << "Post-affichage du vecteur : "; affichage(recuVecteur);
cout << endl << "Post-affichage du deque : "; affichage(recuDeque);
}
else
cout << "Le vecteur est vide, operation impossible.";
};
do
{
ieMenu();
cin >> choixMenu;
switch (choixMenu)
{
case 1:
cout << endl << endl << "---> REMPLISSAGE DE VECTEUR" << endl << endl;
remplirVecteur(notesVecteur);
cout << endl << endl;
system("pause");
break;
case 2:
cout << endl << endl << "---> AUGMENTATION DE NOTE FINALE" << endl << endl;
augmenterNoteFoncteur foncteur; foncteur(notesVecteur);
cout << endl << endl;
system("pause");
break;
case 3:
cout << endl << endl << "---> TRANSFERT DE DONNEES DANS UN DEQUE" << endl << endl;
transfertDequeLambda(notesVecteur, notesDeque);
cout << endl << endl;
system("pause");
break;
case 4:
cout << endl << endl << "---> TRANSFORMATION DES NOTES DU DEQUE" << endl << endl;
transformerDeque(notesDeque);
cout << endl << endl;
system("pause");
break;
}
} while (choixMenu != 5); // choisir 5 fait sortir du programme
cout << endl << endl;
system("pause");
return 0;
}
void remplirVecteur(vector<int> &recuVecteur) // reception d'un vecteur par reference
{
int nbNotes, // le nombre de note a entrer
note; // la note entrée
cout << "Pre-affichage du vecteur : "; affichage(recuVecteur);
cout << endl << endl << "Combien de notes voulez-vous entrer ? "; cin >> nbNotes; cout << endl; // on entre le nombre de note a entrer
for (int i = 0; i < nbNotes; i++) // pour le nombre de notes a entrer...
{
cout << "Note " << i + 1 << '/' << nbNotes << ": "; cin >> note; // on entre une note
recuVecteur.push_back(note); // et on la place dans le vecteur
}
cout << endl << "Post-affichage du vecteur : "; affichage(recuVecteur);
}
void transformerDeque(deque<int> &recuDeque) // reception d'un deque par reference
{
if (!recuDeque.empty()) // si le deque n'est pas vide...
{
cout << "Pre-affichage du deque : "; affichage(recuDeque);
// ce for bizarre permet d'"inverser" les nombres, soit rentre 76->67, 80->8 (08), 45->54, ...
for (auto i = recuDeque.begin(); i != recuDeque.end(); ++i) // tout au long du deque...
{
int j = 0; // on instancie cette jolie variable
while (*i) // tant que l'element n'est pas 0
{
j *= 10; j += *i % 10; *i /= 10; // on multipilie j a lui meme et 10, on addition j a lui même et le reste de l'element divisé par 10 et on divise l'element par lui-même et 10.
}
*i = j; // cela fait en sorte que j est le nombre "inversé" qu'on place a la place de l'ancien element
}
cout << endl << "Intra-affichage du deque : "; affichage(recuDeque);
sort(recuDeque.begin(), recuDeque.end()); // on place le deque en ordre croissant
reverse(recuDeque.begin(), recuDeque.end()); // puis on l'inverse, ce qui fait un ordre decroissant
cout << endl << "Post-affichage du deque : "; affichage(recuDeque);
}
else
cout << "Le deque est vide, operation impossible.";
}
template <typename T> void affichage(T recu) // reception d'un vecteur ou un deque par valeur
{
if (!recu.empty()) // si la reception n'est pas vide...
{
for (auto i = recu.begin(); i != recu.end(); ++i) // on l'affiche
std::cout << *i << ' ';
}
else
cout << "Aucun element";
}
void ieMenu()
{
cout << endl << endl << "---> MENU PRINCIPAL" << endl << endl << endl;
cout << "1. Remplir un vecteur de notes etudiantes." << endl;
cout << "2. Utiliser un foncteur pour augmenter une note finale." << endl;
cout << "3. Utiliser une fonction lambda pour transferer des donnees dans un deque." << endl;
cout << "4. Se servir d'un algorithme pour transformer les notes du deque. " << endl << endl;
cout << "5. Quitter" << endl << endl;
cout << endl << "Votre choix : ";
}<file_sep>/README.md
# Cpp_TP_Divers
Ceci est le dernier travail pratique de mon cours de C++. Le but était de maîtriser l'ensemble des connaissances apprises dans le cours.
Le travail etait de 4 numéros :
1-Placer des notes entrées au clavier dans un vecteur.
2-Utiliser un foncteur (classe qui redefinit les opérateurs ()) pour augmenter une note.
3-Utiliser un lambda pour transformer le vecteur en deque.
4-Mettre le elements (integers) du deque en ordre inversé.
| 4f91a4cc8299746902c58ce0753953bbdbb08976 | [
"Markdown",
"C++"
] | 2 | C++ | ExiledNarwal28/Cpp_TP_Divers | 36a9cdfe4504275a4d0b2a9bafb75ca083a8edf0 | 7446e701aef9f8747b950e0828d43247e6e4bf85 |
refs/heads/master | <file_sep># Linked List
A terminal prompt to interact with a linked list.
## Running
To run the program, just open the terminal in the same folder and enter command:
```
$ make
```
<file_sep>#ifndef LINKED_LIST
#define LINKED_LIST
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
int content;
struct node *next;
} Node;
void run_prompt();
void linked_list(Node *list, char *command, int number);
#endif<file_sep>#include "linked_list.h"
void run_prompt()
{
printf("\nWelcome!\nType \"help\" to check available commands.\n\n");
char command[30];
char number[4];
Node *list;
list = (Node *) malloc(sizeof(Node));
list->next = NULL;
while(1)
{
printf("prompt-> ");
fscanf (stdin, "%s", command);
fgets (number, 100, stdin);
if(strcmp(command, "exit") == 0) break;
linked_list(list, command, atoi(number));
printf("\n\n");
}
return;
}
void help()
{
printf("\nCOMMANDS:\n\n");
printf("help \t\t\t- Shows this help.\n");
printf("put [number] \t\t- Insert a value in the list.\n");
printf("get [number] \t\t- Gets the value of a given position.\n");
printf("remove [position] \t- Removes the element in the given position.\n");
printf("list \t\t\t- Prints the entire list.\n");
printf("first \t\t\t- Prints the first content of the list.\n");
printf("last \t\t\t- Prints the lat content of the list.\n");
printf("sort \t\t\t- Runs Bubble Sort in the list.\n");
printf("exit \t\t\t- Closes the prompt.\n");
return;
}
int is_empty (Node *n) {
return n->next == NULL ? 1 : 0;
}
void print_list(Node *n)
{
if(is_empty(n))
{
printf("LIST IS EMPTY");
return;
};
Node *p;
for (p = n->next; p != NULL; p = p->next)
printf ("%d ", p->content);
return;
}
int list_length = 0;
void add_node(Node *n, int content)
{
Node *new_node, *p;
new_node = (Node *) malloc(sizeof(Node));
new_node->content = content;
new_node->next = NULL;
if(is_empty(n)) n->next = new_node;
else
{
for (p = n->next; p != NULL; p = p->next)
{
if(p->next == NULL)
{
p->next = new_node;
break;
}
}
}
list_length++;
return;
}
void get_content(Node *n, int position)
{
if(is_empty(n))
{
printf("LIST IS EMPTY");
return;
}
Node *p;
int i = 1;
for (p = n->next; p != NULL; p = p->next)
{
if(i == position)
{
printf ("%d", p->content);
break;
}
i++;
}
if(i < position) printf("LIST LENGTH IS %d", i-1);
return;
}
void remove_node(Node *n, int position)
{
if(is_empty(n)) return;
if(position > list_length) {printf("LIST LENGTH IS %d\n", list_length); return;}
Node *p, *wanted_node;
int i = 0;
for (p = n; p != NULL; p = p->next)
{
if(i+1 == position)
{
wanted_node = p->next;
printf ("%d\n", wanted_node->content);
p->next = wanted_node->next;
free(wanted_node);
list_length--;
break;
}
i++;
}
return;
}
void clear_list(Node *n)
{
Node *p, *q;
p = n->next;
while(p != NULL)
{
q = p->next;
free(p);
p = q;
}
n->next = NULL;
}
void swap(Node *p, Node *q)
{
int temp = p->content;
p->content = q->content;
q->content = temp;
}
void bubbleSort(Node *n)
{
// Se lista vazia, retorna
if (is_empty(n)) return;
Node *p;
Node *prev = NULL;
int swapped;
do
{
swapped = 0;
p = n->next;
while (p->next != prev)
{
if (p->content > p->next->content)
{
swap(p, p->next);
swapped = 1;
}
p = p->next;
}
prev = p;
}
while (swapped);
}
void linked_list(Node *list, char *command, int number)
{
if(strcmp(command, "help") == 0)
{
help();
}
else if(strcmp(command, "list") == 0)
print_list(list);
else if(strcmp(command, "put") == 0)
{
add_node(list, number);
print_list(list);
}
else if(strcmp(command, "get") == 0)
{
get_content(list, number);
}
else if(strcmp(command, "first") == 0)
{
get_content(list, 1);
}
else if(strcmp(command, "last") == 0)
{
get_content(list, list_length);
}
else if(strcmp(command, "remove") == 0)
{
remove_node(list, number);
print_list(list);
}
else if(strcmp(command, "clear") == 0)
{
// while(!is_empty(list)) remove_node(list, 1);
clear_list(list);
print_list(list);
}
else if(strcmp(command, "sort") == 0)
{
bubbleSort(list);
print_list(list);
}
else printf("COMMAND NOT FOUND");
return;
}<file_sep>#include <stdio.h>
#include "linked_list.h"
int main()
{
run_prompt();
return 0;
}
<file_sep>all: compile run
clearscreen:
clear
clean:
echo 0 > prompt.hex && rm prompt.hex
compile: clean
gcc main.c linked_list.c -o prompt.hex
run: compile
clear &&./prompt.hex | ef25aa5c3b0657609e791f0a87524ffed0575906 | [
"Markdown",
"C",
"Makefile"
] | 5 | Markdown | rhobernardi/linked-list | a9d6d636eaa4a7de448b9d88fd451c38809d0986 | 070f7f7d2061431316db52f14fcd60ed3ac6a5fa |
refs/heads/master | <repo_name>davicillo/Arduino_DHT22<file_sep>/DHT_console/DHT_console.ino
#include <DHT.h>
#include <Process.h>
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
Process date;
YunServer server;
void setup() {
Bridge.begin(); // initialize Bridge
Serial.begin(9600);
dht.begin();
// Listen for incoming connection only from localhost
// (no one from the external network could connect)
server.listenOnLocalhost();
server.begin();
}
void loop() {
// Get clients coming from server
YunClient client = server.accept();
date.begin("/bin/date");
date.addParameter("+%d/%m/%Y %T");
date.run();
//if there's a result from the date process, get it.
while (date.available()>0) {
String timeString = date.readString();
// print the results we got.
Serial.print(timeString);
Serial.print("-->");
}
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(", ");
Serial.print(f);
Serial.println(" *F ");
if (client) {
// read the command
String command = client.readString();
command.trim(); //kill whitespace
Serial.println(command);
// is "temperature" command?
if (command == "temperature") {
client.print("Humidity: ");
client.print(h);
client.print(" %\t");
client.print("Temperature: ");
client.print(t);
client.print(" *C ");
client.print(", ");
client.print(f);
client.println(" *F ");
}
client.stop();
}
// Wait a few seconds between measurements.
delay(5000);
}
<file_sep>/DHT_web/DHT_web.ino
#include <DHT.h>
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
YunServer server;
void setup() {
Bridge.begin(); // initialize Bridge
Serial.begin(9600);
dht.begin();
// Listen for incoming connection only from localhost
// (no one from the external network could connect)
server.listenOnLocalhost();
server.begin();
}
void loop() {
// Get clients coming from server
YunClient client = server.accept();
if (client) {
// read the command
String command = client.readString();
command.trim(); //kill whitespace
Serial.println(command);
// is "temperature" command?
if (command == "temperature") {
// get the time from the server:
Process time;
time.runShellCommand("date");
String timeString = "";
while(time.available()) {
char c = time.read();
timeString += c;
}
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
float f = dht.readTemperature(true);
client.print("Current time on the Yún: ");
client.println(timeString);
client.print("Humidity: ");
client.print(h);
client.print(" %\t");
client.print("Temperature: ");
client.print(t);
client.print(" *C ");
client.print(", ");
client.print(f);
client.println(" *F ");
}
client.stop();
}
// Wait a few seconds between measurements.
delay(500);
}
<file_sep>/DHT_thingspeak/DHT_thingspeak.ino
#include <Bridge.h>
#include <Console.h>
#include <Process.h>
#include <DHT.h>
#define ARRAY_SIZE 3
#define DHTPIN 2
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Bridge.begin();
Console.begin();
};
void postToThingSpeak(String key, float value[]) {
Process p;
String cmd = "curl --data \"key="+key;
for (int i=0;i<ARRAY_SIZE;i++) {
cmd = cmd + "&field"+ (i+1) + "=" + value[i];
}
cmd = cmd + "\" http://api.thingspeak.com/update";
p.runShellCommand(cmd);
Console.println(cmd);
p.close();
}
void loop() {
float vol[ARRAY_SIZE];
vol[0] = dht.readTemperature();
vol[1] = dht.readTemperature(true);
vol[2] = dht.readHumidity();
postToThingSpeak("",vol);
delay(30*60000);
}
| 16059d2a438c7b13370b5ab8d60ae5c3b4b99c45 | [
"C++"
] | 3 | C++ | davicillo/Arduino_DHT22 | 235034ae5a15ee8f0d5ebeb4a7a749158e69c2db | b0baa3db702e5db186508920151883cb0b910bfb |
refs/heads/master | <repo_name>PAVv1/DSP-lab-b13-roll28<file_sep>/L6-linked_list.py
"""<NAME>
121910313028"""
#Create a linked list with few sample nodes as static inputs
class Node:
def _init_(self, data):
self.data = data
self.next = None
class SLinkedList:
def _init_(self):
self.head = None
def listprint(self):
printv = self.head
while printv is not None:
print (printv.data)
printv = printv.next
#Programming execution starts here
list = SLinkedList()
list.head = Node(1)
w2 = Node(2)
w3 = Node(3)
w4= Node(4)
w5=Node(5)
# Link first Node to second node
list.head.next = w2
# Link second Node to third node
w2.next = w3
w3.next = w4
w4.next=w5
list.listprint() | 944492df808ea69c6fed0832bf5658d281823d02 | [
"Python"
] | 1 | Python | PAVv1/DSP-lab-b13-roll28 | 2a5172698e5ab49095ac2b17e03188aabbe5dc5f | 31c0e7764db97776bb103e5d197f351f3049f462 |
refs/heads/master | <file_sep># useful-php-functions
commonly useful php functions
<file_sep><?php
function get_domain($domain, $debug = false)
{
$original = $domain = strtolower($domain);
if (filter_var($domain, FILTER_VALIDATE_IP)) { return $domain; }
$debug ? print('<strong style="color:green">»</strong> Parsing: '.$original) : false;
$arr = array_slice(array_filter(explode('.', $domain, 4), function($value){
return $value !== 'www';
}), 0); //rebuild array indexes
if (count($arr) > 2)
{
$count = count($arr);
$_sub = explode('.', $count === 4 ? $arr[3] : $arr[2]);
$debug ? print(" (parts count: {$count})") : false;
if (count($_sub) === 2) // two level TLD
{
$removed = array_shift($arr);
if ($count === 4) // got a subdomain acting as a domain
{
$removed = array_shift($arr);
}
$debug ? print("<br>\n" . '[*] Two level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false;
}
elseif (count($_sub) === 1) // one level TLD
{
$removed = array_shift($arr); //remove the subdomain
if (strlen($_sub[0]) === 2 && $count === 3) // TLD domain must be 2 letters
{
array_unshift($arr, $removed);
}
else
{
// non country TLD according to IANA
$tlds = array(
'aero',
'arpa',
'asia',
'biz',
'cat',
'com',
'coop',
'edu',
'gov',
'info',
'jobs',
'mil',
'mobi',
'museum',
'name',
'net',
'org',
'post',
'pro',
'tel',
'travel',
'xxx',
);
if (count($arr) > 2 && in_array($_sub[0], $tlds) !== false) //special TLD don't have a country
{
array_shift($arr);
}
}
$debug ? print("<br>\n" .'[*] One level TLD: <strong>'.join('.', $_sub).'</strong> ') : false;
}
else // more than 3 levels, something is wrong
{
for ($i = count($_sub); $i > 1; $i--)
{
$removed = array_shift($arr);
}
$debug ? print("<br>\n" . '[*] Three level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false;
}
}
elseif (count($arr) === 2)
{
$arr0 = array_shift($arr);
if (strpos(join('.', $arr), '.') === false
&& in_array($arr[0], array('localhost','test','invalid')) === false) // not a reserved domain
{
$debug ? print("<br>\n" .'Seems invalid domain: <strong>'.join('.', $arr).'</strong> re-adding: <strong>'.$arr0.'</strong> ') : false;
// seems invalid domain, restore it
array_unshift($arr, $arr0);
}
}
$debug ? print("<br>\n".'<strong style="color:gray">«</strong> Done parsing: <span style="color:red">' . $original . '</span> as <span style="color:blue">'. join('.', $arr) ."</span><br>\n") : false;
return join('.', $arr);
}
function get_subdomain($input){
if (preg_match('/^[a-zA-Z\-\.0-9]+$/', $input)){
$domain = get_domain($input);
$domstart = strrpos($input, $domain);
if ($domstart){
return substr($input, 0, $domstart-1);
} else {
return '';
}
} else {
return '';
}
}
?><?php
//
// BELOW:
// TESTS FOR getDomainParts()
//
$urls = array(
'www.example.com' => 'example.com',
'example.com' => 'example.com',
'example.com.br' => 'example.com.br',
'www.example.com.br' => 'example.com.br',
'www.example.gov.br' => 'example.gov.br',
'localhost' => 'localhost',
'www.localhost' => 'localhost',
'subdomain.localhost' => 'localhost',
'www.subdomain.example.com' => 'example.com',
'subdomain.example.com' => 'example.com',
'subdomain.example.com.br' => 'example.com.br',
'www.subdomain.example.com.br' => 'example.com.br',
'www.subdomain.example.biz.br' => 'example.biz.br',
'subdomain.example.biz.br' => 'example.biz.br',
'subdomain.example.net' => 'example.net',
'www.subdomain.example.net' => 'example.net',
'www.subdomain.example.co.kr' => 'example.co.kr',
'subdomain.example.co.kr' => 'example.co.kr',
'example.co.kr' => 'example.co.kr',
'example.jobs' => 'example.jobs',
'www.example.jobs' => 'example.jobs',
'subdomain.example.jobs' => 'example.jobs',
'insane.subdomain.example.jobs' => 'example.jobs',
'insane.subdomain.example.com.br' => 'example.com.br',
'www.doubleinsane.subdomain.example.com.br' => 'example.com.br',
'www.subdomain.example.jobs' => 'example.jobs',
'test' => 'test',
'www.test' => 'test',
'subdomain.test' => 'test',
'www.detran.sp.gov.br' => 'sp.gov.br',
'www.mp.sp.gov.br' => 'sp.gov.br',
'ny.library.museum' => 'library.museum',
'www.ny.library.museum' => 'library.museum',
'ny.ny.library.museum' => 'library.museum',
'www.library.museum' => 'library.museum',
'info.abril.com.br' => 'abril.com.br',
'127.0.0.1' => '127.0.0.1',
'::1' => '::1',
);
$suburls = array(
'www.example.com' => 'www',
'example.com' => '',
'example.com.br' => '',
'www.example.com.br' => 'www',
'www.example.gov.br' => 'www',
'localhost' => '',
'www.localhost' => 'www',
'subdomain.localhost' => 'subdomain',
'www.subdomain.example.com' => 'www.subdomain',
'subdomain.example.com' => 'subdomain',
'subdomain.example.com.br' => 'subdomain',
'www.subdomain.example.com.br' => 'www.subdomain',
'www.subdomain.example.biz.br' => 'www.subdomain',
'subdomain.example.biz.br' => 'subdomain',
'subdomain.example.net' => 'subdomain',
'www.subdomain.example.net' => 'www.subdomain',
'www.subdomain.example.co.kr' => 'www.subdomain',
'subdomain.example.co.kr' => 'subdomain',
'example.co.kr' => '',
'example.jobs' => '',
'www.example.jobs' => 'www',
'subdomain.example.jobs' => 'subdomain',
'insane.subdomain.example.jobs' => 'insane.subdomain',
'insane.subdomain.example.com.br' => 'insane.subdomain',
'www.doubleinsane.subdomain.example.com.br' => 'www.doubleinsane.subdomain',
'www.subdomain.example.jobs' => 'www.subdomain',
'test' => '',
'www.test' => 'www',
'subdomain.test' => 'subdomain',
'www.detran.sp.gov.br' => 'www.detran',
'www.mp.sp.gov.br' => 'www.mp',
'ny.library.museum' => 'ny',
'www.ny.library.museum' => 'www.ny',
'ny.ny.library.museum' => 'ny.ny',
'www.library.museum' => 'www',
'info.abril.com.br' => 'info',
'127.0.0.1' => '',
'::1' => '',
);
echo '<h1>Domain Tests</h1>';
foreach ($urls as $goodinput => $goodoutput) {
$myoutput = get_domain($goodinput);
if ($myoutput == $goodoutput){
echo $myoutput.' == '.$goodoutput.'? <b style="color:green;">YES</b><br>';
} else {
echo $myoutput.' == '.$goodoutput.'? <b style="color:red;">NOPE</b><br>';
}
echo '<br>';
}
echo '<h1>Subdomain Tests</h1>';
foreach ($suburls as $goodinput => $goodoutput) {
$myoutput = get_subdomain($goodinput);
if ($myoutput == $goodoutput){
echo $myoutput.' == '.$goodoutput.'? <b style="color:green;">YES</b><br>';
} else {
echo $myoutput.' == '.$goodoutput.'? <b style="color:red;">NOPE</b><br>';
}
echo '<br>';
}
?>
<style>body{background: black;color: white;}</style>
| 67c3c95749e57daacf9469e88f85981792b5b728 | [
"Markdown",
"PHP"
] | 2 | Markdown | qls0ulp/useful-php-functions | 93f5d2d8c25d71e38c18a9b6b9d5e18f69281978 | e94bca51aa83c330c8776e3b991a6267e414eb16 |
refs/heads/master | <repo_name>IndraTensei/DataBaseProject<file_sep>/sql/ddl.sql
DROP TABLE IF EXISTS CUSTOMER CASCADE;
DROP TABLE IF EXISTS BOOK CASCADE;
DROP TABLE IF EXISTS PURCHASE CASCADE;
DROP TABLE IF EXISTS PUBLISHING_HOUSE CASCADE;
DROP TABLE IF EXISTS BOOK_SHOP CASCADE;
DROP TABLE IF EXISTS BOOK_X_BOOK_SHOP CASCADE;
DROP TABLE IF EXISTS BOOK_X_PUBLISHING_HOUSE CASCADE;
DROP TABLE IF EXISTS PURCHASE_X_BOOK CASCADE;
DROP TABLE IF EXISTS EMPLOYEE CASCADE;
CREATE TABLE IF NOT EXISTS CUSTOMER(
CUSTOMER_ID INT PRIMARY KEY,
CUSTOMER_NM VARCHAR(30) NOT NULL,
CUSTOMER_SURNAME_NM VARCHAR(30) NOT NULL,
LAST_PURCHASE_DTTM TIMESTAMP(0) NOT NULL,
FIRST_PURCHASE_DTTM TIMESTAMP(0) NOT NULL,
CUSTOMER_PHONE_NO VARCHAR(50) UNIQUE
);
CREATE TABLE IF NOT EXISTS BOOK_SHOP(
SHOP_ID INT PRIMARY KEY,
SHOP_ADDRESS VARCHAR(100) UNIQUE,
WORK_DAY_START TIME NOT NULL,
WORK_DAY_FINISH TIME NOT NULL,
OPENING_DATE DATE NOT NULL,
SHOP_PHONE_NO VARCHAR(50) UNIQUE
);
CREATE TABLE IF NOT EXISTS PURCHASE(
PURCHASE_ID INT PRIMARY KEY,
CUSTOMER_ID INT REFERENCES CUSTOMER(CUSTOMER_ID),
SHOP_ID INT REFERENCES BOOK_SHOP(SHOP_ID),
PURCHASE_DTTM TIMESTAMP(0) NOT NULL,
COST_AMT INT NOT NULL,
PURCHASE_DISCOUNT_FLG BOOLEAN DEFAULT FALSE
);
CREATE TABLE IF NOT EXISTS BOOK(
BOOK_ID INT PRIMARY KEY,
AUTHOR_NM VARCHAR(30) ,
AUTHOR_SURNAME_NM VARCHAR(30),
AUTHOR_ID INT NOT NULL,
BOOK_NM VARCHAR(50) NOT NULL,
BOOK_PRICE_AMT INT,
BOOK_GENRE_TXT VARCHAR(50)
);
CREATE TABLE IF NOT EXISTS PUBLISHING_HOUSE(
HOUSE_ID INT PRIMARY KEY,
HOUSE_NM VARCHAR(100) NOT NULL,
FOUNDING_DT DATE NOT NULL,
HOUSE_CHIEF_NM VARCHAR(30) NOT NULL,
HOUSE_CHIEF_SURNAME_NM VARCHAR(30) NOT NULL,
PUBLISHING_PHONE_NO VARCHAR(50) UNIQUE
);
CREATE TABLE IF NOT EXISTS EMPLOYEE(
EMPLOYEE_ID INT ,
EMPLOYEE_TYPE VARCHAR(100) ,
SHOP_ID INT REFERENCES BOOK_SHOP(SHOP_ID),
EMPLOYEE_NM VARCHAR(50) NOT NULL,
EMPLOYEE_SURNAME_NM VARCHAR(50) NOT NULL,
EMPLOYEE_PHONE_NO VARCHAR(50) UNIQUE,
UNIQUE(EMPLOYEE_ID,EMPLOYEE_TYPE)
);
CREATE TABLE IF NOT EXISTS PURCHASE_X_BOOK(
PURCHASE_ID INT REFERENCES PURCHASE(PURCHASE_ID),
BOOK_ID INT REFERENCES BOOK(BOOK_ID)
);
CREATE TABLE IF NOT EXISTS BOOK_X_BOOK_SHOP(
SHOP_ID INT REFERENCES BOOK_SHOP(SHOP_ID),
BOOK_ID INT REFERENCES BOOK(BOOK_ID)
);
CREATE TABLE IF NOT EXISTS BOOK_X_PUBLISHING_HOUSE(
BOOK_ID INT REFERENCES BOOK(BOOK_ID),
HOUSE_ID INT REFERENCES PUBLISHING_HOUSE(HOUSE_ID)
);
| 9b2ec9dc57b50dae9453f7eed5a339de0c015c5d | [
"SQL"
] | 1 | SQL | IndraTensei/DataBaseProject | 32cc0d24871de8cf8b977074821c202f2ed8779b | 463cd573c83f4195dc03c222c68ee3bbdf95f88b |
refs/heads/master | <repo_name>vanphattran/wittwitt<file_sep>/README.md
# wittwitt
Angularjs/MeteorJS
<file_sep>/client/catalogs/controllers/catalogDetailController.js
(function () {
angular.module('wittwitt').controller('catalogDetailController', ['$meteor', '$scope', '$stateParams',
function ($meteor, $scope, $stateParams) {
$scope.catalogId = $stateParams.id;
$scope.catalog = $meteor.object(Catalogs, $stateParams.id, false);
$scope.save = function () {
$scope.catalog.save();
};
$scope.cancel = function () {
$scope.catalog.reset();
}
}]);
})();<file_sep>/model/catalogs.js
Catalogs = new Mongo.Collection("catalogs");
// http://docs.meteor.com/#/basic/Mongo-Collection-allow
Catalogs.allow({
insert: function (userId, catalog) {
return userId && catalog.owner === userId;
},
update: function (userId, catalog, fields, modifier) {
return !(userId !== catalog.owner);
},
remove: function (userId, catalog) {
return !(userId !== catalog.owner);
}
});<file_sep>/client/catalogs/controllers/catalogListController.js
(function () {
angular.module("wittwitt").controller("catalogListController", ['$scope', '$meteor',
function ($scope, $meteor) {
$scope.catalogs = $meteor.collection(Catalogs);
$scope.add = function () {
$scope.newCatalog.owner = $scope.$root.currentUser._id;
$scope.catalogs.push($scope.newCatalog);
$scope.newCatalog = '';
};
$scope.remove = function (catalog) {
$scope.catalogs.remove(catalog);
};
$scope.removeAll = function () {
$scope.catalogs.remove();
};
}]);
})(); | 6d6fd2cfc0fe284cfa77a128c3f31bde52c34365 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | vanphattran/wittwitt | 5a58dca25e2471d992e2efb83386a2823b593b1d | 889ab7dc8085ee4f81fe107c86fc91a2b5a31509 |
refs/heads/master | <file_sep>from flask import Flask, request, render_template
import random
import requests
import ipdb
import pickle
from main import tf_idf, stop_list, describe_nmf_results, nmf_model2,reconst_mse
import numpy as np
import main
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
# import ipdb; ipdb.set_trace()
global message_body
global message_URL
global feature_words
global document_term_mat
message_body = None
message_URL = None
feature_words = None
document_term_mat = None
# Initialize the app and load the pickled data.
#================================================
# init flask app
app = Flask(__name__)
data_dict = pickle.load(open('data/data_dict_df.pkl', 'r'))
products = data_dict.keys()
@app.context_processor
def inject_enumerate():
return dict(enumerate=enumerate)
# Homepage with form on it.
#================================================
@app.route('/')
def index():
return render_template('jumbotron.html', title='Welcome!', products=products)
#================================================
@app.route('/topics', methods=['POST'])
def topics():
# get data from request form
data = request.form['productname']
#keys = '\n'.join([k for k in request.form])
# convert data from unicode to string
data = str(data)
df = data_dict[data]
global message_body
message_body = df['Message Body No HTML']
global message_URL
message_URL = df['Message URL']
df_side_feat = df[['Replies/Comments','Number of Views']]
global feature_words
global document_term_mat
vectorizer, document_term_mat, feature_words = tf_idf(stop_list(),message_body)
n_features = 15
n_topics = 5
n_top_words = 10
W_sklearn, H_sklearn = nmf_model2(n_topics,document_term_mat)
topics_num = []
words = []
for topic_num, topic in enumerate(H_sklearn):
topics_num.append("Topic number %d:" % topic_num)
words.append(" ".join([feature_words[i] for i in topic.argsort()[:-n_top_words - 1:-1]]))
return render_template('jumbotron0.html', product_name=data, topics=zip(topics_num,words),\
feature_words=feature_words)
@app.route('/keyword', methods=['POST'])
def keyword():
# get data from request form
issue_question = request.form['keyword']
# keys = '\n'.join([k for k in request.form])
# convert data from unicode to string
issue_question = str(issue_question)
topic_num = request.form['topic']
num_posts = 2
global message_body
global message_URL
vectorizer, document_term_mat, feature_words = tf_idf(stop_list(),message_body)
n_features = 15
n_topics = 5
n_top_words = 10
W_sklearn, H_sklearn = nmf_model2(n_topics,document_term_mat)
ind = feature_words.index(issue_question)
test_m = document_term_mat.toarray()
contained_docs = test_m[:,ind]
docs_ind = np.nonzero(contained_docs)[0] # indices are from the masked data frame
docs_list = message_body.iloc[docs_ind]
# docs_list = message_body[docs_ind]
issue_number = docs_list.shape[0]
# docs_list = [message_body[i] for i in docs_ind]
ind_doc_max_s = np.argsort(W_sklearn[docs_ind,topic_num])[:-num_posts-1:-1]
x = message_URL.iloc[docs_ind[ind_doc_max_s]]
y = docs_list.iloc[ind_doc_max_s]
top_posts = zip(x,y)
# top_posts = docs_list.iloc[ind_doc_max_s]
return render_template('newpage.html', top_posts=top_posts)
@app.route('/question', methods=['POST'])
def question():
# get data from request form
question = request.form['question']
#keys = '\n'.join([k for k in request.form])
# convert data from unicode to string
question = str(question)
##
n_related_posts=3
global feature_words
vec_question = TfidfVectorizer(stop_words=stop_list(), vocabulary=feature_words)
tfidf_matrix_question = vec_question.fit_transform([question]).toarray()
global document_term_mat
cos_sim = np.empty((document_term_mat.shape[0],))
for i in xrange(document_term_mat.shape[0]):
temp_sim = cosine_similarity(tfidf_matrix_question[0].reshape(1, -1), \
document_term_mat.toarray()[i].reshape(1, -1))
cos_sim[i] = temp_sim
similar_posts = [message_body.iloc[i] for i in np.argsort(cos_sim)[:-n_related_posts - 1:-1]]
return render_template('newpage0.html', similar_posts=similar_posts)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
<file_sep>from __future__ import division
import pandas as pd
import numpy as np
from nltk.corpus import stopwords
import string
from sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import TruncatedSVD, NMF
from numpy.random import rand, RandomState
from numpy import array, matrix, linalg
from sklearn.cluster import KMeans, MiniBatchKMeans
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
import graphlab
from graphlab import SFrame
from sklearn.metrics.pairwise import cosine_similarity
def read_data(filename):
'''
Gets the input file and do some preprocessing and output it as a dataframe
INPUT: The name and address of the csv file with the post informtion
OUTPUT: dataframe, forum post text, and data frame of the extra features
'''
data = pd.read_csv(filename, sep='\t', encoding='utf-16', header=3)
df = data[['Message Subject','Message Body No HTML','Parent Node',\
'Replies/Comments','Number of Views']]
# converting the unicode to string
df['Message Body No HTML'] = df['Message Body No HTML'].fillna('').apply(lambda x: x.encode('ascii','ignore'))
message_body = df['Message Body No HTML']
df_side_feat = df[['Replies/Comments','Number of Views']]
return df, message_body, df_side_feat
def read_data_masked(filename):
'''
Only gets the orginal posts and exclude the Replies.
INPUT: The name and address of the csv file with the post informtion
OUTPUT: dataframe, forum post text, and data frame of the extra features, and the URLs
'''
# Index([u'Message Subject', u'Message Body', u'Message Body No HTML',
# u'Message URL', u'Parent Node', u'Node Type', u'Author',
# u'Time of Post', u'Replies/Comments', u'Tags', u'Labels', u'Statuses',
# u'Status Names', u'Me Too', u'Kudos', u'5-star Rating',
# u'Number of Views', u'Parent Message URL', u'Root Message URL',
# u'Accepted As Solution', u'Images', u'Videos', u'Attachments',
# u'Read by Moderator', u'Message Teaser', u'Marked Read Only',
# u'Last Edit Author', u'Last Edit Time', u'TKB Helpful',
# u'TKB Not Helpful'],
# dtype='object')
data = pd.read_csv(filename, sep='\t', encoding='utf-16', header=3)
mask = data['Message Subject'].apply(lambda x:x[0:2] != 'Re')
df = data[['Message Subject','Message Body No HTML','Message URL','Parent Node',\
'Replies/Comments','Number of Views']][mask]
# converting the unicode to string
df['Message Body No HTML'] = df['Message Body No HTML'].fillna('').apply(lambda x: x.encode('ascii','ignore'))
message_body = df['Message Body No HTML']
message_URL = df['Message URL']
df_side_feat = df[['Replies/Comments','Number of Views']]
return df, message_body, df_side_feat, message_URL
def reconst_mse(X, W, H):
return (array(X - W.dot(H))**2).mean()
def describe_nmf_results(document_term_mat, W, H, n_top_words=15):
'''
Showing the topics and the most important words associated with those topics
'''
print("Reconstruction error: %f") %(reconst_mse(document_term_mat, W, H))
# each row of H matrix belongs to a topic, find the highest coeff and type associated words.
for topic_num, topic in enumerate(H):
print("Topic number %d:" % topic_num)
print(" ".join([feature_words[i] \
for i in topic.argsort()[:-n_top_words - 1:-1]]))
return
def stop_list():
stop_list = set(stopwords.words('english') + \
["n't", "'s", "'m", "ca", "'re", "quot",'thanks','thank','hi','hello','autodesk'\
,'adsk', '"']
+ list(ENGLISH_STOP_WORDS))
# List of symbls we don't care about
symbls = " ".join(string.punctuation).split(" ")
symbls += [""]
# Full set of stops
stops = stop_list ^ set(symbls)
return stops
def tokenize(text):
PUNCTUATION = set(string.punctuation)
STOPWORDS = set(stopwords.words('english') + ["n't", "'s", "'m" , "'re"] + \
["quot","thanks","thank","hi","hello"] + list(ENGLISH_STOP_WORDS))
STEMMER = PorterStemmer()
tokens = word_tokenize(text)
lowercased = [t.lower() for t in tokens]
no_punctuation = []
for word in lowercased:
punct_removed = ''.join([letter for letter in word if not letter in PUNCTUATION])
no_punctuation.append(punct_removed)
no_stopwords = [w for w in no_punctuation if not w in STOPWORDS]
stemmed = [STEMMER.stem(w) for w in no_stopwords]
return [w for w in stemmed if w]
def tf_idf(stop_lists,message_body):
# vectorizer = TfidfVectorizer( stop_words='english')
# vectorizer = TfidfVectorizer( stop_words='english',tokenizer=tokenize)
# vectorizer = TfidfVectorizer(tokenizer=tokenize)
vectorizer = TfidfVectorizer( stop_words=stop_lists)
document_term_mat = vectorizer.fit_transform(message_body)
feature_words = vectorizer.get_feature_names()
return vectorizer, document_term_mat, feature_words
def nmf_model(n_topics,document_term_mat):
print("\n\n---------\n decomposition")
nmf = NMF(n_components=n_topics, l1_ratio=0.0)
W_sklearn = nmf.fit_transform(document_term_mat)
H_sklearn = nmf.components_
describe_nmf_results(document_term_mat, W_sklearn, H_sklearn)
return W_sklearn, H_sklearn
def nmf_model2(n_topics,document_term_mat):
# print("\n\n---------\n decomposition")
nmf = NMF(n_components=n_topics, l1_ratio=0.0)
W_sklearn = nmf.fit_transform(document_term_mat)
H_sklearn = nmf.components_
# describe_nmf_results(document_term_mat, W_sklearn, H_sklearn)
return W_sklearn, H_sklearn
def df_sf(df):
sf = graphlab.SFrame(df[['user_id', 'joke_id', 'rating']])
return df, sf
def rec_factorization(document_term_mat,side_data,n_topics):
data = document_term_mat.toarray()
rows = []
cols = []
values = []
for row in xrange(len(data)):
for col, value in enumerate(data[row]):
rows.append(row)
cols.append(col)
values.append(value)
d = {'doc':rows, 'word': cols, 'rating':values}
new_df = pd.DataFrame(d)
new_df[['doc','word']] = new_df[['doc','word']] + 1
side_data = SFrame(data=side_data)
sf = SFrame(data=new_df)
rec = graphlab.recommender.factorization_recommender.create(
sf,
user_id='doc',
item_id='word',
user_data = side_data,
target='rating',
solver='als',
num_factors =n_topics,
side_data_factorization=True,
# regularization=0.001,
nmf=True);
word_sf = rec['coefficients']['word'] #rec.get('coefficients') or rec.list_fields()
doc_sf = rec['coefficients']['doc']
H_graph = word_sf['factors'].to_numpy()
H_graph = H_graph.T
#H_graph.shape
W_graph = doc_sf['factors'].to_numpy()
describe_nmf_results(document_term_mat, W_graph, H_graph)
return H_graph, W_graph
def post_recommender(n_related_posts=2):
'''
Recommends posts that may already have your answer
INPUT: str, the question that you want to post in the forum, number of similar questions
OUTPUT: dataframe, forum post text, and data frame of the extra features
'''
question = input("Please enter your question: ")
vec_question = TfidfVectorizer(stop_words=stop_list(), vocabulary=feature_words)
tfidf_matrix_question = vec_question.fit_transform([question]).toarray()
cos_sim = np.empty((document_term_mat.shape[0],))
for i in xrange(document_term_mat.shape[0]):
temp_sim = cosine_similarity(tfidf_matrix_question[0].reshape(1, -1), \
document_term_mat.toarray()[i].reshape(1, -1))
cos_sim[i] = temp_sim
print [message_body.iloc[i] for i in np.argsort(cos_sim)[:-n_related_posts - 1:-1]]
def issue_detection(matrix, W, H, num_posts=2):
'''
Shows the most important posts that contain the selected keyword from the selected topic
INPUT: tfidf_matrix, W, H
OUTPUT: Most relavant post to the selected topic with the selcted keyword
'''
issue_question = input("Please enter the key word/words you are intrested in: ")
# issue_question = list(issue_question)
topic_num = input("Please enter the topic number: ")
ind = feature_words.index(issue_question)
test_m = document_term_mat.toarray()
contained_docs = test_m[:,ind]
docs_ind = np.nonzero(contained_docs) # indices are from the masked data frame
docs_list = message_body.iloc[docs_ind]
issue_number = docs_list.shape[0]
ind_doc_max_s = np.argsort(W_sklearn[docs_ind[0],topic_num])[:-num_posts-1:-1]
# message_body.iloc[docs_ind[0][ind_doc_max_s]] # other way to find the questions
# top_posts = docs_list.iloc[ind_doc_max_s]
top_posts = zip(message_URL.iloc[docs_ind[0][ind_doc_max_s]],docs_list.iloc[ind_doc_max_s])
print top_posts
if __name__ == '__main__':
filename = 'data/csv_search-3644074-1470267303460.csv'
# df, message_body,df_side_feat = read_data(filename)
df, message_body,df_side_feat, message_URL = read_data_masked(filename)
vectorizer, document_term_mat, feature_words = tf_idf(stop_list(),message_body)
n_features = 15
n_topics = 5
# W_sklearn, H_sklearn = nmf_model(n_topics,document_term_mat)
# using graphlab recommender
H_graph, W_graph = rec_factorization(document_term_mat,df_side_feat,n_topics)
W_sklearn, H_sklearn = nmf_model(n_topics,document_term_mat)
top_posts = issue_detection(document_term_mat, W_sklearn, H_sklearn)
post_recommender()
# try:
# ...: y = float(x)
# ...: except:
# ...: y = None
<file_sep>final_project, data inference from customers forum posts
Overview
For tech companies, specially the ones with subscription based business models, users are constantly providing valuable inputs for the products in the forums through their posts. To make the best use of the provided inputs and improve user experience, this project performs natural language processing (NLP) on the forum texts to find the most important issues that users are struggling with and finds the optimal number of topics for each product. Using this information, appropriate interventions can be performed to improve different aspects of the products where users have issue with. Moreover, post recommendation are suggested to be added to the forum to avoid repeated posts.
Analysis
To extract the dominant topics, I created a text preprocessing-cleaning-tokenizing-TFIDF-NMF pipeline. number of replies and number of views are added as extra features in graph lab to magnify these effects. Separation and cohesion metrics were used to find the optimal number of topic for each product. Using the coefficients from matrix factorization along with TFIDF, I found the most relevant post containing a specific key word. And finally, recommendation engine is created to show most similar previous posts to a question that a user has to ask.
Validating the model with domain knowledge
Subject matter expert(SME) with the domain knowledge verified the results from the analysis of this project.
| bda890a7cf4bb628de017f6bdd74642c3af4629e | [
"Markdown",
"Python"
] | 3 | Python | maryamre/final_project | d0ec63a36fc329d85a594916049fd13d2acc5684 | 09bf834f508747da32153d037dc4605ce54bf75e |
refs/heads/master | <repo_name>dominiksinsaarland/my_stuff<file_sep>/featureExtraction_ace.py
import re
import itertools
import operator
import os
from parameters10_for_ace import *
import nltk
import sys
import gzip
import unicodedata
import json
import time
from collections import defaultdict
import pickle
import argparse
def clean_and_tokenize(sentence):
e1_idx, e2_idx = 0, 0
sentence = sentence[:-1] + ' ' + sentence[-1]
e1_capture = re.findall(r'([^\s]*)<e1>(.*?)</e1>([^\s]*)', sentence)[0]
e2_capture = re.findall(r'([^\s]*)<e2>(.*?)</e2>([^\s]*)', sentence)[0]
if ' ' in e1_capture[1]:
sentence = sentence.replace(e1_capture[1], '_'.join([word for word in e1_capture[1].split()]))
if ' ' in e2_capture[1]:
sentence = sentence.replace(e2_capture[1], '_'.join([word for word in e2_capture[1].split()]))
tokens = sentence.split()
for i, token in enumerate(tokens):
if '<e1>' in token:
e1_idx = i
clean = token.replace('<e1>', '')
clean = clean.replace('</e1>', '')
tokens[i] = clean
if '<e2>' in token:
e2_idx = i
clean = token.replace('<e2>', '')
clean = clean.replace('</e2>', '')
tokens[i] = clean
# nltk tokenization performs worse than my own tokenization (mine doesn't separate punctuation from words)
# dirty_tokens = nltk.word_tokenize(sentence)
# remove = {'>', '<', 'e1', 'e2', '/e1', '/e2'}
# for i, token in enumerate(dirty_tokens):
# if token == '>' and dirty_tokens[i-1] == '/e1':
# e1 = dirty_tokens[i-3]
# if token == '>' and dirty_tokens[i-1] == '/e2':
# e2 = dirty_tokens[i-3]
# tokens = [token for token in dirty_tokens if token not in remove]
# e1_idx = tokens.index(e1)
# e2_idx = len(tokens) - tokens[::-1].index(e2) - 1 # done to find first index starting from right of list
return tokens, e1_idx + 1, e2_idx + 1 # plus 1 because counting starts from 1
def create_indexes(train_file, train):
with open(train_file) as file:
train1, train2 = itertools.tee(file, 2)
sent_index = {}
for line in itertools.islice(train1, 0, None, 4):
split = line.strip().split('\t')
index, sentence = int(split[0]), split[1][1:-1]
sent_index[index] = sentence
if train:
lab_index = {int(index): label.strip() for index, label in
enumerate(itertools.islice(train2, 1, None, 4), start=1)}
else:
lab_index = {int(index): label.strip() for index, label in
enumerate(itertools.islice(train2, 1, None, 4), start=8001)}
return sent_index, lab_index
def create_record(rec_file, sent_index, lab_index):
with open(rec_file, 'w+') as record:
for index, sentence in sorted(sent_index.items(), key=operator.itemgetter(0)):
tokens, e1_index, e2_index = clean_and_tokenize(sentence)
s_len = len(tokens)
dist_e1_e2 = e2_index - (e1_index + 1) # number of elements between entities
if dist_e1_e2 < 0:
print('Indexes of e1 and e2 are inaccurate; sent2vec script will fail.')
print('This occurs at sentence', index)
dist_bos_e1 = e1_index - 1 # number of elements to left of e1
dist_e2_eos = s_len - e2_index # number of elements to right of e2
label = lab_index[index]
to_write = tuple([index, tokens, e1_index, e2_index, label, s_len, dist_e1_e2, dist_bos_e1, dist_e2_eos])
record.write(str(to_write) + '\n')
def create_indexes_ace2005(train_file, train, file_list = []):
sent_index = {}
lab_index = {}
e1_e2_index = {}
types_heads = {}
if train:
index = 1
with gzip.open(train_file,'rb') as infile:
# hackish because I didn't find a quick solution how to load concatenated json files
data = json.loads("[" + infile.read().decode("utf-8").replace("]}\n\n{", "]},{").replace("\n", "") + "]")
for line in data:
"""
nePairs = json.loads(line["nePairs"])
e1_index, e2_index = nePairs[0]["m1"]["head"] + 1, nePairs[0]["m2"]["head"] + 1
dist_e1_e2 = e2_index - (e1_index + 1) # number of elements between entities
if dist_e1_e2 > 15:
continue
"""
sent_index[index] = line["words"]
lab_index[index] = line["relLabels"][0]
nePairs = json.loads(line["nePairs"])
e1_e2_index[index] = ((nePairs[0]["m1"]["start"],nePairs[0]["m1"]["end"]),(nePairs[0]["m2"]["start"],nePairs[0]["m2"]["end"]))
types_heads[index] = ((nePairs[0]["m1"]["type"], nePairs[0]["m2"]["type"]),(nePairs[0]["m1"]["head"],nePairs[0]["m2"]["head"]))
index += 1
else:
index = 45000 + 1
if not file_list:
with gzip.open(train_file,'rb') as infile:
data = json.loads("[" + infile.read().decode("utf-8").replace("]}\n\n{", "]},{").replace("\n", "") + "]")
for line in data:
"""
nePairs = json.loads(line["nePairs"])
e1_index, e2_index = nePairs[0]["m1"]["head"] + 1, nePairs[0]["m2"]["head"] + 1
dist_e1_e2 = e2_index - (e1_index + 1) # number of elements between entities
if dist_e1_e2 > 15:
continue
"""
sent_index[index] = line["words"]
lab_index[index] = line["relLabels"][0]
nePairs = json.loads(line["nePairs"])
e1_e2_index[index] = ((nePairs[0]["m1"]["start"],nePairs[0]["m1"]["end"]),(nePairs[0]["m2"]["start"],nePairs[0]["m2"]["end"]))
types_heads[index] = ((nePairs[0]["m1"]["type"], nePairs[0]["m2"]["type"]),(nePairs[0]["m1"]["head"],nePairs[0]["m2"]["head"]))
index += 1
return sent_index, e1_e2_index, types_heads, lab_index
for file_name in file_list:
with gzip.open(file_name, 'rb') as infile:
# hackish because I didn't find a quick solution how to load concatenated json files
data = json.loads("[" + infile.read().decode("utf-8").replace("]}\n\n{", "]},{").replace("\n", "") + "]")
for line in data:
"""
nePairs = json.loads(line["nePairs"])
e1_index, e2_index = nePairs[0]["m1"]["head"] + 1, nePairs[0]["m2"]["head"] + 1
dist_e1_e2 = e2_index - (e1_index + 1) # number of elements between entities
if dist_e1_e2 > 15:
continue
"""
sent_index[index] = line["words"]
lab_index[index] = line["relLabels"][0]
nePairs = json.loads(line["nePairs"])
e1_e2_index[index] = ((nePairs[0]["m1"]["start"],nePairs[0]["m1"]["end"]),(nePairs[0]["m2"]["start"],nePairs[0]["m2"]["end"]))
types_heads[index] = ((nePairs[0]["m1"]["type"], nePairs[0]["m2"]["type"]),(nePairs[0]["m1"]["head"],nePairs[0]["m2"]["head"]))
index += 1
return sent_index, e1_e2_index, types_heads, lab_index
def create_record_ace2005(rec_file, sent_index, e1_e2_index, types_heads, lab_index):
fails = 0
fail_d = defaultdict(int)
with open(rec_file, 'w+') as record:
for index, tokens in sorted(sent_index.items(), key=operator.itemgetter(0)):
try:
e1_index, e2_index = types_heads[index][1][0] + 1, types_heads[index][1][1] + 1
except:
print (len(types_heads))
print (index)
#print (types_heads[index])
time.sleep(1)
s_len = len(tokens)
tokens = sent_index[index]
dist_e1_e2 = e2_index - (e1_index + 1) # number of elements between entities
"""
elif dist_e1_e2 > 15:
print ("distnace too big")
continue
"""
dist_bos_e1 = e1_index - 1 # number of elements to left of e1
dist_e2_eos = s_len - e2_index # number of elements to right of e2
label = lab_index[index]
this_types = types_heads[index][0]
if dist_e1_e2 < 0:
#print('Indexes of e1 and e2 are inaccurate; sent2vec script will fail.')
#print('This occurs at sentence', index)
fails += 1
fail_d[label] += 1
# to do: insert e2 after e1 in tokens and set e2_index to e1_index + len(e1)
#print (tokens, e1_index, e2_index, types_heads[index], e1_e2_index[index], lab_index[index])
to_debug = e1_e2_index[index]
to_write = tuple([index, tokens, e1_index, e2_index, label, s_len, dist_e1_e2, dist_bos_e1, dist_e2_eos, this_types, to_debug])
#debug_file.write(str(to_write) + '\n')
continue
to_write = tuple([index, tokens, e1_index, e2_index, label, s_len, dist_e1_e2, dist_bos_e1, dist_e2_eos, this_types])
record.write(str(to_write) + '\n')
def learn_labels(lab_file, lab_index):
unique_labels = set(list(lab_index.values()))
with open(lab_file, 'w+') as labels:
for label in sorted(unique_labels):
labels.write(label + '\n')
def learn_words(wor_file, sent_index):
unique_tokens = set()
for sentence in list(sent_index.values()):
unique_tokens.update(sentence)
with open(wor_file, 'w+') as vocab:
for token in unique_tokens:
vocab.write(token + '\n')
return unique_tokens
def learn_suffixes(suf_file, voc):
unique_suffixes = set()
for token in voc:
if len(token) >= max_suffix_size:
sliced_token = token[-max_suffix_size:]
else:
sliced_token = token
unique_suffixes.update([token[i:] for i, char in enumerate(sliced_token)])
with open(suf_file, 'w+') as suffixes:
for suffix in unique_suffixes:
suffixes.write(suffix + '\n')
def learn_words_semeval(wor_file, sent_index):
unique_tokens = set()
for sentence in sent_index.values():
unique_tokens.update(clean_and_tokenize(sentence)[0])
with open(wor_file, 'w+') as vocab:
for token in sorted(unique_tokens):
vocab.write(token + '\n')
return unique_tokens
def learn_shapes(shp_file, sent_index):
# unique_shapes = []
# for sentence in sent_index.values():
# tokens = clean_and_tokenize(sentence)[0]
# for i, token in enumerate(tokens):
# vector = [0, 0, 0, 0, 0, 0, 0]
# if any(char.isupper() for char in token):
# vector[0] = 1
# if '-' in token:
# vector[1] = 1
# if any(char.isdigit() for char in token):
# vector[2] = 1
# if i == 0 and token[0].isupper():
# vector[3] = 1
# if token[0].islower():
# vector[4] = 1
# if '_' in token:
# vector[5] = 1
# if '"' in token:
# vector[6] = 1
# tup_vec = tuple(vector)
# if tup_vec not in unique_shapes:
# unique_shapes.append(tup_vec)
# currently keeping the above code until testing can be done
unique_shapes = list(itertools.product(range(2), repeat=7)) # change repeat value for how many shape features used
with open(shp_file, 'w+') as shapes:
for shape in unique_shapes:
shapes.write(str(shape) + '\n')
def learn_tags(tag_file):
with open(tag_file, 'w+') as tags:
for tag in nltk.data.load('help/tagsets/PY3/upenn_tagset.pickle').keys():
tags.write(tag + '\n')
tags.write('#' + '\n')
def learn_categories(cat_file):
with open(cat_file, 'w+') as cats:
for cat in {unicodedata.category(c) for c in map(chr, range(sys.maxunicode+1))}:
cats.write(cat + '\n')
def learn_types(types_file):
with open(types_file, 'w+') as type_file:
covered = set()
for entry in types:
if types[entry][0][0] not in covered:
type_file.write(types[entry][0][0] + "\n")
covered.add(types[entry][0][0])
if types[entry][0][1] not in covered:
type_file.write(types[entry][0][1] + "\n")
covered.add(types[entry][0][1])
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--path_to_feat_folder', default='features/', type=str)
parser.add_argument('--path_to_model_folder', default='models/', type=str)
parser.add_argument('--path_to_train', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/bn+nw.json.gz', type=str)
parser.add_argument('--path_to_dev', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/bc_dev.json.gz', type=str)
parser.add_argument('--path_to_bc_test', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/bc_test.json.gz', type=str)
parser.add_argument('--path_to_cts_test', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/cts.json.gz', type=str)
parser.add_argument('--path_to_wl_test', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/wl.json.gz', type=str)
parser.add_argument('--eval', default='dev', type=str)
parser.add_argument('--W', default=0, type=int)
parser.add_argument('--max_suffix_size', default=0, type=int)
#parser.add_argument('--after_e1', default=True,type=bool)
#parser.add_argument('--before_e2', default=False,type=bool)
parser.add_argument('--corpus', default="ace", type=str)
args = parser.parse_args()
if args.corpus == "ace":
train_sentence_index, e1_e2_index, types, train_label_index = create_indexes_ace2005(args.path_to_train, True)
elif args.corpus == "semeval":
train_sentence_index, train_label_index = create_indexes(args.path_to_train, True)
if args.eval == "dev" and args.corpus == "ace":
test_sentence_index, test_e1_e2_index, test_types, test_label_index = create_indexes_ace2005(args.path_to_dev, False)
elif args.eval == "bc":
test_sentence_index, test_e1_e2_index, test_types, test_label_index = create_indexes_ace2005(args.path_to_bc_test, False)
elif args.eval == "cts":
test_sentence_index, test_e1_e2_index, test_types, test_label_index = create_indexes_ace2005(args.path_to_cts_test, False)
elif args.eval == "wl":
test_sentence_index, test_e1_e2_index, test_types, test_label_index = create_indexes_ace2005(args.path_to_wl_test, False)
elif args.eval == "all":
file_list = [args.path_to_bc_test, args.path_to_cts_test, args.path_to_wl_test]
test_sentence_index, test_e1_e2_index, test_types, test_label_index = create_indexes_ace2005("", False, file_list)
elif args.corpus == "semeval":
test_sentence_index, test_label_index = create_indexes(args.path_to_dev, False)
if args.W < 0 or not isinstance(args.W, int):
print('W must be a positive integer!')
print('Please check the value of W in parameters.py script.')
exit(1)
if args.max_suffix_size < 0 or not isinstance(args.max_suffix_size, int):
print('Max suffix size must be a positive integer!')
print('Please check the value of max suffix size in parameters.py script.')
exit(1)
if not os.path.exists(args.path_to_feat_folder):
os.makedirs(args.path_to_feat_folder)
if not os.path.exists(args.path_to_model_folder):
os.makedirs(args.path_to_model_folder)
train_record_file = args.path_to_feat_folder + 'record_train_ace2005.txt'
test_record_file = args.path_to_feat_folder + 'record_test_ace2005.txt'
label_file = args.path_to_feat_folder + 'labels_ace2005.txt'
words_file = args.path_to_feat_folder + 'vocab_ace2005.txt'
suffix_file = args.path_to_feat_folder + 'suffixes_ace2005.txt'
shape_file = args.path_to_feat_folder + 'shapes_ace2005.txt'
tags_file = args.path_to_feat_folder + 'tags_ace2005.txt'
categories_file = args.path_to_feat_folder + 'categories_ace2005.txt'
if args.corpus == "ace":
create_record_ace2005(train_record_file, train_sentence_index, e1_e2_index, types, train_label_index)
create_record_ace2005(test_record_file, test_sentence_index, test_e1_e2_index, test_types, test_label_index)
learn_types("features/types_ace2005.txt")
learn_labels(label_file, train_label_index)
vocab = learn_words(words_file, train_sentence_index)
learn_shapes(shape_file, train_sentence_index)
elif args.corpus == "semeval":
create_record(train_record_file, train_sentence_index, train_label_index)
create_record(test_record_file, test_sentence_index, test_label_index)
learn_labels(label_file, train_label_index)
vocab = learn_words_semeval(words_file, train_sentence_index)
learn_shapes(shape_file, train_sentence_index)
learn_suffixes(suffix_file, vocab)
learn_tags(tags_file)
learn_categories(categories_file)
<file_sep>/find_parameters_semeval10.sh
#!/bin/bash
s=4
c=0.1
e=0.3
out_name="s${s//.}c${c//.}e${e//.}"
mainDir=$(pwd)
featDir=${mainDir}"/features/"
modelDir=${mainDir}"/models/"
# vanilla test:
python3 featureExtraction_ace.py --corpus semeval --path_to_train /home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/SemEval2010_task8_all_data/SemEval2010_task8_training/TRAIN_FILE.TXT --path_to_dev /home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/SemEval2010_task8_all_data/SemEval2010_task8_testing_keys/TEST_FILE_FULL.TXT
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python evaluate.py --OTHER_RELATION Other --result_file semeval_results.txt --metric macro
# W = 2:
python3 featureExtraction_ace.py --corpus semeval --W 2 --path_to_train /home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/SemEval2010_task8_all_data/SemEval2010_task8_training/TRAIN_FILE.TXT --path_to_dev /home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/SemEval2010_task8_all_data/SemEval2010_task8_testing_keys/TEST_FILE_FULL.TXT
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --W 2
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python evaluate.py --OTHER_RELATION Other --result_file semeval_results.txt --params W_2 --metric macro
# fire positions:
python3 featureExtraction_ace.py --corpus semeval --path_to_train /home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/SemEval2010_task8_all_data/SemEval2010_task8_training/TRAIN_FILE.TXT --path_to_dev /home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/SemEval2010_task8_all_data/SemEval2010_task8_testing_keys/TEST_FILE_FULL.TXT
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_positions --metric macro
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_positions_true --OTHER_RELATION Other --result_file semeval_results.txt --metric macro
# fire shapes:
#python3 featureExtraction_ace.py --fire_positions True
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_shapes
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_shapes_true --OTHER_RELATION Other --result_file semeval_results.txt --metric macro
# fire char embeddings:
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_char_embeddings
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_char_embeddings_true --OTHER_RELATION Other --result_file semeval_results.txt --metric macro
# fire marlin clusters:
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_clusters --marlin
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_clusters_marlin_true --OTHER_RELATION Other --result_file semeval_results.txt --metric macro
# fire brown clusters:
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_clusters --brown
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_clusters_brown_true --OTHER_RELATION Other --result_file semeval_results.txt --metric macro
# fire suffixes:
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_suffixes
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_suffixes_true --OTHER_RELATION Other --result_file semeval_results.txt --metric macro
# fire suffixes length 3:
python3 featureExtraction_ace.py --max_suffix_size 3 --corpus semeval --path_to_train /home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/SemEval2010_task8_all_data/SemEval2010_task8_training/TRAIN_FILE.TXT --path_to_dev /home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/SemEval2010_task8_all_data/SemEval2010_task8_testing_keys/TEST_FILE_FULL.TXT
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_suffixes --max_suffix_size 3
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_suffixes_true_size_3 --OTHER_RELATION Other --result_file semeval_results.txt --metric macro
<file_sep>/lstm_with_context.py
from data_load import *
import tensorflow as tf
import os
import numpy as np
flags = tf.flags
flags.DEFINE_string("data_path", "features", "Where the training/test data is stored.")
flags.DEFINE_string("train_file", "record_train_ace2005", "Name of training file")
flags.DEFINE_string("test_file", "record_test_ace2005", "Name of test file")
flags.DEFINE_bool("fire_embeddings", True, "our main feature, should be True")
flags.DEFINE_integer("hidden_units", 128, "number of hidden units")
flags.DEFINE_float("learning_rate", 0.001, "")
flags.DEFINE_integer("num_labels", 19, "for dev purposes")
flags.DEFINE_integer("batch_size", 32, "")
flags.DEFINE_float("dropout", 0.9, "dropout")
FLAGS = flags.FLAGS
vocab_file = "../gridsearch/features/numberbatch-en-17.06.txt"
record_train = "../gridsearch/features/record_train_ace2005.txt"
record_test = "../gridsearch/features/record_test_ace2005.txt"
labels_file = "../gridsearch/features/labels_ace2005.txt"
embs, vocab = read_embeddings(vocab_file)
x_train, y_train, x_train_left, x_train_right = read_records_context(record_train, vocab, labels_file)
print (np.shape(x_train), np.shape(y_train), np.shape(x_train_left), np.shape(x_train_right))
x_test, y_test, x_test_left, x_test_right = read_records_context(record_test, vocab, labels_file)
vocab_size = np.shape(embs)[0]
embs_size = np.shape(embs)[1]
# initialize the embeddings
embeddings = tf.get_variable("embedding", [vocab_size, embs_size], initializer=tf.constant_initializer(embs),dtype=tf.float32)
# some placeholders
x = tf.placeholder(tf.int32, shape=[None, None])
y = tf.placeholder(tf.int32, shape=[None, FLAGS.num_labels])
sequence_lengths = tf.placeholder(tf.int32, shape=[None])
left_context = tf.placeholder(tf.int32, shape=[None, None])
right_context = tf.placeholder(tf.int32, shape=[None, None])
left_lengths = tf.placeholder(tf.int32, shape=[None])
right_lengths = tf.placeholder(tf.int32, shape=[None])
inputs = tf.nn.embedding_lookup(embeddings, x)
inputs_left = tf.nn.embedding_lookup(embeddings, left_context)
inputs_right = tf.nn.embedding_lookup(embeddings, right_context)
# forward and backward LSTM + dropout
with tf.variable_scope("main_lstm"):
cell_fw = tf.contrib.rnn.LSTMCell(FLAGS.hidden_units)
cell_fw = tf.contrib.rnn.DropoutWrapper(cell_fw, output_keep_prob=FLAGS.dropout)
cell_bw = tf.contrib.rnn.LSTMCell(FLAGS.hidden_units)
cell_bw = tf.contrib.rnn.DropoutWrapper(cell_bw, output_keep_prob=FLAGS.dropout)
(output_fw, output_bw), (f1, f2) = tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, inputs, sequence_length=sequence_lengths, dtype=tf.float32)
# forward and backward LSTM + dropout left context
with tf.variable_scope("left_context"):
cell_fw_left = tf.contrib.rnn.LSTMCell(FLAGS.hidden_units / 2)
cell_fw_left = tf.contrib.rnn.DropoutWrapper(cell_fw_left, output_keep_prob=FLAGS.dropout)
cell_bw_left = tf.contrib.rnn.LSTMCell(FLAGS.hidden_units / 2)
cell_bw_left = tf.contrib.rnn.DropoutWrapper(cell_bw_left, output_keep_prob=FLAGS.dropout)
_, (f1_left, f2_left) = tf.nn.bidirectional_dynamic_rnn(cell_fw_left, cell_bw_left, inputs_left, sequence_length=left_lengths, dtype=tf.float32)
# forward and backward LSTM + dropout right context
with tf.variable_scope("right_context"):
cell_fw_right = tf.contrib.rnn.LSTMCell(FLAGS.hidden_units / 2)
cell_fw_right = tf.contrib.rnn.DropoutWrapper(cell_fw_right, output_keep_prob=FLAGS.dropout)
cell_bw_right = tf.contrib.rnn.LSTMCell(FLAGS.hidden_units / 2)
cell_bw_right = tf.contrib.rnn.DropoutWrapper(cell_bw_right, output_keep_prob=FLAGS.dropout)
_, (f1_right, f2_right) = tf.nn.bidirectional_dynamic_rnn(cell_fw_right, cell_bw_right, inputs_right, sequence_length=right_lengths, dtype=tf.float32)
concat = tf.concat([f1_left.h, f2_left.h, f1.h, f2.h, f1_right.h, f2_right.h], axis=-1)
second_last_layer = tf.nn.dropout(tf.layers.dense(inputs=concat,units=FLAGS.hidden_units, activation = tf.tanh), FLAGS.dropout)
#second_last_layer = tf.layers.Dropout(tf.layers.dense(2 * FLAGS.hidden_units, activation = tf.tanh), rate=0.2)
output_weights = tf.get_variable("W_out", shape=[FLAGS.hidden_units, FLAGS.num_labels], dtype=tf.float32)
output_biases = tf.get_variable("B_out", shape=[FLAGS.num_labels], dtype=tf.float32, initializer=tf.zeros_initializer())
logits = tf.matmul(second_last_layer, output_weights) + output_biases
# pass on to the costfunction (without softmax layer, because this is done implicitely in the cross_entropy_with_logits function)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
# optimize the lossfunction
# take random optimizer, RMSProp is a good default one, given that the hyperparameters don't matter that much
optimizer = tf.train.RMSPropOptimizer(learning_rate=FLAGS.learning_rate).minimize(cost)
#optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate).minimize(cost)
# to do the actual prediction
preds = tf.nn.softmax(logits)
# take the argmax of the output vector
labels_pred = tf.cast(tf.argmax(preds, axis=-1), tf.int32)
# run the session
acc = 0
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(10):
p = np.random.permutation(len(x_train))
# x_train, y_train, x_train_left, x_train_right = read_records_context(record_train, vocab, labels_file)
x_train, y_train, x_train_left, x_train_right = x_train[p], y_train[p], x_train_left[p], x_train_right[p]
# do batchwise optimization
for batch in range(int(len(x_train)/FLAGS.batch_size)):
xs, ys, lens, x_lefts, lens_left, x_rights, lens_right = compute_batch_context_LSTM(x_train, y_train, batch * FLAGS.batch_size, (batch + 1) * FLAGS.batch_size, x_train_left, x_train_right)
# train the model
preds = sess.run(optimizer, feed_dict={x: xs, y: ys, sequence_lengths: lens, left_context:x_lefts, right_context: x_rights, left_lengths:lens_left, right_lengths: lens_right})
# show progress
whole_x, lens, x_lefts, lens_left, x_rights, lens_right = compute_whole_set_context_LSTM(x_train, x_train_left, x_train_right)
labs = sess.run(labels_pred, feed_dict={x:whole_x, y:y_train, sequence_lengths:lens, left_context:x_lefts, right_context: x_rights, left_lengths:lens_left, right_lengths: lens_right})
acc_new = sum([1 for i,j in zip(labs, y_train) if i == np.argmax(j)])/len(y_train)
print ("epoch", epoch, "accuracy", acc_new)
whole_test, lens, test_left, lens_left, test_right, lens_right = compute_whole_set_context_LSTM(x_test, x_test_left, x_test_right)
labs = sess.run(labels_pred, feed_dict={x:whole_test, y:y_test, sequence_lengths:lens, left_context:test_left, right_context: test_right, left_lengths:lens_left, right_lengths: lens_right})
acc_new = sum([1 for i,j in zip(labs, y_test) if i == np.argmax(j)])/len(y_test)
print ("testset acc:", acc_new)
<file_sep>/sent2vec_ace.py
import ast
import re
from collections import Counter
import operator
import string
import unicodedata
import time
import pandas as pd
import pickle
import gensim
import sys
import random
import argparse
"""
def read_record(file):
with open(file) as f:
return [ast.literal_eval(line) for line in f]
"""
def read_record(file, adjust_ratio=False):
with open(file) as f:
if adjust_ratio:
list_1, list_2 = [], []
for line in f:
line = ast.literal_eval(line)
if line[4] == "NO_RELATION(Arg-1,Arg-1)":
list_1.append(line)
else:
list_2.append(line)
random.seed(1337)
random.shuffle(list_1)
list_1 = list_1[:2*len(list_2)]
truncated = list_1 + list_2
random.shuffle(truncated)
return truncated
else:
return [ast.literal_eval(line) for line in f]
def read_tags(file):
with open(file) as f:
return {tag.strip(): i for i, tag in enumerate(f)}
def read_shape_file(file, unkwn):
shps = {}
with open(file) as f:
for i, line in enumerate(f):
shps[ast.literal_eval(line)] = i
shps[unkwn] = len(shps)
return shps
def read_feat_file(file, unkwn):
feats = {}
with open(file) as f:
for i, item in enumerate(f):
feats[item.strip()] = i
feats[unkwn] = len(feats)
return feats
def read_clusters(file):
clusts = {}
with open(file) as f:
for line in f:
wrd, clust = line.strip().split()
if 'marlin' in file:
clusts[wrd] = int(clust)
elif 'brown' in file:
clusts[wrd] = int(clust, 2) # converts binary to int
if 'brown' in file:
clusts['<RARE>'] = max(clusts.values()) + 1
return clusts
def read_embeddings(file):
embs = {}
with open(file) as f:
for line in f:
split = line.strip().split()
if len(split) == 2:
continue
else:
word, vec = split[0], [float(val) for val in split[1:]]
embs[word] = vec
return embs
"""
def read_embeddings(file):
embs = gensim.models.KeyedVectors.load_word2vec_format('/home/dominik/Documents/FS_2016/Supertagging/second_try/GoogleNews-vectors-negative300.bin.gz', binary=True)
embeddings = {}
for i in embs.vocab:
embeddings[i] = embs.get_vector(i)
del embs
return embeddings
"""
def read_cats(file):
cats = {}
with open(file) as f:
for i, line in enumerate(f):
cats[line.strip()] = i
return cats
def read_types(file):
types = {}
with open(file) as f:
for i, line in enumerate(f):
types[line.strip()] = i
return types
def create_pos_index(s_and_i, M, avg_m):
posits = {}
K = 2 * args.W + M
vec_len = 2 * K + 2 + 1 # plus 2 for entities and plus 1 for middle
for s, e1, e2 in s_and_i:
norm_sent = normalize(M, [s, e1, e2], avg_m)
vectors = vectorize(norm_sent, e1, e2, vec_len)
for vector in vectors:
if vector not in posits:
posits[vector] = len(posits)
posits['UNKNOWN'] = len(posits)
return posits
def normalize(m, sent, avg_m):
tkns, e1_index, e2_index = sent[0], sent[1], sent[2]
l = e1_index - 1
r = len(tkns) - e2_index
current_m = e2_index - (e1_index + 1)
if l == args.W and r == args.W:
# print('1')
if current_m > avg_m and args.use_avg_M:
tkns = slice_middle(tkns, avg_m, e1_index, e2_index)
else:
tkns = pad_middle(tkns, m, e1_index, e2_index)
elif l == args.W and r < args.W:
# print('2')
tkns = pad_right(tkns, r)
if current_m > avg_m and args.use_avg_M:
tkns = slice_middle(tkns, avg_m, e1_index, e2_index)
else:
tkns = pad_middle(tkns, m, e1_index, e2_index)
elif l == args.W and r > args.W:
# print('3')
tkns = slice_right(tkns, r)
if current_m > avg_m and args.use_avg_M:
tkns = slice_middle(tkns, avg_m, e1_index, e2_index)
else:
tkns = pad_middle(tkns, m, e1_index, e2_index)
elif r == args.W and l < args.W:
# print('4')
tkns = pad_left(tkns, l)
if current_m > avg_m and args.use_avg_M:
tkns = slice_middle(tkns, avg_m, e1_index, e2_index)
else:
tkns = pad_middle(tkns, m, e1_index, e2_index)
elif r == args.W and l > args.W:
# print('5')
tkns = slice_left(tkns, l)
if current_m > avg_m and args.use_avg_M:
tkns = slice_middle(tkns, avg_m, e1_index, e2_index)
else:
tkns = pad_middle(tkns, m, e1_index, e2_index)
elif l < args.W and r < args.W:
# print('6')
tkns = pad_left(tkns, l)
tkns = pad_right(tkns, r)
if current_m > avg_m and args.use_avg_M:
tkns = slice_middle(tkns, avg_m, e1_index, e2_index)
else:
tkns = pad_middle(tkns, m, e1_index, e2_index)
elif l > args.W and r > args.W:
# print('7')
tkns = slice_left(tkns, l)
tkns = slice_right(tkns, r)
if current_m > avg_m and args.use_avg_M:
tkns = slice_middle(tkns, avg_m, e1_index, e2_index)
else:
tkns = pad_middle(tkns, m, e1_index, e2_index)
elif l < args.W < r:
# print('8')
tkns = pad_left(tkns, l)
tkns = slice_right(tkns, r)
if current_m > avg_m and args.use_avg_M:
tkns = slice_middle(tkns, avg_m, e1_index, e2_index)
else:
tkns = pad_middle(tkns, m, e1_index, e2_index)
elif r < args.W < l:
# print('9')
tkns = slice_left(tkns, l)
tkns = pad_right(tkns, r)
if current_m > avg_m and args.use_avg_M:
tkns = slice_middle(tkns, avg_m, e1_index, e2_index)
else:
tkns = pad_middle(tkns, m, e1_index, e2_index)
return tkns
def vectorize(tokes, e1, e2, vec_length):
vecs = []
middle = vec_length // 2
for i in range(1, len(tokes) + 1):
vec = [0 for _ in range(vec_length)]
val1 = i - e1
val2 = i - e2
vec[middle + val1] = 1
vec[middle + val2] = 1
if vec not in vecs:
vecs.append(vec)
return [tuple(v) for v in vecs]
def pad_middle(lst, m, e1, e2):
for i in range(m - (e2 - e1) + 1):
if args.after_e1:
lst.insert(args.W+1, None)
elif args.before_e2:
lst.insert(len(lst)-(args.W+1), None)
elif not args.after_e1 and not args.before_e2:
middle = m // 2
if m % 2 == 0:
lst.insert(args.W+middle+1, None)
else:
lst.insert(args.W+middle+2, None) # +2 treats middle closer to e2 and +1 treats middle closer to e1
return lst
def slice_middle(lst, avg_m, e1, e2):
if args.after_e1:
return lst[:e1+avg_m] + lst[e2:]
if args.before_e2:
return lst[:e1] + lst[e2-avg_m:]
def pad_left(lst, l):
for i in range(args.W - l):
lst.insert(0, None)
return lst
def pad_right(lst, r):
for i in range(args.W - r):
lst.append(None)
return lst
def slice_left(lst, l):
return lst[l-args.W:]
def slice_right(lst, r):
return lst[:-(r - args.W)]
def create_one_hot(i, dims):
vec = dims * [0]
vec[i] = 1
return vec
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--path_to_feat_folder', default='features/', type=str)
parser.add_argument('--path_to_model_folder', default='models/', type=str)
parser.add_argument('--path_to_train', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/bn+nw.json.gz', type=str)
parser.add_argument('--path_to_dev', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/bc_dev.json.gz', type=str)
parser.add_argument('--path_to_bc_test', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/bc_test.json.gz', type=str)
parser.add_argument('--path_to_cts_test', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/cts.json.gz', type=str)
parser.add_argument('--path_to_wl_test', default='/home/dominik/Documents/DFKI/Hiwi-master/NemexRelator2010/ace-05-splits/json-ygd15-r11/wl.json.gz', type=str)
parser.add_argument('--eval', default='dev', type=str)
# window size
parser.add_argument('--W', default=0, type=int)
# basic features
parser.add_argument('--fire_words', action='store_true', default=False)
parser.add_argument('--fire_embeddings', action='store_true', default=False)
parser.add_argument('--fire_types', action='store_true', default=False)
# padding decisions
parser.add_argument('--after_e1', action='store_true', default=False)
parser.add_argument('--before_e2', action='store_true', default=False)
# padding decisions 2, how many padding tokens do we add?
parser.add_argument('--use_avg_M', action='store_true', default=False)
parser.add_argument('--use_avg_M_plus_mode', action='store_true', default=False)
parser.add_argument('--use_fixed_M', action='store_true', default=False)
# additional features, to be played around with
parser.add_argument('--max_suffix_size', default=0, type=int)
parser.add_argument('--fire_suffixes', action='store_true', default=False)
parser.add_argument('--fire_clusters', action='store_true', default=False)
parser.add_argument('--marlin', action='store_true', default=False)
parser.add_argument('--brown', action='store_true', default=False)
parser.add_argument('--fire_tagger', action='store_true', default=False)
parser.add_argument('--fire_unicode_cats', action='store_true', default=False)
parser.add_argument('--fire_positions', action='store_true', default=False)
parser.add_argument('--fire_shapes', action='store_true', default=False)
parser.add_argument('--fire_char_embeddings', action='store_true', default=False)
parser.add_argument('--adjust_ratio', action='store_true', default=False)
args = parser.parse_args()
in_embs = 0
oov = 0
unknown = 'UNKNOWN'
punc = set(string.punctuation)
records_and_outs = [(args.path_to_feat_folder + 'record_train_ace2005.txt', args.path_to_model_folder + 'libLinearInput_train_ace2005.txt'),
(args.path_to_feat_folder + 'record_test_ace2005.txt', args.path_to_model_folder + 'libLinearInput_test_ace2005.txt')]
num_words = 0
num_positions = 0
num_clusters = 0
num_suffixes = 0
num_shapes = 0
num_tags = 0
num_embeddings = 0
char_emb_dims = 0
cat_dims = 0
words = read_feat_file(args.path_to_feat_folder + 'vocab_ace2005.txt', unknown)
if args.fire_words:
num_words = len(words)
if args.fire_clusters:
if args.marlin:
clusters = read_clusters(args.path_to_feat_folder + 'en_marlin_cluster_1000')
elif args.brown:
clusters = read_clusters(args.path_to_feat_folder + 'en_brown_1000')
num_clusters = max(clusters.values()) + 1
if args.fire_suffixes:
suffixes = read_feat_file(args.path_to_feat_folder + 'suffixes_ace2005.txt', unknown)
num_suffixes = len(suffixes)
if args.fire_shapes:
shapes = read_shape_file(args.path_to_feat_folder + 'shapes_ace2005.txt', unknown)
num_shapes = len(shapes)
if args.fire_tagger:
from nltk.tag import pos_tag_sents
tags = read_tags(args.path_to_feat_folder + 'tags_ace2005.txt')
num_tags = len(tags)
if args.fire_embeddings:
#embeddings = read_embeddings("/home/dominik/Documents/Supertagging/glove.6B.300d.txt")
embeddings = read_embeddings(args.path_to_feat_folder + 'numberbatch-en-17.06.txt')
num_embeddings = len(list(embeddings.values())[0])
if args.fire_char_embeddings:
char_embeddings = read_embeddings(args.path_to_feat_folder + 'numberbatch-en-char.txt')
char_emb_dims = len(list(char_embeddings.values())[0])
if args.fire_unicode_cats:
unicode_categories = read_cats(args.path_to_feat_folder + 'categories_ace2005.txt')
cat_dims = len(unicode_categories)
if args.fire_types:
types = read_types(args.path_to_feat_folder + "types_ace2005.txt")
types_dim = len(types)
for record_file, out_file in records_and_outs:
which = re.findall(r'record_(.*?).txt', record_file)[0]
if args.adjust_ratio:
if which == "train_ace2005":
records = read_record(record_file, adjust_ratio=True)
else:
records = read_record(record_file)
else:
records = read_record(record_file)
sentences_and_indexes = [(record[1], int(record[2]), int(record[3])) for record in records]
sentence_labels = [record[4] for record in records]
with open(args.path_to_feat_folder + 'labels_ace2005.txt') as labs:
labels = {lab.strip(): i for i, lab in enumerate(labs)}
if 'train' in record_file:
all_M_vals = [record[6] for record in records]
M = max(all_M_vals)
avg_M = sum(all_M_vals) // len(records)
if args.use_avg_M_plus_mode:
M_counts = Counter(all_M_vals)
avg_M += max(M_counts.items(), key=operator.itemgetter(1))[0]
if args.use_fixed_M and args.use_avg_M:
avg_M = 15
positions = create_pos_index(sentences_and_indexes, M, avg_M)
num_positions = len(positions) if args.fire_positions else 0
norm_sents = [normalize(M, sentence, avg_M) for sentence in sentences_and_indexes]
if args.fire_tagger:
from nltk.tag import pos_tag_sents
tagged_sents = pos_tag_sents([[w if w is not None else 'none' for w in sent] for sent in norm_sents])
else:
tagged_sents = None
if args.max_suffix_size == 0:
word_lengths = [len(w) for w in words]
suffix_length = sum(word_lengths) // num_words
else:
suffix_length = args.max_suffix_size
num_char_embeddings = suffix_length * char_emb_dims
num_cats = cat_dims * suffix_length
len_token_vec = num_words + num_positions + num_clusters + num_suffixes + num_shapes + num_tags + num_embeddings + num_char_embeddings + num_cats
if args.fire_types:
types_list = [record[-1] for record in records]
feat_val = ':1.0'
errs = 0
with open(out_file, 'w+') as lib_out:
for i, sentence in enumerate(sentences_and_indexes):
try:
sentence_feats = []
current_label = sentence_labels[i]
norm_sent = norm_sents[i]
#if len(norm_sent) > M:
# norm_sent = norm_sent[:M]
if tagged_sents:
tagged_sent = tagged_sents[i]
K = 2 * args.W + M
pos_vecs = vectorize(norm_sent, sentence[1], sentence[2], 2 * K + 2 + 1)
for idx, token in enumerate(norm_sent):
offset = idx * len_token_vec
token_feats = []
if token:
token_length = len(token)
if args.fire_words:
if token in words:
feat_pos = offset + words[token] + 1
else:
feat_pos = offset + words[unknown] + 1
token_feat = str(feat_pos) + feat_val
token_feats.append(token_feat)
if args.fire_positions:
if pos_vecs[idx] in positions:
feat_pos = offset + positions[pos_vecs[idx]] + num_words + 1
else:
feat_pos = offset + positions[unknown] + num_words + 1
token_feat = str(feat_pos) + feat_val
token_feats.append(token_feat)
if args.fire_clusters:
temp_token = ''.join('0' if char.isdigit() else char for char in token)
if any(char.isalpha() for char in temp_token) and len(temp_token) > 1:
temp_token = ''.join(char for char in temp_token if char not in string.punctuation)
if temp_token in clusters:
feat_pos = offset + clusters[temp_token] + num_words + num_positions + 1
else:
feat_pos = offset + clusters['<RARE>'] + num_words + num_positions + 1
token_feat = str(feat_pos) + feat_val
token_feats.append(token_feat)
if args.fire_suffixes:
suffix_vec = []
for j in range(len(token)):
suffix = token[j:]
if suffix in suffixes:
suffix_vec.append(suffixes[suffix])
else:
if suffixes[unknown] not in suffix_vec:
suffix_vec.append(suffixes[unknown])
for s in sorted(suffix_vec):
feat_pos = offset + s + num_words + num_positions + num_clusters + 1
token_feat = str(feat_pos) + feat_val
token_feats.append(token_feat)
if args.fire_shapes:
shape_vec = [0, 0, 0, 0, 0, 0, 0]
if any(char.isupper() for char in token):
shape_vec[0] = 1
if '-' in token:
shape_vec[1] = 1
if any(char.isdigit() for char in token):
shape_vec[2] = 1
if i == 0 and token[0].isupper():
shape_vec[3] = 1
if token[0].islower():
shape_vec[4] = 1
if '_' in token:
shape_vec[5] = 1
if '"' in token:
shape_vec[6] = 1
tup_vec = tuple(shape_vec)
feat_pos = offset + shapes[tup_vec] + num_words + num_positions + num_clusters + num_suffixes + 1
token_feat = str(feat_pos) + feat_val
token_feats.append(token_feat)
if args.fire_tagger:
current_tag = tagged_sent[idx][1]
feat_pos = offset + tags[current_tag] + num_shapes + num_words + num_positions + num_clusters + num_suffixes + 1
token_feat = str(feat_pos) + feat_val
token_feats.append(token_feat)
if args.fire_embeddings:
temp_token = ''.join('#' if char.isdigit() else char for char in token)
temp_token = ''.join('_' if char == '-' else char for char in temp_token)
lowered = temp_token.lower()
if lowered in embeddings:
vec = embeddings[lowered]
token_feats += [str(offset + n + num_tags + num_shapes + num_words + num_positions +
num_clusters + num_suffixes + 1) + ':' + str(vec[n])
for n in range(num_embeddings)]
if args.fire_char_embeddings:
vec = []
empty_vec = [0.0] * char_emb_dims
if token_length < suffix_length:
for i in range(suffix_length - token_length):
vec += empty_vec
suffix = token[-suffix_length:]
for char in suffix:
if char in char_embeddings:
vec += char_embeddings[char]
else:
print(char, 'not found')
vec += empty_vec
token_feats += [str(offset + n + num_embeddings + num_tags + num_shapes + num_words
+ num_positions + num_clusters + num_suffixes + 1) + ':' + str(vec[n])
for n in range(char_emb_dims)]
if args.fire_unicode_cats:
cat_vec = []
suffix = token[-suffix_length:]
for i, char in enumerate(suffix):
cat = unicodedata.category(char)
cat_vec.append(unicode_categories[cat] + i*cat_dims)
for c in sorted(cat_vec):
feat_pos = offset + c + num_char_embeddings + num_embeddings + num_tags + num_shapes + num_words + num_positions + num_clusters + num_suffixes + 1
char_feat = str(feat_pos) + feat_val
token_feats.append(char_feat)
else:
unknown_word = None
unknown_position = None
unknown_cluster = None
unknown_suffix = None
unknown_shape = None
unknown_tag = None
# not handling unknown embeddings because they don't have indices
if args.fire_words:
feat_pos = offset + words[unknown] + 1
unknown_word = str(feat_pos) + feat_val
if args.fire_positions:
feat_pos = offset + positions[unknown] + num_words + 1
unknown_position = str(feat_pos) + feat_val
if args.fire_clusters:
feat_pos = offset + clusters['<RARE>'] + num_words + num_positions + 1
unknown_cluster = str(feat_pos) + feat_val
if args.fire_suffixes:
feat_pos = offset + suffixes[unknown] + num_words + num_positions + num_clusters + 1
unknown_suffix = str(feat_pos) + feat_val
if args.fire_shapes:
feat_pos = offset + shapes[unknown] + num_words + num_positions + num_clusters + num_suffixes + 1
unknown_shape = str(feat_pos) + feat_val
if args.fire_tagger:
feat_pos = offset + tags['NN'] + num_shapes + num_words + num_positions + num_clusters + num_suffixes + 1
unknown_tag = str(feat_pos) + feat_val
token_feats = [unknown_word, unknown_position, unknown_cluster, unknown_suffix, unknown_shape,
unknown_tag]
sentence_feats += token_feats
lib_out.write(str(labels[current_label]) + ' ')
if args.fire_types:
lib_out.write(' '.join(i for i in sentence_feats if i))
this_types = types_list[i]
t1, t2 = types[this_types[0]], types[this_types[1]]
feat_pos_1 = len(norm_sent) * len_token_vec + 1 + t1
feat_pos_2 = len(norm_sent) * len_token_vec + types_dim + 1 + t2
lib_out.write(" " + str(feat_pos_1) + feat_val + " " + str(feat_pos_2) + feat_val + "\n")
else:
lib_out.write(' '.join(i for i in sentence_feats if i) + "\n")
except Exception as e:
print (str(e))
print (norm_sents[i])
print (i, ",", sentence)
print (len_token_vec, M, avg_M)
errs += 1
<file_sep>/addLabels10_ace2005.py
import itertools
import sys
import os
from parameters10_for_ace import *
import ast
def read_labels(file):
labs = {}
with open(file) as lbs:
for i, lab in enumerate(lbs):
labs[str(i)] = lab.strip()
return labs
def read_record(file):
with open(file) as f:
return [ast.literal_eval(line) for line in f]
if __name__ == '__main__':
s, c, e = [''.join(char for char in arg if char != '.') for arg in sys.argv[1:]]
lib_linear_params = 's' + s + 'c' + c + 'e' + e
path_to_predictions = path_to_model_folder + lib_linear_params + '_predictions_ace2005.txt'
path_to_labels = path_to_feat_folder + 'labels_ace2005.txt'
#path_to_full_test = 'SemEval2010_task8_all_data/SemEval2010_task8_testing_keys/TEST_FILE_FULL.TXT'
labels = read_labels(path_to_labels)
with open(path_to_predictions) as predicts:
lines = []
for i, line in enumerate(predicts):
p = line.strip()
lines.append([i, labels[p]])
with open(path_to_model_folder + lib_linear_params + '_predictions_with_labels_ace2005.txt', 'w+') as out:
for line in lines:
out.write('\t'.join(str(el) for el in line) + '\n')
"""
with open(path_to_full_test) as test, open('answer_key10.txt', 'w+') as key:
correct_labels = itertools.islice(test, 1, None, 4)
for i, label in enumerate(correct_labels):
key.write(str(i) + '\t' + label)
"""
correct_labels = read_record(os.path.join("features", "record_test_ace2005.txt"))
with open("answer_key10_ace2005.txt", "w+") as key:
for i, label in enumerate(correct_labels):
key.write(str(i) + "\t" + label[4] + "\n")
<file_sep>/data_load.py
# -*- coding: utf-8 -*-
#/usr/bin/python2
'''
June 2017 by <NAME>.
<EMAIL>.
https://www.github.com/kyubyong/transformer
'''
import numpy as np
import ast
import string
import re
from nltk.stem import WordNetLemmatizer
def create_one_hot(length, x):
zeros = np.zeros(length, dtype=np.int32)
zeros[x] = 1
return zeros
def lookup(w, vocab):
lemmatizer = WordNetLemmatizer()
reg = re.compile('[%s]' % re.escape(string.punctuation.replace("_", "").replace("#", "")))
if normalize_word(w,reg) in vocab:
# elif strip punctuation
return vocab[normalize_word(w,reg)]
# elif lemmatize
if lemmatizer.lemmatize(normalize_word(w,reg)) in vocab:
return vocab[lemmatizer.lemmatize(normalize_word(w,reg))]
# if multiword, just take the last entry
if lemmatizer.lemmatize(normalize_word(w.split("_")[-1],reg)) in vocab:
return vocab[lemmatizer.lemmatize(normalize_word(w.split("_")[-1],reg))]
return vocab["__UNKNOWN__"]
def normalize_word(word, reg):
word = word.lower()
word = reg.sub("",word)
return word
def generate_batch_transformers(Xs, Ys, old, new, queries):
xs = Xs[old:new]
ys = Ys[old:new]
this_queries = queries[old:new]
lens = [len(x) for x in xs]
max_length = 32
#max_length = max(lens)
xs = [np.concatenate((np.zeros(max_length - len(x)), x)) for x in xs]
return xs, ys, np.expand_dims([x[0] for x in this_queries], axis=-1), np.expand_dims([x[1] for x in this_queries], axis=-1)
def compute_batch_LSTM(Xs, Ys, old, new):
# compute a batch dynamically, especially the lengths of the sentences in the batch
xs = Xs[old:new]
ys = Ys[old:new]
lens = [len(x) for x in xs]
max_length = max(lens)
xs = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in xs]
return xs, ys, lens
def compute_whole_set_LSTM(xs):
# vectorize the whole set
lens = [len(x) for x in xs]
max_length = max(lens)
xs = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in xs]
return xs, lens
def generate_test_set_transformers(xs, queries):
# vectorize the whole set
lens = [len(x) for x in xs]
#max_length = max(lens)
max_length = 32
xs = [np.concatenate((np.zeros(max_length - len(x)),x)) for x in xs]
return xs, np.expand_dims([x[0] for x in queries],axis=-1), np.expand_dims([x[1] for x in queries],axis=-1)
def read_vocab(fn):
vocab_counter = 1
vocab = {}
with open(fn) as f:
for line in f:
split = line.strip().split()
# header line
if len(split) == 2:
continue
else:
word = split[0]
vocab[word] = vocab_counter
vocab_counter += 1
vocab["__PADDING__"] = 0
vocab["__UNKNOWN__"] = vocab_counter
vocab["#"] = vocab_counter + 1
return vocab
def read_embeddings(fn):
"""
read embeddings and store each word in the rows of the matrix at its index
returns the embedding matrix
first row is 0 vector for padding, last row is __UNKNOWN__ vector (just average of all vectors)
"""
vocab_counter = 1
vocab = {}
embs = np.zeros((417194 + 3, 300))
single_digits = []
with open(fn) as f:
for line in f:
split = line.strip().split()
# header line
if len(split) == 2:
continue
else:
word, vec = split[0], [float(val) for val in split[1:]]
if word.isdigit() and len(word) == 1:
single_digits.append(vec)
vocab[word] = vocab_counter
embs[vocab_counter,:] = vec
vocab_counter += 1
vocab["__PADDING__"] = 0
vocab["__UNKNOWN__"] = vocab_counter
vocab["#"] = vocab_counter + 1
embs[vocab_counter,:] = np.mean(embs, axis=0)
embs[vocab_counter + 1,:] = np.mean(np.asarray(single_digits), axis=0)
return embs, vocab
def read_records_context(fn, vocab, labels_file):
with open(labels_file) as labs:
labels = {lab.strip(): i for i, lab in enumerate(labs)}
X,y = [], []
X_left, X_right = [], []
with open(fn) as infile:
for line in infile:
# read line
line = ast.literal_eval(line)
sent = line[1]
e1, e2 = line[2]-1, line[3]
label = line[4]
# vectorize the relation
tmp_left, tmp, tmp_right = [], [], []
for w in sent[:e1 + 1]:
w = ''.join('#' if char.isdigit() else char for char in w)
w = ''.join('_' if char == '-' else char for char in w)
if w in vocab:
tmp_left.append(vocab[w])
else:
tmp_left.append(lookup(w, vocab))
for w in sent[e1:e2]:
w = ''.join('#' if char.isdigit() else char for char in w)
w = ''.join('_' if char == '-' else char for char in w)
if w in vocab:
tmp.append(vocab[w])
else:
tmp.append(lookup(w, vocab))
for w in sent[e2 - 1:]:
w = ''.join('#' if char.isdigit() else char for char in w)
w = ''.join('_' if char == '-' else char for char in w)
if w in vocab:
tmp_right.append(vocab[w])
else:
tmp_right.append(lookup(w, vocab))
#tmp = np.concatenate((np.zeros(32 - len(tmp)), tmp))
X.append(tmp)
X_left.append(tmp_left)
X_right.append(tmp_right)
y.append(create_one_hot(len(labels), labels[label]))
return np.asarray(X), np.asarray(y), np.asarray(X_left), np.asarray(X_right)
def compute_batch_context_LSTM(Xs, Ys, old, new, x_left, x_right):
# compute a batch dynamically, especially the lengths of the sentences in the batch
xs = Xs[old:new]
ys = Ys[old:new]
x_lefts = x_left[old:new]
x_rights = x_right[old:new]
lens = [len(x) for x in xs]
max_length = max(lens)
xs = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in xs]
lens_left = [len(x) for x in x_lefts]
max_length = max(lens_left)
x_lefts = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in x_lefts]
lens_right = [len(x) for x in x_rights]
max_length = max(lens_right)
x_rights = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in x_rights]
return xs, ys, lens, x_lefts, lens_left, x_rights, lens_right
def compute_whole_set_context_LSTM(xs,x_left, x_right):
# vectorize the whole set
lens = [len(x) for x in xs]
max_length = max(lens)
xs = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in xs]
lens_left = [len(x) for x in x_left]
max_length = max(lens_left)
x_left = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in x_left]
lens_right = [len(x) for x in x_right]
max_length = max(lens_right)
x_right = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in x_right]
return xs, lens, x_left, lens_left, x_right, lens_right
def load_labels(labels_file):
with open(labels_file) as labs:
labels2id = {lab.strip(): i for i, lab in enumerate(labs)}
with open(labels_file) as labs:
id2labels = {i:lab.strip() for i, lab in enumerate(labs)}
return labels2id, id2labels
def read_records(fn, vocab, labels_file):
"""
reads the train and test file and vectorizes sequences with word indexes
returns X and y
"""
with open(labels_file) as labs:
labels = {lab.strip(): i for i, lab in enumerate(labs)}
NUM_OOV_TOKENS = 0
NUM_TOKENS = 0
X,y = [], []
queries = []
oov_file = open("oov_file.txt", 'w')
with open(fn) as infile:
for line in infile:
# read line
line = ast.literal_eval(line)
sent = line[1]
e1, e2 = line[2]-1, line[3]
label = line[4]
# vectorize the relation
tmp = []
for w in sent[e1:e2]:
NUM_TOKENS += 1
w = ''.join('#' if char.isdigit() else char for char in w)
w = ''.join('_' if char == '-' else char for char in w)
# handling OOV tokens is a long story and requires some discussion...
# decided to normalize word, strip punctuation, replace digits with #, lemmatize if necessary, just take the last token of MWE if necessary
# reduces OOV tokens of semeval10 training file to 0.6%, seems ok
if w in vocab:
# if the word appears in the vocab, we don't have a problem
tmp.append(vocab[w])
else:
tmp.append(lookup(w, vocab))
if tmp[-1] == vocab["__UNKNOWN__"]:
NUM_OOV_TOKENS += 1
oov_file.write(w + "\n")
queries_tmp = [tmp[0], tmp[-1]]
queries.append(queries_tmp)
#tmp = np.concatenate((np.zeros(32 - len(tmp)), tmp))
X.append(tmp)
y.append(create_one_hot(len(labels), labels[label]))
oov_file.close()
print (NUM_OOV_TOKENS, NUM_TOKENS, NUM_OOV_TOKENS/NUM_TOKENS)
return np.asarray(X), np.asarray(y), np.asarray(queries)
def read_records(fn, vocab, labels_file):
"""
reads the train and test file and vectorizes sequences with word indexes
returns X and y
"""
with open(labels_file) as labs:
labels = {lab.strip(): i for i, lab in enumerate(labs)}
NUM_OOV_TOKENS = 0
NUM_TOKENS = 0
X,y = [], []
queries = []
oov_file = open("oov_file.txt", 'w')
with open(fn) as infile:
for line in infile:
# read line
line = ast.literal_eval(line)
sent = line[1]
e1, e2 = line[2]-1, line[3]
label = line[4]
# vectorize the relation
tmp = []
for w in sent[e1:e2]:
NUM_TOKENS += 1
w = ''.join('#' if char.isdigit() else char for char in w)
w = ''.join('_' if char == '-' else char for char in w)
# handling OOV tokens is a long story and requires some discussion...
# decided to normalize word, strip punctuation, replace digits with #, lemmatize if necessary, just take the last token of MWE if necessary
# reduces OOV tokens of semeval10 training file to 0.6%, seems ok
if w in vocab:
# if the word appears in the vocab, we don't have a problem
tmp.append(vocab[w])
else:
tmp.append(lookup(w, vocab))
if tmp[-1] == vocab["__UNKNOWN__"]:
NUM_OOV_TOKENS += 1
oov_file.write(w + "\n")
queries_tmp = [tmp[0], tmp[-1]]
queries.append(queries_tmp)
#tmp = np.concatenate((np.zeros(32 - len(tmp)), tmp))
X.append(tmp)
y.append(create_one_hot(len(labels), labels[label]))
oov_file.close()
print (NUM_OOV_TOKENS, NUM_TOKENS, NUM_OOV_TOKENS/NUM_TOKENS)
return np.asarray(X), np.asarray(y), np.asarray(queries)
def compute_batch_attention(Xs, Ys, old, new, queries):
# compute a batch dynamically, especially the lengths of the sentences in the batch
xs = Xs[old:new]
ys = Ys[old:new]
this_queries = queries[old:new]
lens = [len(x) for x in xs]
max_length = max(lens)
xs = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in xs]
return xs, ys, lens, np.expand_dims([x[0] for x in this_queries], axis=-1), np.expand_dims([x[1] for x in this_queries], axis=-1)
def compute_whole_set_attention(xs, queries):
# vectorize the whole set
lens = [len(x) for x in xs]
max_length = max(lens)
xs = [np.concatenate((x,np.zeros(max_length - len(x)))) for x in xs]
return xs, lens, np.expand_dims([x[0] for x in queries],axis=-1), np.expand_dims([x[1] for x in queries],axis=-1)
<file_sep>/vanilla_lstm.py
from data_load import *
import tensorflow as tf
import os
import numpy as np
from evaluate import macro_f1
flags = tf.flags
# initialize some parameters
flags.DEFINE_string("data_path", "features", "Where the training/test data is stored.")
flags.DEFINE_string("train_file", "record_train_ace2005", "Name of training file")
flags.DEFINE_string("test_file", "record_test_ace2005", "Name of test file")
flags.DEFINE_bool("fire_embeddings", True, "our main feature, should be True")
flags.DEFINE_integer("hidden_units", 128, "number of hidden units")
flags.DEFINE_float("learning_rate", 0.001, "")
flags.DEFINE_integer("num_labels", 19, "for dev purposes")
flags.DEFINE_integer("batch_size", 32, "")
flags.DEFINE_float("dropout", 0.9, "dropout")
FLAGS = flags.FLAGS
vocab_file = "../gridsearch/features/numberbatch-en-17.06.txt"
record_train = "../gridsearch/features/record_train_ace2005.txt"
record_test = "../gridsearch/features/record_test_ace2005.txt"
labels_file = "../gridsearch/features/labels_ace2005.txt"
# load labels
labels2id, id2labels = load_labels(labels_file)
# load embeddings, vocab, train and test vectors
embs, vocab = read_embeddings(vocab_file)
x_train, y_train, queries = read_records(record_train, vocab, labels_file)
x_test, y_test, queries_test = read_records(record_test, vocab, labels_file)
vocab_size = np.shape(embs)[0]
embs_size = np.shape(embs)[1]
# initialize the embeddings matrix in tensorflow
embeddings = tf.get_variable("embedding", [vocab_size, embs_size], initializer=tf.constant_initializer(embs),dtype=tf.float32)
# some placeholders to define the computation graph
x = tf.placeholder(tf.int32, shape=[None, None])
y = tf.placeholder(tf.int32, shape=[None, FLAGS.num_labels])
sequence_lengths = tf.placeholder(tf.int32, shape=[None])
# first a word lookup
inputs = tf.nn.embedding_lookup(embeddings, x)
# the LSTM cells with dropout
cell_fw = tf.contrib.rnn.LSTMCell(FLAGS.hidden_units)
cell_fw = tf.contrib.rnn.DropoutWrapper(cell_fw, output_keep_prob=FLAGS.dropout)
cell_bw = tf.contrib.rnn.LSTMCell(FLAGS.hidden_units)
cell_bw = tf.contrib.rnn.DropoutWrapper(cell_bw, output_keep_prob=FLAGS.dropout)
# the actual LSTM
(output_fw, output_bw), (f1, f2) = tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, inputs, sequence_length=sequence_lengths, dtype=tf.float32)
concat = tf.concat([f1.h, f2.h], axis=-1)
# two more fully connected layers on top
second_last_layer = tf.nn.dropout(tf.layers.dense(inputs=concat,units=FLAGS.hidden_units, activation = tf.tanh), FLAGS.dropout)
output_weights = tf.get_variable("W_out", shape=[FLAGS.hidden_units, FLAGS.num_labels], dtype=tf.float32)
output_biases = tf.get_variable("B_out", shape=[FLAGS.num_labels], dtype=tf.float32, initializer=tf.zeros_initializer())
# unnormalized outputs
logits = tf.matmul(second_last_layer, output_weights) + output_biases
# cost function
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
# optimize the lossfunction
# take random optimizer, RMSProp is a good default one, given that the hyperparameters don't matter that much
optimizer = tf.train.RMSPropOptimizer(learning_rate=FLAGS.learning_rate).minimize(cost)
# to do the actual prediction
preds = tf.nn.softmax(logits)
# take the argmax of the output vector
labels_pred = tf.cast(tf.argmax(preds, axis=-1), tf.int32)
# so far, we only defined the computation graph, now we do actual predictions
acc = 0
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print (np.shape(x_train), np.shape(y_train), np.shape(x_test), np.shape(y_test))
# just do it for 10 steps and see what happens
for epoch in range(20):
# shuffle the set
p = np.random.permutation(len(x_train))
x_train, y_train = x_train[p], y_train[p]
# do batchwise optimization
for batch in range(int(len(x_train)/FLAGS.batch_size)):
# compute batch dynamically (especially for the lens of the vector to let the LSTM stop early after it reached the end of a batch
xs, ys, lens = compute_batch_LSTM(x_train, y_train, batch * FLAGS.batch_size, (batch + 1) * FLAGS.batch_size)
# perform the optimization step
preds = sess.run(optimizer, feed_dict={x: xs, y: ys, sequence_lengths: lens})
# show progress
whole_x, lens = compute_whole_set_LSTM(x_train)
labs = sess.run(labels_pred, feed_dict={x:whole_x, y:y_train, sequence_lengths:lens})
acc_new = sum([1 for i,j in zip(labs, y_train) if i == np.argmax(j)])/len(y_train)
print ("epoch", epoch, "accuracy", acc_new)
whole_test, lens = compute_whole_set_LSTM(x_test)
labs = sess.run(labels_pred, feed_dict={x:whole_test, y:y_test, sequence_lengths:lens})
acc_new = sum([1 for i,j in zip(labs, y_test) if i == np.argmax(j)])/len(y_test)
print ("testset acc:", acc_new)
print (macro_f1([id2labels[np.argmax(i)] for i in y_test], [id2labels[i] for i in labs]))
# best is
# epoch 7 accuracy 0.914375
# testset acc: 0.7615016562384983
# ('79.72', '80.22', '79.92')
<file_sep>/evaluate.py
from collections import defaultdict
from sklearn.metrics import f1_score
import ast
import argparse
def f1(y_true, y_pred):
d = defaultdict(int)
for i,j in zip(y_true, y_pred):
if i == j:
d[i +"_TP"] += 1
else:
d[j + "_FP"] += 1
d[i + "_FN"] += 1
TP = 0
FP = 0
FN = 0
for i,j in d.items():
if i.endswith("_TP") and i != args.OTHER_RELATION + "_TP":
TP += j
if i.endswith("_FP") and i != args.OTHER_RELATION + "_FP":
FP += j
if i.endswith("_FN") and i != args.OTHER_RELATION + "_FN":
FN += j
Pr = TP/(TP + FP)
Rc = TP/(TP + FN)
F1 = (2 * Pr * Rc) / (Pr + Rc)
#return TP, FP, FN, "Precision: " + "{0:.2f}".format(Pr * 100), "Recall: " + "{0:.2f}".format(Rc * 100), "F1 measure: " + "{0:.2f}".format(F1 * 100)
return "{0:.2f}".format(Pr * 100), "{0:.2f}".format(Rc * 100), "{0:.2f}".format(F1 * 100)
def macro_f1(y_true, y_pred):
OTHER = "Other"
d = defaultdict(int)
for i,j in zip(y_true, y_pred):
if i == j:
d[i.split("(")[0] +"_TP"] += 1
else:
d[j.split("(")[0] + "_FP"] += 1
d[i.split("(")[0] + "_FN"] += 1
TP = 0
FP = 0
FN = 0
items = set()
for key in d:
items.add(key.split("_")[0])
items.remove(OTHER)
pr, rc, f = 0,0,0
for item in items:
t_pr = d[item + "_TP"] / (d[item + "_TP"] + d[item + "_FP"])
t_rc = d[item + "_TP"] / (d[item + "_TP"] + d[item + "_FN"])
pr += t_pr
rc += t_rc
f += 2 * t_pr * t_rc / (t_pr + t_rc)
Pr = pr /len(items)
Rc = rc / len(items)
F1 = f / len(items)
#return TP, FP, FN, "Precision: " + "{0:.2f}".format(Pr * 100), "Recall: " + "{0:.2f}".format(Rc * 100), "F1 measure: " + "{0:.2f}".format(F1 * 100)
return "{0:.2f}".format(Pr * 100), "{0:.2f}".format(Rc * 100), "{0:.2f}".format(F1 * 100)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--params', default='vanilla', type=str)
parser.add_argument('--OTHER_RELATION', default='NO_RELATION(Arg-1,Arg-1)', type=str)
parser.add_argument('--result_file', default='results.txt', type=str)
parser.add_argument('--metric', default='micro', type=str)
args = parser.parse_args()
s_1, s_2 = [], []
with open("models/s4c01e03_predictions_with_labels_ace2005.txt") as infile:
for line in infile:
line = line.strip().split("\t")
s_2.append(line[-1])
with open("answer_key10_ace2005.txt") as infile:
for line in infile:
line = line.strip().split("\t")
s_1.append(line[-1])
t_1, t_2 = [], []
for i,j in zip(s_1, s_2):
#if i != "NO_RELATION(Arg-1,Arg-1)":
if i != "Other":
t_1.append(i)
t_2.append(j)
with open(args.result_file, 'a') as outfile:
"""
print (len(t_1), len(t_2))
print ("macro without NON_RELATION", f1_score(t_1, t_2, average="macro"))
print ("micro without NON_RELATION", f1_score(t_1, t_2, average="micro"))
print ("weighted without NON_RELATION", f1_score(t_1, t_2, average="weighted"))
print ("accuracy without NON_RELATION", sum([1 for i,j in zip(t_1,t_2) if i==j])/len(t_1))
"""
if args.metric == "micro":
scores = f1(s_1, s_2)
elif args.metric == "macro":
scores = macro_f1(s_1, s_2)
outfile.write(args.params + " & " + scores[0] + " & " + scores[1] + " & " + scores[2] + "\n")
<file_sep>/find_parameters_ace.sh
#!/bin/bash
s=4
c=0.1
e=0.3
out_name="s${s//.}c${c//.}e${e//.}"
mainDir=$(pwd)
featDir=${mainDir}"/features/"
modelDir=${mainDir}"/models/"
# vanilla test:
python3 featureExtraction_ace.py
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python evaluate.py --result_file ace_results.txt
# W = 2:
python3 featureExtraction_ace.py --W 2
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --W 2 --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python evaluate.py --result_file ace_results.txt --params W_2
# fire positions:
python3 featureExtraction_ace.py
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_positions --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_positions_true --result_file ace_results.txt
# fire shapes:
#python3 featureExtraction_ace.py --fire_positions True
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_shapes --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_shapes_true --result_file ace_results.txt
# fire char embeddings:
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_char_embeddings --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_char_embeddings_true --result_file ace_results.txt
# fire marlin clusters:
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_clusters --marlin --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_clusters_marlin_true --result_file ace_results.txt
# fire brown clusters:
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_clusters --brown --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_clusters_brown_true --result_file ace_results.txt
# fire suffixes:
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_suffixes --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_suffixes_true --result_file ace_results.txt
# fire suffixes length 3:
python3 featureExtraction_ace.py --max_suffix_size 3
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_suffixes --max_suffix_size 3 --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_suffixes_true_size_3 --result_file ace_results.txt
# fire types
python3 featureExtraction_ace.py
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --fire_types --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_fire_types --result_file ace_results.txt
# downsample others
python3 sent2vec_ace.py --fire_words --fire_embeddings --after_e1 --adjust_ratio --use_avg_M
cd ../liblinear-2.20
echo "---training LibLinear model---"
./train -s ${s} -c ${c} -e ${e} ${modelDir}"libLinearInput_train_ace2005.txt" ${modelDir}${out_name}"_ace2005.model"
echo "---predicting on test set---"
./predict ${modelDir}"libLinearInput_test_ace2005.txt" ${modelDir}${out_name}"_ace2005.model" ${modelDir}${out_name}"_predictions_ace2005.txt"
cd ${mainDir}
echo "---adding labels to LibLinear output---"
python3 addLabels10_ace2005.py ${s} ${c} ${e}
echo "---scoring model---"
#perl ${semEvalScorerDir}"/semeval2010_task8_scorer-v1.2_for_ace.pl" ${modelDir}${out_name}"_predictions_with_labels_ace2005.txt" answer_key10_ace2005.txt
python3 evaluate.py --params fire_downsample_others --result_file ace_results.txt
<file_sep>/feature_Extraction_riedel_2010.py
import Document_pb2
import os
import time
from google.protobuf.internal.encoder import _VarintBytes
from google.protobuf.internal.decoder import _DecodeVarint32
import re
# https://www.datadoghq.com/blog/engineering/protobuf-parsing-in-python/
# tar -xvf manual-05-06.tgz
def read_file(filename, g_sid, g_tid):
"""
from: 11
to: 14
label: "ORGANIZATION"
"""
pattern = re.compile("from: (.*?)\n")
with open(filename, 'rb') as f:
buf = f.read()
n = 0
read_document = Document_pb2.Document()
read_document.ParseFromString(buf)
for sent in read_document.sentences:
sid_flag, tid_flag = False, False
for mention in sent.mentions:
tid = mention.id
# f, t = mention.from, mention.to
if g_tid == tid:
tid_from = re.findall(pattern, str(mention))[0]
tid_to = mention.to
tid_flag = True
if g_sid == tid:
sid_from = re.findall(pattern, str(mention))[0]
sid_to = mention.to
sid_flag = True
if sid_flag and tid_flag:
# this is the sentence...
tokens = []
for token in sent.tokens:
tokens.append(token.word)
return tokens, int(sid_from), sid_to, int(tid_from), tid_to
def read_relations(fn):
sentence_id = 1
"""
sourceGuid: "/guid/9202a8c04000641f8000000000078105"
destGuid: "/guid/9202a8c04000641f800000000006bea9"
relType: "/people/person/place_of_birth"
mention {
filename: "/m/vinci8/data1/riedel/projects/relation/kb/nyt1/docstore/2007-joint/1835479.xml.pb"
sourceId: -2147483641
destId: -2147483642
feature: "PERSON->LOCATION"
feature: "inverse_false|PERSON|set in fin-de-si \303\250cle|LOCATION"
feature: "inverse_false|by|PERSON|set in fin-de-si \303\250cle|LOCATION|,"
feature: "inverse_false|story by|PERSON|set in fin-de-si \303\250cle|LOCATION|, opens"
feature: "inverse_false|PERSON|VBD IN JJ NN|LOCATION"
feature: "inverse_false|by|PERSON|VBD IN JJ NN|LOCATION|,"
feature: "inverse_false|story by|PERSON|VBD IN JJ NN|LOCATION|, opens"
feature: "str:Arthur[NMOD]->|PERSON|[PMOD]->by[NMOD]->story[PMOD]->on[ADV]->based[NMOD]->operetta[NMOD]->Comedy[SBJ]->set[ROOT]<-in[ADV]<-|LOCATION|[NMOD]->fin-de-si"
feature: "str:Arthur[NMOD]->|PERSON|[PMOD]->by[NMOD]->story[PMOD]->on[ADV]->based[NMOD]->operetta[NMOD]->Comedy[SBJ]->set[ROOT]<-in[ADV]<-|LOCATION|[NMOD]->\303\250cle"
feature: "str:Arthur[NMOD]->|PERSON|[PMOD]->by[NMOD]->story[PMOD]->on[ADV]->based[NMOD]->operetta[NMOD]->Comedy[SBJ]->set[ROOT]<-in[ADV]<-|LOCATION"
feature: "dep:[NMOD]->|PERSON|[PMOD]->[NMOD]->[PMOD]->[ADV]->[NMOD]->[NMOD]->[SBJ]->[ROOT]<-[ADV]<-|LOCATION"
feature: "dir:->|PERSON|->->->->->->-><-<-|LOCATION"
feature: "str:PERSON|[PMOD]->by[NMOD]->story[PMOD]->on[ADV]->based[NMOD]->operetta[NMOD]->Comedy[SBJ]->set[ROOT]<-in[ADV]<-|LOCATION|[NMOD]->fin-de-si"
feature: "dep:PERSON|[PMOD]->[NMOD]->[PMOD]->[ADV]->[NMOD]->[NMOD]->[SBJ]->[ROOT]<-[ADV]<-|LOCATION|[NMOD]->"
feature: "dir:PERSON|->->->->->->-><-<-|LOCATION|->"
feature: "str:PERSON|[PMOD]->by[NMOD]->story[PMOD]->on[ADV]->based[NMOD]->operetta[NMOD]->Comedy[SBJ]->set[ROOT]<-in[ADV]<-|LOCATION|[NMOD]->\303\250cle"
feature: "dep:PERSON|[PMOD]->[NMOD]->[PMOD]->[ADV]->[NMOD]->[NMOD]->[SBJ]->[ROOT]<-[ADV]<-|LOCATION|[NMOD]->"
feature: "dir:PERSON|->->->->->->-><-<-|LOCATION|->"
feature: "str:PERSON|[PMOD]->by[NMOD]->story[PMOD]->on[ADV]->based[NMOD]->operetta[NMOD]->Comedy[SBJ]->set[ROOT]<-in[ADV]<-|LOCATION"
sentence: "The Little Comedy , \'\' a mannered operetta based on a short story by <NAME> set in fin-de-si \303\250cle Vienna , opens the evening ."
}
"""
outfile = open("features_" + fn.split("/")[-1], 'w')
counter_fail = 0
with open(fn, "rb") as f:
buf = f.read()
n = 0
while n < len(buf):
msg_len, new_pos = _DecodeVarint32(buf, n)
n = new_pos
msg_buf = buf[n:n+msg_len]
n += msg_len
read_relation = Document_pb2.Relation()
read_relation.ParseFromString(msg_buf)
# sourceGuid: "/guid/9202a8c04000641f800000000006daf1"
# destGuid: "/guid/9202a8c04000641f800000000001de10"
# relType: "/people/person/nationality"
# mention {
sGuid = read_relation.sourceGuid
tGuid = read_relation.destGuid
reltype = read_relation.relType
for mention in read_relation.mention:
filename = mention.filename
sId = mention.sourceId
dId = mention.destId
# type list
feature = mention.feature
sent = mention.sentence
if os.path.isfile(os.path.join("nyt-2005-2006.backup",filename.split("/")[-1])):
tokens, sid_from, sid_to, tid_from, tid_to = read_file(os.path.join("nyt-2005-2006.backup",filename.split("/")[-1]), sId, dId)
if tid_from < sid_from:
sid_from, tid_from = tid_from, sid_from
sid_to, tid_to = tid_to, sid_to
e1 = "_".join(tokens[sid_from:sid_to + 1])
e2 = "_".join(tokens[tid_from:tid_to + 1])
t_new = []
for j,t in enumerate(tokens):
if j == sid_from:
t_new.append(e1)
if j >= sid_from and j <= sid_to:
continue
if j == tid_from:
t_new.append(e2)
if j >= tid_from and j <= tid_to:
continue
else:
t_new.append(t)
e1 = sid_from
e2 = tid_from - (sid_to - sid_from)
to_write = str(tuple([sentence_id, t_new, e1 + 1, e2 + 1, reltype, len(t_new), e2 - e1 - 1, e1, len(t_new) - e2 - 1]))
outfile.write(to_write + "\n")
sentence_id += 1
else:
counter_fail += 1
debug_file.write("features_" + fn.split("/")[-1] + "\tfailed" + str(counter_fail) + "\n")
outfile.close()
def read_entity(fn):
pattern = re.compile("guid:(.*)\n")
entities = []
with open(fn, "rb") as f:
buf = f.read()
n = 0
while n < len(buf):
msg_len, new_pos = _DecodeVarint32(buf, n)
n = new_pos
msg_buf = buf[n:n+msg_len]
n += msg_len
read_entity = Document_pb2.Entity()
read_entity.ParseFromString(msg_buf)
guid = re.findall(pattern, str(read_entity))
#print (read_entity)
#print (guid[0].strip().strip('"'))
print (len(read_entity.ListFields()))
# guid
print (read_entity.ListFields()[0])
# name
print (read_entity.ListFields()[1])
# type
print (read_entity.ListFields()[2])
# pred
print (read_entity.ListFields()[3])
# mentions
time.sleep(2)
"""
# this works
file_path = "nyt-2005-2006.backup"
files = os.listdir(file_path)
files = ["1662854.xml.pb"]
for fn in files:
infile = read_file(os.path.join(file_path, fn))
break
"""
# this too
debug_file = open("statistics_readel_2010.txt", 'w')
file_path = "heldout_relations"
files = os.listdir(file_path)
for fn in files:
print (fn)
read_relations(os.path.join(file_path, fn))
sys.exit(0)
"""
sourceGuid: "/guid/9202a8c04000641f800000000006daf1"
destGuid: "/guid/9202a8c04000641f800000000001de10"
relType: "/people/person/nationality"
mention {
filename: "/m/vinci8/data1/riedel/projects/relation/kb/nyt1/docstore/2007-joint/1852805.xml.pb"
sourceId: -2147483641
destId: -2147483643
feature: "PERSON->LOCATION"
feature: "inverse_false|PERSON|, who was president of Banco Ambrosiano , one of|LOCATION"
feature: "inverse_false|murder|PERSON|, who was president of Banco Ambrosiano , one of|LOCATION|\'s"
feature: "inverse_false|to murder|PERSON|, who was president of Banco Ambrosiano , one of|LOCATION|\'s largest"
feature: "inverse_false|PERSON|, WP VBD NN IN NNP NNP , CD IN|LOCATION"
feature: "inverse_false|murder|PERSON|, WP VBD NN IN NNP NNP , CD IN|LOCATION|\'s"
feature: "inverse_false|to murder|PERSON|, WP VBD NN IN NNP NNP , CD IN|LOCATION|\'s largest"
feature: "str:murder[NMOD]->|PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION|[NMOD]->\'s"
feature: "str:Roberto[NMOD]->|PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION|[NMOD]->\'s"
feature: "str:,[P]->|PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION|[NMOD]->\'s"
feature: "str:to[ADV]<-|PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION|[NMOD]->\'s"
feature: "str:murder[NMOD]->|PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION"
feature: "dep:[NMOD]->|PERSON|[PMOD]<-[NMOD]<-[PRD]<-[NMOD]<-[PMOD]<-[NMOD]<-[NMOD]<-[PMOD]<-|LOCATION"
feature: "dir:->|PERSON|<-<-<-<-<-<-<-<-|LOCATION"
feature: "str:Roberto[NMOD]->|PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION"
feature: "dep:[NMOD]->|PERSON|[PMOD]<-[NMOD]<-[PRD]<-[NMOD]<-[PMOD]<-[NMOD]<-[NMOD]<-[PMOD]<-|LOCATION"
feature: "dir:->|PERSON|<-<-<-<-<-<-<-<-|LOCATION"
feature: "str:,[P]->|PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION"
feature: "dep:[P]->|PERSON|[PMOD]<-[NMOD]<-[PRD]<-[NMOD]<-[PMOD]<-[NMOD]<-[NMOD]<-[PMOD]<-|LOCATION"
feature: "dir:->|PERSON|<-<-<-<-<-<-<-<-|LOCATION"
feature: "str:to[ADV]<-|PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION"
feature: "dep:[ADV]<-|PERSON|[PMOD]<-[NMOD]<-[PRD]<-[NMOD]<-[PMOD]<-[NMOD]<-[NMOD]<-[PMOD]<-|LOCATION"
feature: "dir:<-|PERSON|<-<-<-<-<-<-<-<-|LOCATION"
feature: "str:PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION|[NMOD]->\'s"
feature: "dep:PERSON|[PMOD]<-[NMOD]<-[PRD]<-[NMOD]<-[PMOD]<-[NMOD]<-[NMOD]<-[PMOD]<-|LOCATION|[NMOD]->"
feature: "dir:PERSON|<-<-<-<-<-<-<-<-|LOCATION|->"
feature: "str:PERSON|[PMOD]<-was[NMOD]<-president[PRD]<-of[NMOD]<-Ambrosiano[PMOD]<-one[NMOD]<-of[NMOD]<-banks[PMOD]<-|LOCATION"
sentence: "A court in Rome acquitted five people accused of conspiring to murder <NAME> , who was president of <NAME>iano , one of Italy \'s largest private banks , and a financial adviser to the Vatican when he was found hanged under Blackfriars Bridge in London in 1982 , his pockets stuffed with rocks , bricks and cash ."
}
"""
file_path = "kb_manual"
files = os.listdir(file_path)
files = ["testNewEntities.pb"]
for fn in files:
read_entity(os.path.join(file_path, fn))
break
"""
guid: "guid0"
name: "WKCR"
type: ""
pred: "person"
mention {
filename: "/m/vinci8/data1/riedel/projects/relation/kb/nyt1/docstore/2007/1850511.xml.pb"
id: -2147483641
feature: "by@head"
feature: "IN@hpos"
feature: "ORGANIZATION"
feature: "WKCR"
feature: "WKCR"
feature: "by@-1"
feature: "VBN IN@-2-1"
feature: "the@+1"
feature: "the student-run@+1+2"
}
mention {
filename: "/m/vinci8/data1/riedel/projects/relation/kb/nyt1/docstore/2007/1849689.xml.pb"
id: -2147483646
feature: "station@head"
feature: "NN@hpos"
feature: "ORGANIZATION"
feature: "WKCR"
feature: "WKCR"
feature: ",@-1"
feature: "NN ,@-2-1"
feature: "B_1@+1"
feature: "B_1 B_2@+1+2"
}
mention {
filename: "/m/vinci8/data1/riedel/projects/relation/kb/nyt1/docstore/2007/1849689.xml.pb"
id: -2147483635
feature: "marched@head"
feature: "VBD@hpos"
feature: "ORGANIZATION"
feature: "WKCR"
feature: "WKCR"
feature: "week@-1"
feature: "DT NN@-2-1"
feature: "through@+1"
feature: "through that@+1+2"
}
guid: "guid3"
name: "<NAME>"
type: ""
pred: "person"
mention {
filename: "/m/vinci8/data1/riedel/projects/relation/kb/nyt1/docstore/2007/1850511.xml.pb"
id: -2147483643
feature: "of@head"
feature: "IN@hpos"
feature: "ORGANIZATION"
feature: "Sam"
feature: "Rivers"
feature: "Trio"
feature: "<NAME>"
feature: "1970s-era@-1"
feature: "DT CD@-2-1"
feature: "with@+1"
feature: "with Dave@+1+2"
}
mention {
filename: "/m/vinci8/data1/riedel/projects/relation/kb/nyt1/docstore/2007/1849689.xml.pb"
id: -2147483633
feature: "performs@head"
feature: "VBZ@hpos"
feature: "ORGANIZATION"
feature: "Sam"
feature: "Rivers"
feature: "Trio"
feature: "<NAME>"
feature: "The@-1"
feature: "-LRB- DT@-2-1"
feature: "tonight@+1"
feature: "tonight at@+1+2"
}
mention {
filename: "/m/vinci8/data1/riedel/projects/relation/kb/nyt1/docstore/2007/1849689.xml.pb"
id: -2147483641
feature: "of@head"
feature: "IN@hpos"
feature: "PERSON"
feature: "Sam"
feature: "Rivers"
feature: "Trio"
feature: "<NAME>"
feature: "1970s@-1"
feature: "DT CD@-2-1"
feature: "with@+1"
feature: "with Dave@+1+2"
}
"""
| c82de68628359bb6c0c0f0ab8eb872f2a064cf0e | [
"Python",
"Shell"
] | 10 | Python | dominiksinsaarland/my_stuff | 709b3dda13cc4f9dc956c4cdb7b7444f9d3435ce | c8edc7d04723926b30e8115a2a07b183e0a99e15 |
refs/heads/main | <repo_name>FriederikeM/javascript-dom-exercises<file_sep>/1-hello-world/solution.js
let h1 = document.querySelector("h1");
h1.textContent = "Hello World, I'm Rikki";
<file_sep>/7-rainbow/solution.js
let button = document.querySelector("button");
let li = document.querySelectorAll(".list__item");
button.addEventListener("click", () => {
li[0].style.color = "red";
li[1].style.color = "orange";
li[2].style.color = "yellow";
li[3].style.color = "green";
li[4].style.color = "blue";
li[5].style.color = "indigo";
li[6].style.color = "violet";
});
<file_sep>/6-fancy-hello-world/solution.js
let input = document.querySelector("input");
let h1 = document.querySelector("h1");
input.addEventListener("input", () => {
h1.textContent = `Hello World, ${input.value}`;
});
<file_sep>/3-toggling-classes/solution.js
let h1 = document.querySelector("h1");
h1.classList.toggle("super-header");
<file_sep>/8-form/solution.js
const button = document.querySelector("button");
const form = document.querySelector("form");
const data = [];
form.addEventListener("submit", (event) => {
event.preventDefault();
const person = {
nameInput: form["name"].value,
ageInput: form["age"].value,
marriedInput: form["married"].checked,
hobbiesInput: form["hobbies"].value,
};
data.push(person);
console.log(data);
form.reset();
});
| d8b611f42d04a32e39304dc3250900439a456a63 | [
"JavaScript"
] | 5 | JavaScript | FriederikeM/javascript-dom-exercises | b0de7935dc1bd8f709a937f18425e62bb38a0fb4 | d4cdedec65291793b14d367a146e4aa957e37fc1 |
refs/heads/master | <file_sep>using System;
using System.Reflection;
using AspnetWebApi2Helpers.Serialization.Protobuf.Internal;
using JetBrains.Annotations;
using WebApiContrib.Formatting;
namespace AspnetWebApi2Helpers.Serialization.Protobuf
{
/// <summary>
/// Extension methods for configuring ProtoBuf media type formatter to handle cyclical references.
/// </summary>
public static class ProtobufFormatterExtensions
{
/// <summary>
/// Configure serializer for ProtoBufFormatter to handle cyclical references.
/// </summary>
/// <param name="protoBufFormatter">ProtoBuf media type formatter</param>
/// <param name="types">One or more types to be configured.</param>
public static void ProtobufPreserveReferences([NotNull] this ProtoBufFormatter protoBufFormatter,
[NotNull] params Type[] types)
{
ProtobufFormatterHelper.ConfigureProtobufFormatter(types);
}
/// <summary>
/// Configure serializer for ProtoBufFormatter to handle cyclical references.
/// </summary>
/// <param name="protoBufFormatter">ProtoBuf media type formatter</param>
/// <param name="assembly">Assembly containing types to be configured.</param>
public static void ProtobufPreserveReferences([NotNull] this ProtoBufFormatter protoBufFormatter,
[NotNull] Assembly assembly)
{
ProtobufPreserveReferences(protoBufFormatter, assembly.GetTypes());
}
}
}
<file_sep>using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Reflection;
using JetBrains.Annotations;
using ProtoBuf.Meta;
using WebApiContrib.Formatting;
namespace AspnetWebApi2Helpers.Serialization.Protobuf.Internal
{
/// <summary>
/// Utility methods for configuring Protobuf formatters.
/// </summary>
public static class ProtobufFormatterHelper
{
/// <summary>
/// Configure one or more types to handle cyclical references with Protobuf.
/// </summary>
/// <param name="types">Array of types.</param>
public static void ConfigureProtobufFormatter([NotNull] params Type[] types)
{
foreach (var type in types)
{
if (!ProtoBufFormatter.Model.GetTypes().OfType<MetaType>().Any(t => t.Type == type))
{
var meta = ProtoBufFormatter.Model.Add(type, false);
var props = type.GetProperties();
for (var i = 0; i < props.Length; i++)
{
meta.Add(i + 1, props[i].Name);
}
meta.AsReferenceDefault = true;
}
}
}
}
}
<file_sep>using AspnetWebApi2Helpers.Serialization.Tests.Common.Entities;
using WebApiContrib.Formatting;
using Xunit;
namespace AspnetWebApi2Helpers.Serialization.Protobuf.Tests
{
public class ProtoBufFormatterExtensionsTests
{
[Fact]
public void ProtoBufFormatter_ProtobufPreserveReferences_should_configure_ProtoBufFormatter()
{
// Arrange
var category = new Category {Name = "Beverages"};
var product = new Product {Name = "Chai", Category = category};
category.Products.Add(product);
var formatter = new ProtoBufFormatter();
// Act
formatter.ProtobufPreserveReferences(typeof(Category).Assembly);
// Assert
var clonedProduct = product.Clone(ProtoBufFormatter.Model);
Assert.Equal(product.Category.Name, clonedProduct.Category.Name);
}
}
}
<file_sep>using System;
using System.Net.Http.Formatting;
using JetBrains.Annotations;
using System.Runtime.Serialization;
namespace AspnetWebApi2Helpers.Serialization
{
/// <summary>
/// Extension methods for configuring Xml media type formatter to handle cyclical references.
/// </summary>
public static class XmlMediaTypeFormatterExtensions
{
/// <summary>
/// Configure serializer for Xml formatter to handle cyclical references.
/// </summary>
/// <param name="xmlFormatter">Xml media type formatter</param>
/// <param name="types">One or more types to be configured.</param>
public static void XmlPreserveReferences([NotNull] this XmlMediaTypeFormatter xmlFormatter, [NotNull] params Type[] types)
{
var settings = new DataContractSerializerSettings
{
PreserveObjectReferences = true
};
foreach (var type in types)
{
var serializer = new DataContractSerializer(type, settings);
xmlFormatter.SetSerializer(type, serializer);
}
}
}
}<file_sep>using System.Net.Http.Formatting;
using System.Runtime.Serialization;
using AspnetWebApi2Helpers.Serialization.Tests.Common;
using AspnetWebApi2Helpers.Serialization.Tests.Common.Entities;
using Xunit;
namespace AspnetWebApi2Helpers.Serialization.Tests
{
public class XmlMediaTypeFormatterExtensionsTests
{
[Fact]
public void XmlFormatter_XmlPreserveReferences_should_configure_XmlFormatter()
{
// Arrange
var category = new Category {Name = "Beverages"};
var product = new Product {Name = "Chai", Category = category};
category.Products.Add(product);
var formatter = new XmlMediaTypeFormatter();
// Act
formatter.XmlPreserveReferences(typeof(Category), typeof(Product));
// Assert
var serializer = formatter.InvokeGetSerializer(typeof (Product),
null, null) as DataContractSerializer;
var clonedProduct = product.Clone(serializer);
Assert.Equal(product.Category.Name, clonedProduct.Category.Name);
}
}
}
<file_sep>using System.Net.Http.Formatting;
using JetBrains.Annotations;
using Newtonsoft.Json;
namespace AspnetWebApi2Helpers.Serialization
{
/// <summary>
/// Extension methods for configuring formatters to handle cyclical references.
/// </summary>
public static class MediaTypeFormatterCollectionExtensions
{
/// <summary>
/// Configure JsonFormatter to handle cyclical references.
/// </summary>
/// <param name="formatters">Collection class that contains <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> instances.</param>
public static void JsonPreserveReferences([NotNull] this MediaTypeFormatterCollection formatters)
{
formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling =
PreserveReferencesHandling.All;
}
/// <summary>
/// Configure XmlFormatter to handle cyclical references.
/// </summary>
/// <param name="formatters">Collection class that contains <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> instances.</param>
public static void XmlPreserveReferences([NotNull] this MediaTypeFormatterCollection formatters)
{
formatters.Remove(formatters.XmlFormatter);
var xmlFormatter = new XmlDataContractSerializerFormatter
{
SerializerSettings = {PreserveObjectReferences = true}
};
formatters.Add(xmlFormatter);
}
}
}
<file_sep>Client Sample ReadMe
This demonstrates how to use AspNetWebApi2Helpers.Serialization package
to configure Json, Xml and Protobuf formatters to handle cyclical references.
1. Add the NuGet package: AspNetWebApi2Helpers.Serialization
- If necessary include pre-released packages
- This will also add the Microsoft.AspNet.WebApi.Client package
<file_sep>using System.Web.Http;
using AspnetWebApi2Helpers.Sample.Entities;
using AspnetWebApi2Helpers.Serialization;
using AspnetWebApi2Helpers.Serialization.Protobuf;
namespace AspnetWebApi2Helpers.Sample.Web
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Formatters.JsonPreserveReferences();
config.Formatters.XmlPreserveReferences();
config.Formatters.ProtobufPreserveReferences(typeof(Category).Assembly);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
<file_sep>using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Reflection;
using AspnetWebApi2Helpers.Serialization.Protobuf.Internal;
using JetBrains.Annotations;
using Newtonsoft.Json;
using WebApiContrib.Formatting;
namespace AspnetWebApi2Helpers.Serialization.Protobuf
{
/// <summary>
/// Extension methods for configuring formatters to handle cyclical references.
/// </summary>
public static class MediaTypeFormatterCollectionExtensions
{
/// <summary>
/// Configure one or more types to handle cyclical references with Protobuf.
/// </summary>
/// <param name="formatters">Collection class that contains <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> instances.</param>
/// <param name="types">Array of types.</param>
public static void ProtobufPreserveReferences([NotNull] this MediaTypeFormatterCollection formatters, [NotNull] params Type[] types)
{
// Configure protobuf formatter to handle cyclical references
ProtobufFormatterHelper.ConfigureProtobufFormatter(types);
// Remove protobuf formatters
var protoBufFormatter = formatters.SingleOrDefault(f => f.GetType() == typeof(ProtoBufFormatter));
if (protoBufFormatter != null)
formatters.Remove(protoBufFormatter);
// Add protobuf formatters
formatters.Add(new ProtoBufFormatter());
}
/// <summary>
/// Configure all types in an assembly to handle cyclical references with Protobuf.
/// </summary>
/// <param name="formatters">Collection class that contains <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> instances.</param>
/// <param name="assembly">Managed assembly.</param>
public static void ProtobufPreserveReferences([NotNull] this MediaTypeFormatterCollection formatters, [NotNull] Assembly assembly)
{
ProtobufPreserveReferences(formatters, assembly.GetTypes());
}
}
}
<file_sep>using System.IO;
using System.Runtime.Serialization;
namespace AspnetWebApi2Helpers.Serialization.Tests
{
public static class TestHelper
{
public static T Clone<T>(this T obj, XmlObjectSerializer serializer)
{
T copy;
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, obj);
stream.Position = 0;
copy = (T)serializer.ReadObject(stream);
}
return copy;
}
}
}
<file_sep>Web Sample ReadMe
This demonstrates how to use AspNetWebApi2Helpers.Serialization package
to configure Json, Xml and Protobuf formatters to handle cyclical references.
The entities returned by the controllers have cyclical references:
Category references Product, and Product references Category. By default,
trying to serialize either one results in an exception.
1. Run the Web app in the browser
- Click API, Get Categories, Test API, Send
- You should see an error which describes a self-referencing loop
2. Add these NuGet packages:
AspNetWebApi2Helpers.Serialization
AspnetWebApi2Helpers.Serialization.Protobuf
- If necessary include pre-released packages
3. Add code to WebApiConfig.Register:
config.Formatters.JsonPreserveReferences();
config.Formatters.XmlPreserveReferences();
config.Formatters.ProtobufPreserveReferences(typeof(Category).Assembly);
4. Restart the web app and test the controller again
- The action should return entities which contain cyclical references
NOTE: After building and/or running the web app, you may receive the following warning:
"Found conflicts between different versions of the same dependent assembly."
Simply double-click on the warning in the VS 2013 Error List, and the correct
binding redirect will be added to web.config:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0"/>
</dependentAssembly>
<file_sep>ASP.NET Web API 2 Serialization Helpers
=======================
Library with helper classes for configuring input and output formatters to handle cyclical references, which are common with entities generated by ORM tools such as Entity Framework.
### Source
- AspnetWebApi2Helpers.Serialization
+ Extension methods to configure Json and Xml formatters
- AspnetWebApi2Helpers.Serialization.Protobuf
+ Extension methods to configure Protobuf formatter
### Test
- Unit tests for serialization helpers
### Samples
- Sample Web API 2 application
+ Controllers return entities with cyclical references
+ Includes dependencies on AspnetWebApi2Helpers Nuget packages
+ Startup configures Json, Xml and Protobuf formatters to handle cyclical references
<file_sep>using System;
using System.Net.Http.Formatting;
using System.Runtime.Serialization;
using JetBrains.Annotations;
namespace AspnetWebApi2Helpers.Serialization
{
/// <summary>
/// This class handles deserialization of input XML data
/// to strongly-typed objects using <see cref="DataContractSerializer"/>.
/// </summary>
public class XmlDataContractSerializerFormatter : XmlMediaTypeFormatter
{
private DataContractSerializerSettings _serializerSettings = new DataContractSerializerSettings();
/// <summary>
/// Gets or sets the <see cref="DataContractSerializerSettings"/> used to configure the
/// <see cref="DataContractSerializer"/>.
/// </summary>
public DataContractSerializerSettings SerializerSettings
{
get { return _serializerSettings; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_serializerSettings = value;
}
}
/// <summary>
/// Called during deserialization to get the <see cref="T:System.Runtime.Serialization.XmlObjectSerializer"/>.
/// </summary>
/// <returns>
/// The <see cref="T:System.Runtime.Serialization.DataContractSerializer"/> used during deserialization.
/// </returns>
public override DataContractSerializer CreateDataContractSerializer([NotNull] Type type)
{
return new DataContractSerializer(type, _serializerSettings);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using AspnetWebApi2Helpers.Sample.Entities;
using AspnetWebApi2Helpers.Serialization;
using AspnetWebApi2Helpers.Serialization.Protobuf;
using WebApiContrib.Formatting;
namespace AspnetWebApi2Helpers.Sample.Client
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Retrieve entities with cyclical references.");
Console.WriteLine("Use Fiddler? {Y/N}");
bool useFiddler = Console.ReadLine().ToUpper() == "Y";
string fiddlerSuffix = useFiddler ? ".fiddler" : string.Empty;
string address = string.Format("http://localhost{0}:2266/api/", fiddlerSuffix);
MediaTypeFormatter formatter;
string acceptHeader;
while (GetFormatter(out formatter, out acceptHeader))
{
var client = new HttpClient { BaseAddress = new Uri(address) };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
GetCategories(client, formatter);
GetProducts(client, formatter);
}
}
private static bool GetFormatter(out MediaTypeFormatter formatter, out string acceptHeader)
{
Console.WriteLine("\nSelect a formatter: Json {J}, Xml {X}, Protobuf {P}, or exit {Enter}");
string selection = Console.ReadLine().ToUpper();
if (selection == "J")
{
var jsonFormatter = new JsonMediaTypeFormatter();
jsonFormatter.JsonPreserveReferences();
formatter = jsonFormatter;
acceptHeader = MediaTypes.Json;
}
else if (selection == "X")
{
formatter = new XmlDataContractSerializerFormatter();
acceptHeader = MediaTypes.Xml;
}
else if (selection == "P")
{
var protoFormatter = new ProtoBufFormatter();
protoFormatter.ProtobufPreserveReferences(typeof(Category).Assembly);
formatter = protoFormatter;
acceptHeader = MediaTypes.Protobuf;
}
else
{
formatter = null;
acceptHeader = null;
return false;
}
return true;
}
private static void GetProducts(HttpClient client, MediaTypeFormatter formatter)
{
// Get products
var productsResponse = client.GetAsync("products").Result;
productsResponse.EnsureSuccessStatusCode();
// Read categories
var products = productsResponse.Content.ReadAsAsync<List<Product>>(new[] { formatter }).Result;
foreach (var p in products)
{
Console.WriteLine("{0} {1}, Category {2}: {3}",
p.ProductId,
p.ProductName,
p.CategoryId,
p.Category.CategoryName);
}
}
private static void GetCategories(HttpClient client, MediaTypeFormatter formatter)
{
// Get categories
var categoriesResponse = client.GetAsync("categories").Result;
categoriesResponse.EnsureSuccessStatusCode();
// Read categories
var categories = categoriesResponse.Content.ReadAsAsync<List<Category>>(new[] { formatter }).Result;
foreach (var c in categories)
{
Console.WriteLine("{0} {1}, {2} Products",
c.CategoryId,
c.CategoryName,
c.Products.Count);
}
Console.WriteLine();
}
}
}
<file_sep>using System;
using System.Net.Http.Formatting;
using Newtonsoft.Json;
using Xunit;
namespace AspnetWebApi2Helpers.Serialization.Tests
{
public class JsonMediaTypeFormatterExtensionsTests
{
[Fact]
public void Formatter_JsonPreserveReferences_should_configure_JsonFormatter()
{
// Arrange
var formatter = new JsonMediaTypeFormatter();
// Act
formatter.JsonPreserveReferences();
// Assert
Assert.Equal(PreserveReferencesHandling.All, formatter.SerializerSettings.PreserveReferencesHandling);
}
}
}
<file_sep>using System;
namespace AspnetWebApi2Helpers.Sample.Client
{
public static class MediaTypes
{
public const string Json = "application/json";
public const string Xml = "application/xml";
public const string Protobuf = "application/x-protobuf";
}
}
<file_sep>using System;
namespace AspnetWebApi2Helpers.Serialization.Protobuf.Internal
{
/// <summary>
/// String constants representing media types.
/// </summary>
public static class MediaTypes
{
/// <summary>
/// Json media type formatter.
/// </summary>
public const string Json = "application/json";
/// <summary>
/// Xml media type formatter.
/// </summary>
public const string Xml = "application/xml";
/// <summary>
/// Protobuf media type formatter.
/// </summary>
public const string Protobuf = "application/x-protobuf";
}
}
<file_sep>using System.Net.Http.Formatting;
using JetBrains.Annotations;
using Newtonsoft.Json;
namespace AspnetWebApi2Helpers.Serialization
{
/// <summary>
/// Extension methods for configuring Json media type formatter to handle cyclical references.
/// </summary>
public static class JsonMediaTypeFormatterExtensions
{
/// <summary>
/// Configure serializer for JsonMediaTypeFormatter to handle cyclical references.
/// </summary>
/// <param name="jsonFormatter">Json media type formatter</param>
public static void JsonPreserveReferences([NotNull] this JsonMediaTypeFormatter jsonFormatter)
{
jsonFormatter.SerializerSettings.PreserveReferencesHandling =
PreserveReferencesHandling.All;
}
}
}<file_sep>using System.IO;
using ProtoBuf.Meta;
namespace AspnetWebApi2Helpers.Serialization.Protobuf.Tests
{
public static class TestHelper
{
public static T Clone<T>(this T obj, RuntimeTypeModel serializer)
{
T copy;
using (var stream = new MemoryStream())
{
serializer.Serialize(stream, obj);
stream.Position = 0;
copy = (T)serializer.Deserialize(stream, obj, typeof(T));
}
return copy;
}
}
}
<file_sep>using System.Collections.Generic;
using AspnetWebApi2Helpers.Sample.Entities;
namespace AspnetWebApi2Helpers.Sample.Data
{
public static class MockDatabase
{
static MockDatabase()
{
Categories = new List<Category>
{
new Category { CategoryId = 1, CategoryName = "Beverages" },
new Category { CategoryId = 2, CategoryName = "Condiments" },
new Category { CategoryId = 3, CategoryName = "Confections" },
new Category { CategoryId = 4, CategoryName = "Dairy Products" },
new Category { CategoryId = 5, CategoryName = "Grains/Cereals" },
new Category { CategoryId = 6, CategoryName = "Meat/Poultry" },
new Category { CategoryId = 7, CategoryName = "Produce" },
new Category { CategoryId = 8, CategoryName = "Seafood" },
};
Products = new List<Product>
{
new Product { ProductId = 1, ProductName = "Chai", CategoryId = 1, Category = Categories[0] },
new Product { ProductId = 2, ProductName = "Chang", CategoryId = 1, Category = Categories[0] },
new Product { ProductId = 3, ProductName = "Aniseed Syrup", CategoryId = 2, Category = Categories[1] },
new Product { ProductId = 4, ProductName = "Chef Anton's Cajun Seasoning", CategoryId = 2, Category = Categories[1] },
new Product { ProductId = 5, ProductName = "Chef Anton's Gumbo Mix", CategoryId = 2, Category = Categories[1] },
new Product { ProductId = 6, ProductName = "Grandma's Boysenberry Spread", CategoryId = 2, Category = Categories[1] },
new Product { ProductId = 7, ProductName = "Uncle Bob's Organic Dried Pears", CategoryId = 7, Category = Categories[6] },
new Product { ProductId = 8, ProductName = "Northwoods Cranberry Sauce", CategoryId = 2, Category = Categories[1] },
new Product { ProductId = 9, ProductName = "<NAME>", CategoryId = 6, Category = Categories[5] },
new Product { ProductId = 10, ProductName = "Ikura", CategoryId = 8, Category = Categories[7] },
};
Categories[0].Products.Add(Products[0]);
Categories[0].Products.Add(Products[1]);
Categories[1].Products.Add(Products[2]);
Categories[1].Products.Add(Products[3]);
Categories[1].Products.Add(Products[4]);
Categories[1].Products.Add(Products[5]);
Categories[6].Products.Add(Products[6]);
Categories[1].Products.Add(Products[7]);
Categories[5].Products.Add(Products[8]);
Categories[7].Products.Add(Products[9]);
}
public static List<Category> Categories { get; private set; }
public static List<Product> Products { get; private set; }
}
}<file_sep>using System.Net.Http.Formatting;
using Newtonsoft.Json;
using Xunit;
namespace AspnetWebApi2Helpers.Serialization.Tests
{
public class MediaTypeFormatterCollectionExtensionsTests
{
[Fact]
public void Formatters_JsonPreserveReferences_should_configure_JsonFormatter()
{
// Arrange
var formatters = new MediaTypeFormatterCollection
{ new JsonMediaTypeFormatter() };
// Act
formatters.JsonPreserveReferences();
// Assert
Assert.Equal(PreserveReferencesHandling.All, formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling);
}
[Fact]
public void Formatters_XmlPreserveReferences_should_configure_XmlFormatters()
{
// Arrange
var formatters = new MediaTypeFormatterCollection { new JsonMediaTypeFormatter() };
// Act
formatters.XmlPreserveReferences();
// Assert
Assert.IsAssignableFrom<XmlDataContractSerializerFormatter>(formatters.XmlFormatter);
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
using AspnetWebApi2Helpers.Sample.Data;
using AspnetWebApi2Helpers.Sample.Entities;
namespace AspnetWebApi2Helpers.Sample.Web.Controllers
{
public class ProductsController : ApiController
{
// GET api/products
[ResponseType(typeof(IEnumerable<Product>))]
public IHttpActionResult Get()
{
var products = MockDatabase.Products
.OrderBy(p => p.ProductName)
.ToList();
return Ok(products);
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
using AspnetWebApi2Helpers.Sample.Data;
using AspnetWebApi2Helpers.Sample.Entities;
namespace AspnetWebApi2Helpers.Sample.Web.Controllers
{
public class CategoriesController : ApiController
{
// GET api/categories
[ResponseType(typeof(IEnumerable<Category>))]
public IHttpActionResult Get()
{
var categories = MockDatabase.Categories
.OrderBy(e => e.CategoryName)
.ToList();
return Ok(categories);
}
}
}
| 320ab29879fb8e6a0dd57a4c17e41cc4c68cd569 | [
"Markdown",
"C#",
"Text"
] | 23 | C# | tonysneed/aspnet-webapi-2-contrib | 92ec030a69b0e628383087609e6550c9dc2598f0 | aae6383729e174348c3babb60e81711783714ac4 |
refs/heads/master | <repo_name>hamaguchi/PictureSelect<file_sep>/PictureSelect/Form1.cs
/***
* PictureSelect
* Copyright (C) 2011-2015 <NAME> All Rights Reserved.
***/
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using LevDan.Exif;
namespace PictureSelect
{
public partial class Form1 : Form
{
// C#で配列を宣言するには?
// http://www.atmarkit.co.jp/fdotnet/dotnettips/261arrayinit/arrayinit.html
// Coding4Fun: .NET で Flickr を使用する
// http://msdn.microsoft.com/ja-jp/library/bb932361.aspx
// ExifTagCollection - An EXIF metadata extraction library
// http://www.codeproject.com/KB/graphics/exiftagcol.aspx
//
// 全画像ファイルパス
string[] pictureFiles = null;
string[] deletePictureFiles = null;
bool[] deletePictureFlag = null;
string selectPath = null;
// string editProgram = null;
long pictureNowCount;
long deletePictoureCount;
public Form1()
{
InitializeComponent();
noSecondToolStripMenuItem.Checked = true;
disableEXIFToolStripMenuItem.Checked = true;
//アプリケーションの設定を読み込む
Properties.Settings.Default.Reload();
// 設定からバックグラウンド色を取得する
pictureBox1.BackColor = Properties.Settings.Default.BackColor;
//dataGridView1.BackgroundColor = Properties.Settings.Default.BackColor;
// 設定からExif表示ある/なしを取得する
if (Properties.Settings.Default.ExifFlag)
{
enableEXIFToolStripMenuItem.Checked = true;
disableEXIFToolStripMenuItem.Checked = false;
}
else
{
enableEXIFToolStripMenuItem.Checked = false;
disableEXIFToolStripMenuItem.Checked = true;
}
// 最後に読み込んだディレクトリを取得する
selectPath = Properties.Settings.Default.LastSelectPath;
if (selectPath != "" || selectPath == null)
{
// 指定されたディレクトリを取得する
folderOpen(selectPath);
}
// 最後のWindows状態を取得する
FormWindowState windowState = Properties.Settings.Default.WindowState;
this.WindowState = windowState;
// 編集プログラムを取得する
// editProgram = Properties.Settings.Default.EditProgram;
// ユーザーによる新しい行の追加禁止
dataGridView1.AllowUserToAddRows = false;
// ユーザーによる行の変更、削除の禁止
dataGridView1.ReadOnly = true;
//DataGridView1の列の幅をユーザーが変更できないようにする
dataGridView1.AllowUserToResizeColumns = false;
//DataGridView1の行の高さをユーザーが変更できないようにする
dataGridView1.AllowUserToResizeRows = false;
}
private void Form1_Load(object sender, EventArgs e)
{
// Form も、すべてのキーイベントを受け取るように設定する
this.KeyPreview = true;
// タイマーは無効にする
timer1.Enabled = false;
}
private void versionToolStripMenuItem_Click(object sender, EventArgs e)
{
{
VersionDialog VersionDialog = new VersionDialog();
VersionDialog.ShowDialog();
VersionDialog.Dispose();
}
}
private void selectDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
// 新規のフォルダを作るを禁止
folderBrowserDialog1.ShowNewFolderButton = false;
// もしもフォルダが開けたら
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
//// 選択したパスを保存する
selectPath = folderBrowserDialog1.SelectedPath;
// 指定されたディレクトリを取得する
folderOpen(selectPath);
folderBrowserDialog1.Dispose();
}
}
private void folderOpen(String selectPath)
{
try
{
// フォルダーオープン時点で、現在の画像番号を初期化する
pictureNowCount = 0;
// フォルダーオープン時点で、削除ファイル番号を初期化する。
deletePictoureCount = 0;
// 拡張子が .jpg を抽出する
string[] files_jpg = Directory.GetFiles(selectPath, "*.jpg");
// 拡張子が .jpeg を抽出する
string[] files_jpeg = Directory.GetFiles(selectPath, "*.jpeg");
// 拡張子が .png を抽出する
string[] files_png = Directory.GetFiles(selectPath, "*.png");
// 拡張子が .bmp を抽出する
string[] files_bmp = Directory.GetFiles(selectPath, "*.bmp");
// 拡張子が .gif を抽出する
string[] files_gif = Directory.GetFiles(selectPath, "*.gif");
pictureFiles = files_jpg;
pictureFiles = pictureFiles.Concat(files_jpeg).ToArray();
pictureFiles = pictureFiles.Concat(files_png).ToArray();
pictureFiles = pictureFiles.Concat(files_bmp).ToArray();
pictureFiles = pictureFiles.Concat(files_gif).ToArray();
if (pictureFiles.Length > 0)
{
this.pictureFilesLoad();
}
// ステータスバーのプログレッシブバーのMAX/MINをセット
toolStripProgressBar1.Minimum = 0;
toolStripProgressBar1.Maximum = pictureFiles.Length;
// 削除予約文字列を初期化
deletePictureFiles = new String[pictureFiles.Length];
// 削除予約フラグを初期化
deletePictureFlag = new bool[pictureFiles.Length];
for (int i = 0; i < pictureFiles.Length; i++)
{
deletePictureFlag[i] = false;
}
// 読み込んだディレクトリをセーブ
Properties.Settings.Default.LastSelectPath = selectPath;
}
catch
{
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
// プログラム終了
//this.pictureFiles.Initialize();
//this.deletePictureFiles.Initialize();
//this.deletePictureFlag.Initialize();
// Windows状態を保存します。
Properties.Settings.Default.WindowState = this.WindowState;
// 編集プログラムを保持します。
// Properties.Settings.Default.EditProgram = editProgram;
//アプリケーションの設定を保存する
Properties.Settings.Default.Save();
this.Close();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (pictureFiles == null)
{
return;
}
if (e.KeyCode == Keys.D)
{
// 画像カウントを+1する
pictureNowCount++;
// 次の画像を表示
this.pictureFilesLoad();
}
else if (e.KeyCode == Keys.A)
{
// 画像カウントを-1にする
pictureNowCount--;
// 次の画像を表示
this.pictureFilesLoad();
}
else if (e.KeyCode == Keys.E)
{
// 画像を回転させる(右90度回転)
pictureBox1.Load(pictureFiles[pictureNowCount]);
pictureBox1.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox1.Refresh();
}
else if (e.KeyCode == Keys.Q)
{
// 画像を回転させる(左90度回転)
pictureBox1.Load(pictureFiles[pictureNowCount]);
pictureBox1.Image.RotateFlip(RotateFlipType.Rotate270FlipNone);
pictureBox1.Refresh();
}
else if (e.KeyCode == Keys.W)
{
// 削除する変数にファイルを追加
deletePictureFiles[deletePictoureCount] = pictureFiles[pictureNowCount];
// 削除フラグをtrueにする
deletePictureFlag[pictureNowCount] = true;
// 削除ファイル番号を+1する
deletePictoureCount++;
// 画像カウントを+1する
pictureNowCount++;
// 次の画像を表示
this.pictureFilesLoad();
}
else if (e.KeyCode == Keys.S)
{
this.deleteToolStripMenuItem_Click(null, null);
}
else if (e.KeyCode == Keys.X)
{
editPictureStart();
}
}
private void pictureFilesLoad()
{
try
{
// 画像を表示させる
pictureBox1.Load(pictureFiles[pictureNowCount]);
}
catch
{
// MessageBox.Show("画像が最後まで読み込まれました。最初から読み出します。", "インフォメーション", MessageBoxButtons.OK, MessageBoxIcon.Information );
// 画像カウントを0にする
pictureNowCount = 0;
try
{
// 画像を表示させる
pictureBox1.Load(pictureFiles[pictureNowCount]);
}
catch (Exception e)
{
MessageBox.Show("読み込みエラーが発生しました。\r\n違うディレクトリを指定して下さい。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
try
{
// 削除予約の場合、ステータスバーに「削除予定」と表示
if (deletePictureFlag[pictureNowCount] == true)
{
deleteStatusLabel.Text = "削除予定";
deleteStatusLabel.Visible = true;
}
else
{
//deleteStatusLabel.Text = "";
deleteStatusLabel.Visible = false;
}
}
catch
{
}
// ステータスバーにファイルパスを表示する
pictureFilePath.Text = pictureFiles[pictureNowCount];
// 画像サイズは、Zoom
// PictureBox.SizeMode
// http://msdn.microsoft.com/ja-jp/library/system.windows.forms.picturebox.sizemode.aspx
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
toolStripProgressBar1.Value = (int)pictureNowCount;
ExifTagCollection exif = new ExifTagCollection(pictureFiles[pictureNowCount]);
// 画像の回転
pictureOrientation(pictureFiles[pictureNowCount], exif);
// Exif情報表示
if (enableEXIFToolStripMenuItem.Checked == true)
{
dataGridView1.Rows.Clear();
foreach (ExifTag tag in exif)
{
dataGridView1.Rows.Add(tag.FieldName, tag.Value);
}
dataGridView1.Visible = true;
}
else
{
dataGridView1.Visible = false;
}
}
/**
* 画像の回転
*/
private void pictureOrientation(String filename, ExifTagCollection exif)
{
foreach (ExifTag tag in exif)
{
if (tag.FieldName == "Orientation")
{
// case 1: value = "The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side."; break;
if (tag.Value == "1")
{
// 正常
}
// case 2: value = "The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side."; break;
else if (tag.Value == "2")
{
MessageBox.Show("Orientation:2 No,Support");
}
// case 3: value = "The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side."; break;
else if (tag.Value == "3")
{
// 右180度回転
pictureBox1.Image.RotateFlip(RotateFlipType.Rotate180FlipNone);
pictureBox1.Refresh();
}
// case 4: value = "The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side."; break;
else if (tag.Value == "4")
{
MessageBox.Show("Orientation:4 No,Support");
}
// case 5: value = "The 0th row is the visual left-hand side of the image, and the 0th column is the visual top."; break;
else if (tag.Value == "5")
{
MessageBox.Show("Orientation:5 No,Support");
}
// case 6: value = "The 0th row is the visual right-hand side of the image, and the 0th column is the visual top."; break;
else if (tag.Value == "6")
{
// 右90度回転
pictureBox1.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox1.Refresh();
}
// case 7: value = "The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom."; break;
else if (tag.Value == "7")
{
// 右90度回転
pictureBox1.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox1.Refresh();
}
// case 8: value = "The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom."; break;
else if (tag.Value == "8")
{
// 左90度回転
pictureBox1.Image.RotateFlip(RotateFlipType.Rotate270FlipNone);
pictureBox1.Refresh();
}
}
}
}
private void deleteFiles(String filename)
{
try
{
// ファイル削除
System.IO.File.Delete(filename);
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (deletePictureFiles == null)
{
return;
}
String xMessage = "画像ファイル: ";
xMessage = xMessage + deletePictoureCount + "枚を削除します。";
DialogResult result = MessageBox.Show(xMessage, "インフォメーション", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
for (int i = 0; i < deletePictoureCount; i++)
{
this.deleteFiles(deletePictureFiles[i]);
}
deletePictureFiles = null;
deletePictoureCount = 0;
// フォルダーを開き直す
pictureFiles = null;
folderOpen(selectPath);
MessageBox.Show("ファイルを削除しました。", "インフォメーション", MessageBoxButtons.OK, MessageBoxIcon.Information);
deleteStatusLabel.Visible = false;
}
else if (result == DialogResult.No)
{
// 「いいえ」が選択された時
}
else if (result == DialogResult.Cancel)
{
//「キャンセル」が選択された時
}
}
private void backToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.BackColor = colorDialog1.Color;
dataGridView1.BackgroundColor = colorDialog1.Color;
Properties.Settings.Default.BackColor = colorDialog1.Color;
}
}
private void helpToolStripMenuItem1_Click(object sender, EventArgs e)
{
HelpForm HelpForm = new HelpForm();
HelpForm.StartPosition = FormStartPosition.CenterParent;
HelpForm.ShowDialog();
HelpForm.Dispose();
}
private void noSecondToolStripMenuItem_Click(object sender, EventArgs e)
{
second3ToolStripMenuItem.Checked = false;
second8ToolStripMenuItem.Checked = false;
second5ToolStripMenuItem.Checked = false;
// タイマーを止めます。
timer1.Enabled = false;
}
private void second3ToolStripMenuItem_Click(object sender, EventArgs e)
{
noSecondToolStripMenuItem.Checked = false;
second5ToolStripMenuItem.Checked = false;
second8ToolStripMenuItem.Checked = false;
// タイマーを3秒にする
timer1.Interval = 3000;
timer1.Enabled = true;
}
private void second5ToolStripMenuItem_Click(object sender, EventArgs e)
{
noSecondToolStripMenuItem.Checked = false;
second3ToolStripMenuItem.Checked = false;
second8ToolStripMenuItem.Checked = false;
// タイマーを5秒にする
timer1.Interval = 5000;
timer1.Enabled = true;
}
private void second8ToolStripMenuItem_Click(object sender, EventArgs e)
{
noSecondToolStripMenuItem.Checked = false;
second3ToolStripMenuItem.Checked = false;
second5ToolStripMenuItem.Checked = false;
// タイマーを3秒にする
timer1.Interval = 8000;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (pictureFiles != null)
{
// 画像カウントを+1する
pictureNowCount++;
// 次の画像を表示
this.pictureFilesLoad();
}
}
private void disableEXIFToolStripMenuItem_Click(object sender, EventArgs e)
{
enableEXIFToolStripMenuItem.Checked = false;
Properties.Settings.Default.ExifFlag = false;
}
private void enableEXIFToolStripMenuItem_Click(object sender, EventArgs e)
{
disableEXIFToolStripMenuItem.Checked = false;
Properties.Settings.Default.ExifFlag = true;
}
//private void editProgramToolStripMenuItem_Click(object sender, EventArgs e)
//{
// openFileDialog2.Filter = "exe files (*.exe)|*.exe";
// openFileDialog2.FilterIndex = 1;
// openFileDialog2.RestoreDirectory = true;
// openFileDialog2.Title = "画像編集ソフト選択";
// DialogResult result = openFileDialog2.ShowDialog();
// if (result == DialogResult.OK)
// {
// editProgram = openFileDialog2.FileName;
// }
//}
private void editPictureToolStripMenuItem_Click(object sender, EventArgs e)
{
editPictureStart();
}
private void editPictureStart()
{
try
{
// 関連プログラムの起動
Process.Start(@pictureFiles[pictureNowCount]);
}
catch (Exception e)
{
MessageBox.Show("はじめに、画像を表示して下さい。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
}
}
<file_sep>/PictureSelect/Properties/AssemblyInfo.cs
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("PictureSelect")]
[assembly: AssemblyDescription("PictureSelectは、画像を気軽に選別できるプログラムです。\r\n快適な操作性を確保するために基本的にキーボードで行い「WSAD」スタイルを採用しています。\r\n\r\nバグ報告/新規機能の提案等は、<EMAIL> にメールして下さい。\r\nEXIFライブラリは、ExifTagCollection - An EXIF metadata extraction libraryを利用しています。")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("<NAME>")]
[assembly: AssemblyProduct("PictureSelect")]
[assembly: AssemblyCopyright("Copyright © <NAME> 2011-2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("f59bef1f-5ff7-4b2b-bdf6-712b9915573b")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.1")]
[assembly: AssemblyFileVersion("0.9.0.1")]
<file_sep>/PictureSelect/Program.cs
/***
* PictureSelect
* Copyright (C) 2011-2015 <NAME> All Rights Reserved.
***/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace PictureSelect
{
static class Program
{
/// <summary>
/// アプリケーションのメイン エントリ ポイントです。
/// </summary>
///
// Ver 0.0.0.12
// ショートカットキーの設定
// 前回表示していたディレクトリの再表示
// 重複起動の禁止
[STAThread]
static void Main()
{
// アプリケーションの二重起動を抑止する
// http://www.ipentec.com/document/document.aspx?page=csharp-singleexec
//ミューテックス作成
System.Threading.Mutex _mutex = new System.Threading.Mutex(false, "PictureSelect");
//ミューテックスの所有権を要求する
if (_mutex.WaitOne(0, false) == false) {
MessageBox.Show("本ソフトウェアは複数起動できません。");
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
<file_sep>/PictureSelect/Form2.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PictureSelect
{
public partial class HelpForm : Form
{
public HelpForm()
{
InitializeComponent();
String richText = "PictureSelectは、画像を気軽に選別できるプログラムです。\r\n";
richText = richText + "快適な操作性を確保するために、キーボードによるインターフェイスを提供しています。\r\n";
richText = richText + "FPSで使われる「WSAD」スタイルを採用しています。(変更不可)\r\n";
richText = richText + "・Dキー: 次の画像を表示します。\r\n";
richText = richText + "・Aキー: 前の画像を表示します。\r\n";
richText = richText + "・Wキー: 画像に削除予約をします。次の画像を読み出します。\r\n";
richText = richText + "・Qキー: 画像を左90度回転させます。\r\n";
richText = richText + "・Eキー: 画像を右90度回転させます。\r\n";
richText = richText + "・Sキー: 削除予約されているファイルを削除します。\r\n";
richText = richText + "・Xキー: 関連プログラムを起動します。\r\n";
richText = richText + "この画面で動作確認ができます。キーボードを押すと、\r\n";
richText = richText + "ステータスバーに指示された動作が表示されます。\r\n";
richTextBox1.Text = richText;
toolStripStatusLabel1.Text = "説明";
}
private void HelpForm_Load(object sender, EventArgs e)
{
// Form も、すべてのキーイベントを受け取るように設定する
this.KeyPreview = true;
}
private void HelpForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D)
{
toolStripStatusLabel1.Text = "Dキー: 次の画像を表示";
}
else if (e.KeyCode == Keys.A)
{
toolStripStatusLabel1.Text = "Aキー: 前の画像を表示";
}
else if (e.KeyCode == Keys.E)
{
toolStripStatusLabel1.Text = "Eキー: 画像を右90度回転";
}
else if (e.KeyCode == Keys.Q)
{
toolStripStatusLabel1.Text = "Qキー: 画像を左90度回転";
}
else if (e.KeyCode == Keys.W)
{
toolStripStatusLabel1.Text = "Wキー: 画像に削除予約";
}
else if (e.KeyCode == Keys.S)
{
toolStripStatusLabel1.Text = "Sキー: 削除";
}
else if (e.KeyCode == Keys.X)
{
toolStripStatusLabel1.Text = "Xキー: 関連プログラムを起動";
}
}
private void button1_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "Qキー: 画像を左90度回転";
}
private void button2_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "Wキー: 画像に削除予約";
}
private void button3_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "Qキー: 画像を左90度回転";
}
private void button4_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "Aキー: 前の画像を表示";
}
private void button5_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "Sキー: 削除";
}
private void button6_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "Dキー: 次の画像を表示";
}
private void button7_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "Xキー: 関連プログラムを起動";
}
private void okbutton_Click(object sender, EventArgs e)
{
this.Close();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>/README.md
# PictureSelect
##### Ver.0.9.0.1 Copyright (C) 2011-2015 by <NAME>
### 動作環境、および必要なフレームワーク
* PictureSelect は32bitアプリです。Windows 7(64bit)/8.1(64bit)で、動作確認を行なっています。
* PictureSelect は、Microsoft Visual C# 2013 を使って記述しています。実行には、Microsoft .NET Framework 4.5以降が必要です。
### インストール
解凍したファイルの「setup.exe」を起動して下さい。
### アンインストール
OS標準の「プログラムのアンインストール」から「PictureSelect」を選択するとアンインストールが可能です。
### 主な機能(Ver.0.9.0.1)
* PictureSelectは、画像を気軽に選別できるプログラムです。
* 快適な操作性を確保するために、FPSで使われる「WSAD」スタイルのキーボードインターフェイスを提供しています。
#### キー 解説
1. Dキー: 次の画像を表示します。
2. Aキー: 前の画像を表示します。
3. Wキー: 画像に削除予約をします。次の画像を読み出します。
4. Qキー: 画像を左90度回転させます。
5. Eキー: 画像を右90度回転させます。
6. Sキー: 削除予約されているファイルを削除します。
7. Xキー: 関連プログラムを起動します。
### 著作権その他
* PictureSelectはフリーソフトウェアです。転載および再頒布は自由です。
* ソースコード一式は、Github にあります。
[https://github.com/hamaguchi/PictureSelect
](https://github.com/hamaguchi/PictureSelect)
* 不具合、ご要望、不明な点、まちがった英語等がございましたら、次のmailアドレスへご一報頂ければ幸いです。E-mail: [<EMAIL>](mailto:<EMAIL>)
* 最新版、およびバージョンアップ情報は、次のホームページに掲載します。
[http://h7i.jp/](http://h7i.jp/)
* 本プログラムを使用した上で生じたいかなる損害についても、作者は責任を負いません。
* EXIFライブラリは、ExifTagCollection - An EXIF metadata extraction libraryを利用しています。素晴らしいコードを配布していただき感謝しています。
* EMIとNANAに、永遠の愛を捧げます。
| fc6bf5bda12c0a90f9a6ff6743b03ef2f0ff1b91 | [
"Markdown",
"C#"
] | 5 | C# | hamaguchi/PictureSelect | 9e79c8a1f0bc5eb578a039d83b3b38a0a280651b | 3680a5c8d79cbbd8c952f66c6b7a32b23da20868 |
refs/heads/master | <repo_name>bossjones/container-diff<file_sep>/utils/fs_utils.go
/*
Copyright 2017 Google, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"github.com/golang/glog"
)
// Directory stores a representaiton of a file directory.
type Directory struct {
Root string
Content []string
}
type DirectoryEntry struct {
Name string
Size int64
}
type EntryDiff struct {
Name string
Size1 int64
Size2 int64
}
func GetSize(path string) int64 {
stat, err := os.Stat(path)
if err != nil {
glog.Errorf("Could not obtain size for %s: %s", path, err)
return -1
}
if stat.IsDir() {
size, err := getDirectorySize(path)
if err != nil {
glog.Errorf("Could not obtain directory size for %s: %s", path, err)
}
return size
}
return stat.Size()
}
func getDirectorySize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
// GetDirectoryContents converts the directory starting at the provided path into a Directory struct.
func GetDirectory(path string, deep bool) (Directory, error) {
var directory Directory
directory.Root = path
var err error
if deep {
walkFn := func(currPath string, info os.FileInfo, err error) error {
newContent := strings.TrimPrefix(currPath, directory.Root)
if newContent != "" {
directory.Content = append(directory.Content, newContent)
}
return nil
}
err = filepath.Walk(path, walkFn)
} else {
contents, err := ioutil.ReadDir(path)
if err != nil {
return directory, err
}
for _, file := range contents {
fileName := "/" + file.Name()
directory.Content = append(directory.Content, fileName)
}
}
return directory, err
}
// Checks for content differences between files of the same name from different directories
func GetModifiedEntries(d1, d2 Directory) []string {
d1files := d1.Content
d2files := d2.Content
filematches := GetMatches(d1files, d2files)
modified := []string{}
for _, f := range filematches {
f1path := fmt.Sprintf("%s%s", d1.Root, f)
f2path := fmt.Sprintf("%s%s", d2.Root, f)
f1stat, err := os.Stat(f1path)
if err != nil {
glog.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
f2stat, err := os.Stat(f2path)
if err != nil {
glog.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
// If the directory entry in question is a tar, verify that the two have the same size
if isTar(f1path) {
if f1stat.Size() != f2stat.Size() {
modified = append(modified, f)
}
continue
}
// If the directory entry is not a tar and not a directory, then it's a file so make sure the file contents are the same
// Note: We skip over directory entries because to compare directories, we compare their contents
if !f1stat.IsDir() {
same, err := checkSameFile(f1path, f2path)
if err != nil {
glog.Errorf("Error diffing contents of %s and %s: %s\n", f1path, f2path, err)
continue
}
if !same {
modified = append(modified, f)
}
}
}
return modified
}
func GetAddedEntries(d1, d2 Directory) []string {
return GetAdditions(d1.Content, d2.Content)
}
func GetDeletedEntries(d1, d2 Directory) []string {
return GetDeletions(d1.Content, d2.Content)
}
type DirDiff struct {
Adds []DirectoryEntry
Dels []DirectoryEntry
Mods []EntryDiff
}
func GetDirectoryEntries(d Directory) []DirectoryEntry {
return createDirectoryEntries(d.Root, d.Content)
}
func createDirectoryEntries(root string, entryNames []string) (entries []DirectoryEntry) {
for _, name := range entryNames {
entryPath := filepath.Join(root, name)
size := GetSize(entryPath)
entry := DirectoryEntry{
Name: name,
Size: size,
}
entries = append(entries, entry)
}
return entries
}
func createEntryDiffs(root1, root2 string, entryNames []string) (entries []EntryDiff) {
for _, name := range entryNames {
entryPath1 := filepath.Join(root1, name)
size1 := GetSize(entryPath1)
entryPath2 := filepath.Join(root2, name)
size2 := GetSize(entryPath2)
entry := EntryDiff{
Name: name,
Size1: size1,
Size2: size2,
}
entries = append(entries, entry)
}
return entries
}
// DiffDirectory takes the diff of two directories, assuming both are completely unpacked
func DiffDirectory(d1, d2 Directory) (DirDiff, bool) {
adds := GetAddedEntries(d1, d2)
sort.Strings(adds)
addedEntries := createDirectoryEntries(d2.Root, adds)
dels := GetDeletedEntries(d1, d2)
sort.Strings(dels)
deletedEntries := createDirectoryEntries(d1.Root, dels)
mods := GetModifiedEntries(d1, d2)
sort.Strings(mods)
modifiedEntries := createEntryDiffs(d1.Root, d2.Root, mods)
var same bool
if len(adds) == 0 && len(dels) == 0 && len(mods) == 0 {
same = true
} else {
same = false
}
return DirDiff{addedEntries, deletedEntries, modifiedEntries}, same
}
func checkSameFile(f1name, f2name string) (bool, error) {
// Check first if files differ in size and immediately return
f1stat, err := os.Stat(f1name)
if err != nil {
return false, err
}
f2stat, err := os.Stat(f2name)
if err != nil {
return false, err
}
if f1stat.Size() != f2stat.Size() {
return false, nil
}
// Next, check file contents
f1, err := ioutil.ReadFile(f1name)
if err != nil {
return false, err
}
f2, err := ioutil.ReadFile(f2name)
if err != nil {
return false, err
}
if !bytes.Equal(f1, f2) {
return false, nil
}
return true, nil
}
<file_sep>/utils/image_prep_utils.go
/*
Copyright 2017 Google, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"archive/tar"
"compress/gzip"
"context"
"encoding/json"
"errors"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/containers/image/docker"
"github.com/containers/image/docker/tarfile"
"github.com/docker/docker/client"
"github.com/golang/glog"
)
var sourceToPrepMap = map[string]func(ip ImagePrepper) Prepper{
"ID": func(ip ImagePrepper) Prepper { return IDPrepper{ImagePrepper: ip} },
"URL": func(ip ImagePrepper) Prepper { return CloudPrepper{ImagePrepper: ip} },
"tar": func(ip ImagePrepper) Prepper { return TarPrepper{ImagePrepper: ip} },
}
var sourceCheckMap = map[string]func(string) bool{
"ID": CheckImageID,
"URL": CheckImageURL,
"tar": CheckTar,
}
type Image struct {
Source string
FSPath string
Config ConfigSchema
}
type ImageHistoryItem struct {
CreatedBy string `json:"created_by"`
}
type ConfigObject struct {
Env []string `json:"Env"`
}
type ConfigSchema struct {
Config ConfigObject `json:"config"`
History []ImageHistoryItem `json:"history"`
}
type ImagePrepper struct {
Source string
Client *client.Client
}
type Prepper interface {
getFileSystem() (string, error)
getConfig() (ConfigSchema, error)
}
func (p ImagePrepper) GetImage() (Image, error) {
glog.Infof("Starting prep for image %s", p.Source)
img := p.Source
var prepper Prepper
for source, check := range sourceCheckMap {
if check(img) {
prepper = sourceToPrepMap[source](p)
break
}
}
if prepper == nil {
return Image{}, errors.New("Could not retrieve image from source")
}
imgPath, err := prepper.getFileSystem()
if err != nil {
return Image{}, err
}
config, err := prepper.getConfig()
if err != nil {
glog.Error("Error retrieving History: ", err)
}
glog.Infof("Finished prepping image %s", p.Source)
return Image{
Source: img,
FSPath: imgPath,
Config: config,
}, nil
}
func getImageFromTar(tarPath string) (string, error) {
glog.Info("Extracting image tar to obtain image file system")
path := strings.TrimSuffix(tarPath, filepath.Ext(tarPath))
err := unpackDockerSave(tarPath, path)
return path, err
}
// CloudPrepper prepares images sourced from a Cloud registry
type CloudPrepper struct {
ImagePrepper
}
func (p CloudPrepper) getFileSystem() (string, error) {
// The regexp when passed a string creates a list of the form
// [repourl/image:tag, image:tag, tag] (the tag may or may not be present)
URLPattern := regexp.MustCompile("^.+/(.+(:.+){0,1})$")
URLMatch := URLPattern.FindStringSubmatch(p.Source)
// Removing the ":" so that the image path name can be <image><tag>
sanitizedName := strings.Replace(URLMatch[1], ":", "", -1)
path, err := ioutil.TempDir("", sanitizedName)
if err != nil {
return "", err
}
ref, err := docker.ParseReference("//" + p.Source)
if err != nil {
return "", err
}
img, err := ref.NewImage(nil)
if err != nil {
glog.Error(err)
return "", err
}
defer img.Close()
imgSrc, err := ref.NewImageSource(nil, nil)
if err != nil {
glog.Error(err)
return "", err
}
for _, b := range img.LayerInfos() {
bi, _, err := imgSrc.GetBlob(b)
if err != nil {
glog.Errorf("Diff may be inaccurate, failed to pull image layer with error: %s", err)
}
gzf, err := gzip.NewReader(bi)
if err != nil {
glog.Errorf("Diff may be inaccurate, failed to read layers with error: %s", err)
}
tr := tar.NewReader(gzf)
err = unpackTar(tr, path)
if err != nil {
glog.Errorf("Diff may be inaccurate, failed to untar layer with error: %s", err)
}
}
return path, nil
}
func (p CloudPrepper) getConfig() (ConfigSchema, error) {
ref, err := docker.ParseReference("//" + p.Source)
if err != nil {
return ConfigSchema{}, err
}
img, err := ref.NewImage(nil)
if err != nil {
glog.Errorf("Error referencing image %s from registry: %s", p.Source, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
defer img.Close()
configBlob, err := img.ConfigBlob()
if err != nil {
glog.Errorf("Error obtaining config blob for image %s from registry: %s", p.Source, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
var config ConfigSchema
err = json.Unmarshal(configBlob, &config)
if err != nil {
glog.Errorf("Error with config file struct for image %s: %s", p.Source, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
return config, nil
}
type IDPrepper struct {
ImagePrepper
}
func (p IDPrepper) getFileSystem() (string, error) {
tarPath, err := saveImageToTar(p.Client, p.Source, p.Source)
if err != nil {
return "", err
}
defer os.Remove(tarPath)
return getImageFromTar(tarPath)
}
func (p IDPrepper) getConfig() (ConfigSchema, error) {
inspect, _, err := p.Client.ImageInspectWithRaw(context.Background(), p.Source)
if err != nil {
return ConfigSchema{}, err
}
config := ConfigObject{
Env: inspect.Config.Env,
}
history := p.getHistory()
return ConfigSchema{
Config: config,
History: history,
}, nil
}
func (p IDPrepper) getHistory() []ImageHistoryItem {
history, err := p.Client.ImageHistory(context.Background(), p.Source)
if err != nil {
glog.Error("Could not obtain image history for %s: %s", p.Source, err)
}
historyItems := []ImageHistoryItem{}
for _, item := range history {
historyItems = append(historyItems, ImageHistoryItem{CreatedBy: item.CreatedBy})
}
return historyItems
}
type TarPrepper struct {
ImagePrepper
}
func (p TarPrepper) getFileSystem() (string, error) {
return getImageFromTar(p.Source)
}
func (p TarPrepper) getConfig() (ConfigSchema, error) {
tempDir := strings.TrimSuffix(p.Source, filepath.Ext(p.Source)) + "-config"
defer os.RemoveAll(tempDir)
err := UnTar(p.Source, tempDir)
if err != nil {
return ConfigSchema{}, err
}
var config ConfigSchema
// First open the manifest, then find the referenced config.
manifestPath := filepath.Join(tempDir, "manifest.json")
contents, err := ioutil.ReadFile(manifestPath)
if err != nil {
return ConfigSchema{}, err
}
manifests := []tarfile.ManifestItem{}
if err := json.Unmarshal(contents, &manifests); err != nil {
return ConfigSchema{}, err
}
if len(manifests) != 1 {
return ConfigSchema{}, errors.New("specified tar file contains multiple images")
}
cfgFilename := filepath.Join(tempDir, manifests[0].Config)
file, err := ioutil.ReadFile(cfgFilename)
if err != nil {
glog.Errorf("Could not read config file %s: %s", cfgFilename, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
err = json.Unmarshal(file, &config)
if err != nil {
glog.Errorf("Could not marshal config file %s: %s", cfgFilename, err)
return ConfigSchema{}, errors.New("Could not obtain image config")
}
return config, nil
}
<file_sep>/cmd/diff.go
/*
Copyright 2017 Google, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"errors"
"fmt"
"os"
"strings"
"sync"
"github.com/GoogleCloudPlatform/container-diff/differs"
"github.com/GoogleCloudPlatform/container-diff/utils"
"github.com/golang/glog"
"github.com/spf13/cobra"
)
var diffCmd = &cobra.Command{
Use: "diff",
Short: "Compare two images: [image1] [image2]",
Long: `Compares two images using the specifed analyzers as indicated via flags (see documentation for available ones).`,
Args: func(cmd *cobra.Command, args []string) error {
if err := validateArgs(args, checkDiffArgNum, checkArgType); err != nil {
return errors.New(err.Error())
}
if err := checkIfValidAnalyzer(types); err != nil {
return errors.New(err.Error())
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
if err := diffImages(args[0], args[1], strings.Split(types, ",")); err != nil {
glog.Error(err)
os.Exit(1)
}
},
}
func checkDiffArgNum(args []string) error {
if len(args) != 2 {
return errors.New("'diff' requires two images as arguments: container diff [image1] [image2]")
}
return nil
}
func diffImages(image1Arg, image2Arg string, diffArgs []string) error {
cli, err := NewClient()
if err != nil {
return fmt.Errorf("Error getting docker client for differ: %s", err)
}
defer cli.Close()
var wg sync.WaitGroup
wg.Add(2)
glog.Infof("Starting diff on images %s and %s, using differs: %s", image1Arg, image2Arg, diffArgs)
imageMap := map[string]*utils.Image{
image1Arg: {},
image2Arg: {},
}
for imageArg := range imageMap {
go func(imageName string, imageMap map[string]*utils.Image) {
defer wg.Done()
ip := utils.ImagePrepper{
Source: imageName,
Client: cli,
}
image, err := ip.GetImage()
imageMap[imageName] = &image
if err != nil {
glog.Error(err.Error())
}
}(imageArg, imageMap)
}
wg.Wait()
if !save {
defer cleanupImage(*imageMap[image1Arg])
defer cleanupImage(*imageMap[image2Arg])
}
diffTypes, err := differs.GetAnalyzers(diffArgs)
if err != nil {
glog.Error(err.Error())
return errors.New("Could not perform image diff")
}
req := differs.DiffRequest{*imageMap[image1Arg], *imageMap[image2Arg], diffTypes}
diffs, err := req.GetDiff()
if err != nil {
glog.Error(err.Error())
return errors.New("Could not perform image diff")
}
glog.Info("Retrieving diffs")
outputResults(diffs)
if save {
glog.Infof("Images were saved at %s and %s", imageMap[image1Arg].FSPath,
imageMap[image2Arg].FSPath)
}
return nil
}
func init() {
RootCmd.AddCommand(diffCmd)
addSharedFlags(diffCmd)
}
<file_sep>/cmd/root.go
/*
Copyright 2017 Google, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"context"
goflag "flag"
"fmt"
"os"
"sort"
"strings"
"github.com/GoogleCloudPlatform/container-diff/differs"
"github.com/GoogleCloudPlatform/container-diff/utils"
"github.com/docker/docker/client"
"github.com/golang/glog"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
var json bool
var save bool
var types string
type validatefxn func(args []string) error
var RootCmd = &cobra.Command{
Use: "container-diff",
Short: "container-diff is a tool for analyzing and comparing container images",
Long: `container-diff is a CLI tool for analyzing and comparing container images.`,
}
func NewClient() (*client.Client, error) {
cli, err := client.NewEnvClient()
if err != nil {
return nil, fmt.Errorf("Error getting docker client: %s", err)
}
cli.NegotiateAPIVersion(context.Background())
return cli, nil
}
func outputResults(resultMap map[string]utils.Result) {
// Outputs diff/analysis results in alphabetical order by analyzer name
sortedTypes := []string{}
for analyzerType := range resultMap {
sortedTypes = append(sortedTypes, analyzerType)
}
sort.Strings(sortedTypes)
results := make([]interface{}, len(resultMap))
for i, analyzerType := range sortedTypes {
result := resultMap[analyzerType]
if json {
results[i] = result.OutputStruct()
} else {
err := result.OutputText(analyzerType)
if err != nil {
glog.Error(err)
}
}
}
if json {
err := utils.JSONify(results)
if err != nil {
glog.Error(err)
}
}
}
func cleanupImage(image utils.Image) {
if image.FSPath != "" {
glog.Infof("Removing image filesystem directory %s from system", image.FSPath)
errMsg := remove(image.FSPath, true)
if errMsg != "" {
glog.Error(errMsg)
}
}
}
func validateArgs(args []string, validatefxns ...validatefxn) error {
for _, validatefxn := range validatefxns {
if err := validatefxn(args); err != nil {
return err
}
}
return nil
}
func checkImage(arg string) bool {
if !utils.CheckImageID(arg) && !utils.CheckImageURL(arg) && !utils.CheckTar(arg) {
return false
}
return true
}
func checkArgType(args []string) error {
for _, arg := range args {
if !checkImage(arg) {
errMessage := fmt.Sprintf("Argument %s is not an image ID, URL, or tar\n", args[0])
glog.Errorf(errMessage)
return errors.New(errMessage)
}
}
return nil
}
func checkIfValidAnalyzer(flagtypes string) error {
if flagtypes == "" {
return nil
}
analyzers := strings.Split(flagtypes, ",")
for _, name := range analyzers {
if _, exists := differs.Analyzers[name]; !exists {
errMessage := fmt.Sprintf("Argument %s is not a valid analyzer\n", name)
glog.Errorf(errMessage)
return errors.New(errMessage)
}
}
return nil
}
func remove(path string, dir bool) string {
var errStr string
if path == "" {
return ""
}
var err error
if dir {
err = os.RemoveAll(path)
} else {
err = os.Remove(path)
}
if err != nil {
errStr = "\nUnable to remove " + path
}
return errStr
}
func init() {
pflag.CommandLine.AddGoFlagSet(goflag.CommandLine)
}
func addSharedFlags(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&json, "json", "j", false, "JSON Output defines if the diff should be returned in a human readable format (false) or a JSON (true).")
cmd.Flags().StringVarP(&types, "types", "t", "", "This flag sets the list of analyzer types to use. It expects a comma separated list of supported analyzers.")
cmd.Flags().BoolVarP(&save, "save", "s", false, "Set this flag to save rather than remove the final image filesystems on exit.")
cmd.Flags().BoolVarP(&utils.SortSize, "order", "o", false, "Set this flag to sort any file/package results by descending size. Otherwise, they will be sorted by name.")
}
<file_sep>/utils/tar_utils.go
/*
Copyright 2017 Google, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"archive/tar"
"io"
"os"
"path/filepath"
"strings"
"github.com/golang/glog"
)
func unpackTar(tr *tar.Reader, path string) error {
for {
header, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
glog.Error("Error getting next tar header")
return err
}
if strings.Contains(header.Name, ".wh.") {
rmPath := filepath.Join(path, header.Name)
newName := strings.Replace(rmPath, ".wh.", "", 1)
err := os.Remove(rmPath)
if err != nil {
glog.Info(err)
}
err = os.RemoveAll(newName)
if err != nil {
glog.Info(err)
}
continue
}
target := filepath.Join(path, header.Name)
mode := header.FileInfo().Mode()
switch header.Typeflag {
// if its a dir and it doesn't exist create it
case tar.TypeDir:
if _, err := os.Stat(target); err != nil {
if err := os.MkdirAll(target, mode); err != nil {
glog.Errorf("Error creating directory %s while untarring", target)
return err
}
continue
}
// if it's a file create it
case tar.TypeReg:
currFile, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
if err != nil {
glog.Errorf("Error opening file %s", target)
return err
}
_, err = io.Copy(currFile, tr)
if err != nil {
return err
}
currFile.Close()
}
}
return nil
}
// UnTar takes in a path to a tar file and writes the untarred version to the provided target.
// Only untars one level, does not untar nested tars.
func UnTar(filename string, target string) error {
if _, ok := os.Stat(target); ok != nil {
os.MkdirAll(target, 0777)
}
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
tr := tar.NewReader(file)
err = unpackTar(tr, target)
if err != nil {
glog.Error(err)
return err
}
return nil
}
func isTar(path string) bool {
return filepath.Ext(path) == ".tar"
}
func CheckTar(image string) bool {
if strings.TrimSuffix(image, ".tar") == image {
return false
}
if _, err := os.Stat(image); err != nil {
glog.Errorf("%s does not exist", image)
return false
}
return true
}
<file_sep>/utils/docker_utils.go
/*
Copyright 2017 Google, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/docker/docker/client"
"github.com/golang/glog"
)
type Event struct {
Status string `json:"status"`
Error string `json:"error"`
Progress string `json:"progress"`
ProgressDetail struct {
Current int `json:"current"`
Total int `json:"total"`
} `json:"progressDetail"`
}
func getLayersFromManifest(manifestPath string) ([]string, error) {
type Manifest struct {
Layers []string
}
manifestJSON, err := ioutil.ReadFile(manifestPath)
if err != nil {
errMsg := fmt.Sprintf("Could not open manifest to get layer order: %s", err)
return []string{}, errors.New(errMsg)
}
var imageManifest []Manifest
err = json.Unmarshal(manifestJSON, &imageManifest)
if err != nil {
errMsg := fmt.Sprintf("Could not unmarshal manifest to get layer order: %s", err)
return []string{}, errors.New(errMsg)
}
return imageManifest[0].Layers, nil
}
func unpackDockerSave(tarPath string, target string) error {
if _, ok := os.Stat(target); ok != nil {
os.MkdirAll(target, 0777)
}
tempLayerDir := target + "-temp"
err := UnTar(tarPath, tempLayerDir)
if err != nil {
errMsg := fmt.Sprintf("Could not unpack saved Docker image %s: %s", tarPath, err)
return errors.New(errMsg)
}
manifest := filepath.Join(tempLayerDir, "manifest.json")
layers, err := getLayersFromManifest(manifest)
if err != nil {
return err
}
for _, layer := range layers {
layerTar := filepath.Join(tempLayerDir, layer)
if _, err := os.Stat(layerTar); err != nil {
glog.Infof("Did not unpack layer %s because no layer.tar found", layer)
continue
}
err = UnTar(layerTar, target)
if err != nil {
glog.Errorf("Could not unpack layer %s: %s", layer, err)
}
}
err = os.RemoveAll(tempLayerDir)
if err != nil {
glog.Errorf("Error deleting temp image layer filesystem: %s", err)
}
return nil
}
// ImageToTar writes an image to a .tar file
func saveImageToTar(cli client.APIClient, image, tarName string) (string, error) {
glog.Info("Saving image")
imgBytes, err := cli.ImageSave(context.Background(), []string{image})
if err != nil {
return "", err
}
defer imgBytes.Close()
newpath := tarName + ".tar"
return newpath, copyToFile(newpath, imgBytes)
}
<file_sep>/cmd/analyze.go
/*
Copyright 2017 Google, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"errors"
"fmt"
"os"
"strings"
"github.com/GoogleCloudPlatform/container-diff/differs"
"github.com/GoogleCloudPlatform/container-diff/utils"
"github.com/golang/glog"
"github.com/spf13/cobra"
)
var analyzeCmd = &cobra.Command{
Use: "analyze",
Short: "Analyzes an image: [image]",
Long: `Analyzes an image using the specifed analyzers as indicated via flags (see documentation for available ones).`,
Args: func(cmd *cobra.Command, args []string) error {
if err := validateArgs(args, checkAnalyzeArgNum, checkArgType); err != nil {
return errors.New(err.Error())
}
if err := checkIfValidAnalyzer(types); err != nil {
return errors.New(err.Error())
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
if err := analyzeImage(args[0], strings.Split(types, ",")); err != nil {
glog.Error(err)
os.Exit(1)
}
},
}
func checkAnalyzeArgNum(args []string) error {
if len(args) != 1 {
return errors.New("'analyze' requires one image as an argument: container analyze [image]")
}
return nil
}
func analyzeImage(imageArg string, analyzerArgs []string) error {
cli, err := NewClient()
if err != nil {
return fmt.Errorf("Error getting docker client for differ: %s", err)
}
defer cli.Close()
ip := utils.ImagePrepper{
Source: imageArg,
Client: cli,
}
image, err := ip.GetImage()
if !save {
defer cleanupImage(image)
}
if err != nil {
glog.Error(err.Error())
return errors.New("Could not perform image analysis")
}
analyzeTypes, err := differs.GetAnalyzers(analyzerArgs)
if err != nil {
glog.Error(err.Error())
return errors.New("Could not perform image analysis")
}
req := differs.SingleRequest{image, analyzeTypes}
analyses, err := req.GetAnalysis()
if err != nil {
glog.Error(err.Error())
return errors.New("Could not perform image analysis")
}
glog.Info("Retrieving analyses")
outputResults(analyses)
if save {
glog.Infof("Image was saved at %s", image.FSPath)
}
return nil
}
func init() {
RootCmd.AddCommand(analyzeCmd)
addSharedFlags(analyzeCmd)
}
<file_sep>/utils/diff_utils.go
/*
Copyright 2017 Google, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"github.com/pmezard/go-difflib/difflib"
)
// Modification of difflib's unified differ
func GetAdditions(a, b []string) []string {
matcher := difflib.NewMatcher(a, b)
differences := matcher.GetGroupedOpCodes(0)
adds := []string{}
for _, group := range differences {
for _, opCode := range group {
j1, j2 := opCode.J1, opCode.J2
if opCode.Tag == 'r' || opCode.Tag == 'i' {
for _, line := range b[j1:j2] {
adds = append(adds, line)
}
}
}
}
return adds
}
func GetDeletions(a, b []string) []string {
matcher := difflib.NewMatcher(a, b)
differences := matcher.GetGroupedOpCodes(0)
dels := []string{}
for _, group := range differences {
for _, opCode := range group {
i1, i2 := opCode.I1, opCode.I2
if opCode.Tag == 'r' || opCode.Tag == 'd' {
for _, line := range a[i1:i2] {
dels = append(dels, line)
}
}
}
}
return dels
}
func GetMatches(a, b []string) []string {
matcher := difflib.NewMatcher(a, b)
matchindexes := matcher.GetMatchingBlocks()
matches := []string{}
for i, match := range matchindexes {
if i != len(matchindexes)-1 {
start := match.A
end := match.A + match.Size
for _, line := range a[start:end] {
matches = append(matches, line)
}
}
}
return matches
}
<file_sep>/utils/image_utils_test.go
/*
Copyright 2017 Google, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"testing"
)
type imageTestPair struct {
input string
expectedOutput bool
}
func TestCheckImageID(t *testing.T) {
for _, test := range []imageTestPair{
{input: "123456789012", expectedOutput: true},
{input: "gcr.io/repo/image", expectedOutput: false},
{input: "testTars/la-croix1.tar", expectedOutput: false},
} {
output := CheckImageID(test.input)
if output != test.expectedOutput {
if test.expectedOutput {
t.Errorf("Expected input to be image ID but %s tested false", test.input)
} else {
t.Errorf("Didn't expect input to be an image ID but %s tested true", test.input)
}
}
}
}
func TestCheckImageTar(t *testing.T) {
for _, test := range []imageTestPair{
{input: "123456789012", expectedOutput: false},
{input: "gcr.io/repo/image", expectedOutput: false},
{input: "testTars/la-croix1.tar", expectedOutput: true},
} {
output := CheckTar(test.input)
if output != test.expectedOutput {
if test.expectedOutput {
t.Errorf("Expected input to be a tar file but %s tested false", test.input)
} else {
t.Errorf("Didn't expect input to be a tar file but %s tested true", test.input)
}
}
}
}
func TestCheckImageURL(t *testing.T) {
for _, test := range []imageTestPair{
{input: "123456789012", expectedOutput: false},
{input: "gcr.io/repo/image", expectedOutput: true},
{input: "testTars/la-croix1.tar", expectedOutput: false},
} {
output := CheckImageURL(test.input)
if output != test.expectedOutput {
if test.expectedOutput {
t.Errorf("Expected input to be a tar file but %s tested false", test.input)
} else {
t.Errorf("Didn't expect input to be a tar file but %s tested true", test.input)
}
}
}
}
| c5f0a37ed1a4af04eb2182e7be788615d44ba4b9 | [
"Go"
] | 9 | Go | bossjones/container-diff | 982666541251d235c2760c76a02cfec8ee10a241 | b80ba298509bd82f28a8dcb6ff8e2a4a72a0b9e4 |
refs/heads/master | <repo_name>Byte-Code/aws-budget<file_sep>/README.md
# Free Template for AWS CloudFormation
Aws budget exceed notification.
# aws-budget
This template describes a budget entity and send notifications to subscriber email when treshold is exceeded.
[Can be run directly from the following link](https://console.aws.amazon.com/cloudformation/home#/stacks/create/review?templateURL=https://cloufdormationbc.s3-eu-west-1.amazonaws.com/Stacks/budget/budget.yaml&stackName=BudgetAlert&param_Name=BudgetAlert&param_Amount=80)
# awsbudget.sh
A bash script that accomplish the creation of cloudformation stack.
## License
All templates are published under Apache License Version 2.0.
<file_sep>/awsbudget.sh
#!/bin/bash
#
#
# Aws Budgets cretion script
#
#
# Basic Utilities
# Write colored output recieve "colournumber" "message"
function colecho(){
SETCOLOR_SUCCESS="echo -en \\033[1;32m";
SETCOLOR_NORMAL="echo -en \\033[0;39m";
SETCOLOR_FAILURE="echo -en \\033[1;31m";
SETCOLOR_WARNING="echo -en \\033[1;33m";
[ "$1" == "" ] && $SETCOLOR_NORMAL;
[ "$1" == "0" ] && $SETCOLOR_SUCCESS;
[ "$1" == "1" ] && $SETCOLOR_FAILURE;
[ "$1" == "2" ] && $SETCOLOR_WARNING;
[ "$2" == "" ] || echo "$2";
$SETCOLOR_NORMAL;
}
function error(){
[ "$1" == "" ] && usage || colecho "1" "$1";
exit 1;
}
function usage(){
PNAME=`basename $0`
cat << EOF
Disclaimer:
This script will create a cloudformation stack that manages alert for a budget entity.
Usage:
$PNAME [OPTION]
Options:
-h|H
Print this help and exit
-a|A
Amount of your budget is for the month (mandatory)
-e|E
Email address to send notifications to (mandatory)
EOF
exit 0;
}
function createcf(){
cat <<EOF
AWSTemplateFormatVersion: '2010-09-09'
Description: Creates an AWS budget and notifies you when you exceed thresholds.
Parameters:
Name:
Description: The name of the budget
Type: String
Default: Budget
Amount:
Description: What your budget is for the month
Type: Number
Currency:
Description: The currency of your budget
Type: String
Default: USD
FirstThreshold:
Description: The first threshold at which you'll receive a notification
Type: Number
Default: 75
SecondThreshold:
Description: The second threshold at which you'll receive a notification
Type: Number
Default: 99
Email:
Description: The email address to send notifications to
Type: String
# Order the parameters in a way that makes more sense (not alphabetized)
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Parameters:
- Name
- Amount
- Currency
- FirstThreshold
- SecondThreshold
- Email
Resources:
Budget:
Type: AWS::Budgets::Budget
Properties:
Budget:
BudgetName: !Ref Name
BudgetLimit:
Amount: !Ref Amount
Unit: !Ref Currency
TimeUnit: MONTHLY
BudgetType: COST
# "A budget can have up to five notifications. Each notification must have at least one subscriber.
# A notification can have one SNS subscriber and up to ten email subscribers, for a total of 11 subscribers."
NotificationsWithSubscribers:
- Notification:
ComparisonOperator: GREATER_THAN
NotificationType: ACTUAL
Threshold: !Ref FirstThreshold
ThresholdType: PERCENTAGE
Subscribers:
- SubscriptionType: EMAIL
Address: !Ref Email
- Notification:
ComparisonOperator: GREATER_THAN
NotificationType: ACTUAL
Threshold: !Ref SecondThreshold
ThresholdType: PERCENTAGE
Subscribers:
- SubscriptionType: EMAIL
Address: !Ref Email
- Notification:
ComparisonOperator: GREATER_THAN
NotificationType: FORECASTED
Threshold: 100
ThresholdType: PERCENTAGE
Subscribers:
- SubscriptionType: EMAIL
Address: !Ref Email
EOF
}
TMPNAME=./.`basename $0`.$$;
# Options Parser
while getopts "hHa:A:e:E:" opt "$@"
do
case $opt in
a|A) AMOUNT=$OPTARG;;
e|E) EMAIL=$OPTARG;;
h|H) usage;;
*) error "Unknown option!";
esac
done
[ -z "${AMOUNT}" ] && error "Budget for the month is mandatory";
[ -z "${EMAIL}" ] && error "Email address is mandatory";
[ $AMOUNT -eq $AMOUNT 2>/dev/null ] || error "Budget is not a number";
AWS_BIN=$(which aws 2> /dev/null)
[ -z "${AWS_BIN}" ] && error "Aws Cli is missing, install awscli and retry";
NAME=$( echo "${EMAIL}" | tr -dc '[:alnum:]'; )
APPDN="Budget${NAME}${AMOUNT}";
CURRENCY="USD";
FSTTSHD="80";
SNDTSHD="95";
createcf > ${TMPNAME};
aws cloudformation create-stack --stack-name ${APPDN} \
--template-body file://${TMPNAME} \
--parameters \
ParameterKey=Name,ParameterValue=${NAME} \
ParameterKey=Amount,ParameterValue=${AMOUNT} \
ParameterKey=Currency,ParameterValue=${CURRENCY} \
ParameterKey=FirstThreshold,ParameterValue=${FSTTSHD} \
ParameterKey=SecondThreshold,ParameterValue=${SNDTSHD} \
ParameterKey=Email,ParameterValue=${EMAIL}
[ -f "${TMPNAME}" ] && rm -f ${TMPNAME};
| 2626fc61f5fc3bbe9f7a954b435454d9a848ed6c | [
"Markdown",
"Shell"
] | 2 | Markdown | Byte-Code/aws-budget | 4484d183a56ca6c860f086479ced614736795fac | b00d65ed908e2a91167d35fc33bc804175e805ec |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.